Fundamental Data Types
INT = Whole numbers
FLOAT = 1.0 or fractions
BOOL = true or false
STR = Letters/Text or “text” (longer strings can be added using three """
marks on each end of the text)
LIST = ordered sequence of objects that can be any type. Similar to Arrays.
TUPLE = Immutable lists (basically)
SET = unordered collections of unique objects
DICT= a data type & structure, They appear similar to advanced arrays in JS. Can edit within the array of data as a function.
NOT= the opposite. Can be used to determine opposite booleans.
IS= exactly the thing
type()
is a function that will allow you to check data types
Python follows an operator precidence, or PEMDAS as most might understand it. (Parenthesis, Exponents, Mulitplication, Division, Addition, Subtraction). This is the order in which the computer calculates math. Still starts from 0 as most computers do.
COMPLEX = for complex math bin() = is used to return the binary representation of a number. Represented after the letter b.
Classes –> Custom Types
Variables are made pretty simple.
In Python, you can create values based on a certain set of rules.
Here are some things to remember:
-
snake_case: use underscores
-
start with lowercase or underscore
-
Letters, numbers, underscores. You cannot start a variable with a number
-
Case sensitive: Meaning
_variable
is different than_Variable
-
Don’t overwrite keywords: if it’s already a function labeled within Python or a module you can’t use it.
Naming things in Python well is a skill. Learn to do it well.
Marking constants in a specific manner in order to create consistency. Since you can overwrite variables in Python.
You can name multiple variables and assign value to them like so a,b,c = 1,2,3
. This method can be useful in some circumstances.
Expressions vs Statements
`iq = 100
user_age = iq / 5`
The expression is the line iq / 5
and then the statement is user_age = iq / 5
Augmented Assignment Operator
`a_value = 5
a_value = 5 + 2`
Instead of adding to a value like so. You can instead add to a variable this way.
`a_value += 2`
This can be done with most other mathematic operators in Python. Like subtraction (-=
) & multiplication (*=
).
Type Conversion
You can turn numbers or integers into strings by going a = str(100)
. Or int(a)
to find the integers within the string.
Escape Sequence
\
allows you to use "
within a string without breaking the string. Like so:
`"That\'s all folks!"`
\t
can also be used to add a tab space to the beginning of the string/text when it prints. And \n
will create a new line entirely, rather than tabbing on the same line.
Formatted Strings
These are ways in which you can use variables to concatinate strings together.
`name = 'Matty'
print('Hey ' + name)`
You could do this with multiple variables like so:
`name = 'Matty'
age = 30
print('Hey ' + name + 'your age is ' + str(age))`
Thus, you can do this to set values to concatinate together in a new string.
Be sure to add the str()
to your variables with integers in them.
A faster way of doing the above example is adding f
to the beginning of the string.
print(f"Hey {name}. You're age is {age}.
Much cleaner to look at. And is the newer way of doing things in Python 3.
The alternative in Python 2 (still supported in 3) looks like this:
print('Hey {}. You are {} years old'.format(name, age))
Keep in mind that the .format
portion MUST be within the brackets to run correctly.
You can also replace the names of the variables with the numbers they are in accordance with the order they appear in.
In the above example. name is 0
and age is 1
.
String Indexes
`'me me me'
01234567`
This is an example of an index of a string. The numbers here represent each space within the string.
`selfish = 'me me me'
#01234567
print(selfish[0])`
This returns m
[start:stop]
this would be how one calls a range of these numbers in the index.
IE = [0:4] = me me
[start:stop:stepover
this third function allows you to skip over numbers. So if it looked like [0:3:1]
it would go through 0 - 2 normally. And stop at 3.
Replace 1 with 2 or 3. And it skips over that number each step through.
You can leave one or more of these parameters blank. It will perform [::1]
in the default manner. Going through the entire string once.
If you throw a negative number in the function like so print(selfish[-3])
it will print 5
. This is because now it is going backwards through the string. Rather than starting at 0.
print(selfish[::-1])
will actually reverse the entire string. Starting from position 7 and going back to 0.
Immutability
Strings in Python are immutable. They cannot be changed.
A variable can be changed, a string assigned to that variable can only be replaced. Thus you cannot change the 0
position to another number or string etc. Not until that entire string is replaced.
Built In Functions/Methods
print(len("Herooooooooooooo!!!"))
will return with an integer that represents the amount of letters in this string.
shout = "Herooooooooooooo!!!"
print(shout[0:9])
Methods
Similar to functions, but are owned by something else.
.format()
is an example of a method within Python.
These can be performed on strings.
`quote = "To be, or not to be? That is the question.
print(quote.upper())`
This returns: “TO BE OR NOT TO BE? THAT IS THE QUESTION.”
.capitalize()
= Capitalizes the first letter in sentence.
.lower()
= all lowercase letters.
.replace('be', 'me'))
= finds every instance of text and replaces it.
Booleans
bool
Can only be true or false.
As integers they are 0
and 1
Dictionaries
These are just Pythons answer to Advanced arrays.
Strings, numbers, and booleans are immutable. Meaning they cannot change. While a list (or Array in Python) can in fact be changed. A dictonary key must be immutable.
Tuples
Immutable lists
my_tuple = (1,2,3,4,5,6)
You cannot sort, reverse, add to tuples the same way you can edit lists. Because they are immutable. But they can be called like a list. print(5 in my_tuple)
returns True. print(my_tuple[2])
returns 3
as it is the second in the list.
Make’s code simpler. But it is less flexible.
Tuples are valid keys within dictionaries, since they are immutable.
Set
my_set = {1,2,3,4,5}
Printing the above set would return as if it were an array. However, add an extra 5 to the list and print it. And it will not return the extra 5. This is because it will only return the unique sets/items.
Using the function set
before printing a variables output will convert a list into a set. (print(set(my_list))
) will return the unique numbers within the list.
Ternary Operator
A conditional statement within a variable.
can_message = "message allowed" if is_friend else "not allowed to message"
This can be done in one line and can be effective for code refactoring.
Short Circuting
`is_Friend = True
is_User = True
if is_Friend or is_User:
print('best friends forever')`
As I understand it. Short circuting is the process in which the computer reads a conditional statement and determines whether or not it should continue reading the line if one condition gives them the output it’s looking for.
You use or to determine whether one value is true or the other. In this case, if is_Friend
is determined to be true, then the code runs. As long as one condition is met. Then the code may run.
and works in the same way. Since it seeks to determine if both variables are true. And if one is false. It will skip the remaining code.
Logical Operators
== += /= !=
For Loops
`for item in 'Elden Ring':
print(item)`
The iterable in this line of code would be Elden Ring
here. But for
makes a variable with item
then declares it will be in Elden Ring
. So the code will execute the following code to that iterable and loop until the process is done or parameters are met.
Iterables
it is an object or collection that can be iterated over.
Iterated means –> One by one check of each item in the collection.
.range()
.range()
is a way in which you can count and print numbers within a set range and direction.
Only works with integers.
Enumerate
Useful if you need the index counter of the item you are looping through.
`for i, char in enumerate((1,2,3)):
print (i, char)
if char == 50:
print(f'index of 50 is: {i}')`
The i
in this script represents the index number. Or in what order did the computer count this number.
While Loops
This is how you create infinite loops in your code.
Use break
statements to cut off the while
loops.
`i = 0
while i < 50:
print(i)
i += 1`
To jump out of a loop, you either turn the condition false. Or use a break statement.
else
conditionals can be used as well. But they are not common. Used in favor of simple print statements. And without break
statments. The code will only run when the condition is met.
For iteration of iterable items in a single loop, for
loops are great. If you are not sure how many loops are needed, or simply want to repeat a task as many times as it takes. while
loops might be better suited.
Break, Continue, Pass
Break: stops the loop, breaks the line Continue: Repeats the loop from this statement. Pass: basically a placeholder. Good for empty loops that you haven’t figured out yet.
Functions
Create a function in Python by using def
or define. Which signifies defining a function.
`def say_hello():
print("Hello!")`
You can call functions by using the name with parenthesis say_hello()
. The parenthesis is important to signify the calling of the function.
Functions are cool ways to store repeatable code and call to it whenever it is needed. No copy and paste!
Arguments & Parameters
def say_hello(name, emoji):
The variables inside the brackets are parameters. And they are what the function receives by calling other variables.
Arguments look like this say_hello(Matthew, 😂)
The argument is of course the actual input that is entered into the function. Though I am sure you can set a variable with the names in the code used in the examples. To link functions together.
Positional arguments, are arguments that are required to be in the right positions to work correctly.
Keyword arguments
say_hello(emoji=😂, name=Matty)
This directly defines what each parameter is. Apparently this can make things more complicated than it needs to be. But it’s cool.
Default Parameters
When defining the function. You can set predetermined parameters for the function if there are none applied to it when the function is called.
say_hello()
would return whatever parameters were set. If none, it would likely return an error or nothing.
In Andre’s example, (def say_hello(name='Darth Vader', emoji='😂')
), it would call these parameters and print the results of the function.
Return
`def total(num1, num2):
return num1 + num2
print (total(10,5))`
Without the return function here, the actual math isn’t done within the function. With return
in the mix here, it asks the math to return the total from the function.
Functions should either:
-
Do something really well!
-
Should return something!
Methods vs Functions
Methods are something that already exist within Python. Tools that you can use in conjunction with any other data type available.
Functions allow you to store your own code. While Methods are just built into Python. Or you install them.
Docstrings
You can use functions to create a docstring.
`def test(a):
'''
Information about the function can be stored here.
'''
print(a)`
This allows you to add comments within functions for collaborative purposes.
help
function allows you to check and see what a function does in the console.
Magic Method or Dunder Method = print(test.__doc__)
this prints out the code as it is written within the code.
*args & **kwargs
`def super_func(*args):
print(*args)
return sum(args)
super_func(1,2,3,4,5)`
This will print out the arguments. At least while the *
remains before args
. This allows you to add as many arguments to the parameters as you want.
By printing it WITHOUT the *
, it will instead return a tuple
. Adding **kwargs
and setting custom parameters will return a dictionary
when printed.
Walrus Operator
:=
assigns variables as part of a larger expression
`a = "hello!"
if ((n := len(a)) > 10):
print(f"too long {n} elements")`
The if
statement assigns an expression to a value that can then be used within the f
statement to fill the value with the result of the calculation.
Scope
What variables do I have access to?
This is an idea that the code that rests within a function doesn’t have the same scope as the scope of the entire file.
Since Python is best known for it’s clean and organized format of code, each indent plays an important role in determining scope.
1) Start with local scope
2) Parent local?
3) Global scope
4) Built in Python functions
Global
Using the global
function, allows you to use global variables within custom functions!
Andre argues that this is bad form. And instead suggests:
`total = 0
def count(total):
total += 1
return total
print(count(count(count(total))))`
Rather than using global total
putting the variable as an argument of the function allows you to access the global scope.
nonlocal
This is a function that essentially reassigns the value of a variable based on it’s scope.
`def outer():
x = "local
def inner():
nonlocal x
x = "nonlocal"
print("inner: ", x)
inner()
print("outer: ", x)
outer()`
Nonlocal essentially ignores the parent scope in favor of the new local scope.