Python Basics
Variables in Python
We can create a new Python variable by assigning a value to a label, using the = assignment operator.
In this example we assign a string with the value "Roger" to the name label:
name = "Roger"
Here's an example with a number:
age = 8
A variable name can be composed of characters, numbers, and the _ underscore character. It can't start with a number. These are all valid variable names:
name1
AGE
aGE
a11111
my_name
_name
These are invalid variable names:
123
test!
name%
Other than that, anything is valid unless it's a Python keyword. There are some keywords like for, if, while, import and more.
There's no need to memorize them, as Python will alert you if you use one of those as a variable, and you will gradually recognize them as part of the Python programming language syntax.
Expressions and statements in Python
We can expression any sort of code that returns a value. For example
1 + 1
"Roger"
A statement, on the other hand, is an operation on a value. For example these are 2 statements:
name = "Roger"
print(name)
A program is formed by a series of statements. Each statement is put on its own line, but you can use a semicolon to have more than one statement on a single line:
name = "Roger"; print(name)
Comments
In a Python program, everything after a hash mark is ignored, and considered a comment:
#this is a commented line
name = "Roger" # this is an inline comment
Indentation in Python
Indentation in Python is meaningful.
You cannot indent randomly like this:
name = "Flavio"
print(name)
Some other languages do not have meaningful whitespace, but in Python, indentation matters.
In this case, if you try to run this program you would get a IndentationError: unexpected indent error, because indenting has a special meaning.
Everything indented belongs to a block, like a control statement or conditional block, or a function or class body. We'll see more about those later on.
Data Types in Python
Python has several built-in types.
If you create the name variable assigning it the value "Roger", automatically this variable now represents a String data type.
name = "Roger"
You can check the type of a variable by using the type() function, passing the variable as an argument, and then comparing the result to str:
name = "Roger"
type(name) == str #True
Or using isinstance():
name = "Roger"
isinstance(name, str) #True
Notice that to see the True value in Python, outside of a REPL, you need to wrap this code inside print(), but for clarity I avoid using it.
We used the str class here, but the same works for other data types.
First, we have numbers. Integer numbers are represented using the int class. Floating point numbers (fractions) are of type float:
age = 1
type(age) == int #True
fraction = 0.1
type(fraction) == float #True
You saw how to create a type from a value literal, like this:
name = "Flavio"
age = 20
Python automatically detects the type from the value type.
You can also create a variable of a specific type by using the class constructor, passing a value literal or a variable name:
name = str("Flavio")
anotherName = str(name)
You can also convert from one type to another by using the class constructor. Python will try to determine the correct value, for example extracting a number from a string:
age = int("20")
print(age) #20
fraction = 0.1
intFraction = int(fraction)
print(intFraction) #0
This is called casting. Of course this conversion might not always work depending on the value passed. If you write test instead of 20 in the above string, you'll get a ValueError: invalid literal for int() with base 10: 'test' error.
Those are just the basics of types. We have a lot more types in Python:
and more!
Operators in Python
Python operators are symbols that we use to run operations upon values and variables.
We can divide operators based on the kind of operation they perform:
plus some interesting ones like is and in.
Assignment operator in Python
The assignment operator is used to assign a value to a variable:
age = 8
Or to assign a variable value to another variable:
age = 8
anotherVariable = age
Since Python 3.8, the := walrus operator is used to assign a value to a variable as part of another operation.
Arithmetic operators in Python
Python has a number of arithmetic operators: +, -, *, / (division), % (remainder), ** (exponentiation) and // (floor division):
1 + 1 #2
2 - 1 #1
2 * 2 #4
4 / 2 #2
4 % 3 #1
4 ** 2 #16
4 // 2 #2
Note that you don't need a space between the operands, but it's good for readability.
- also works as a unary minus operator:
print(-4) #-4
+ is also used to concatenate String values:
"Roger" + " is a good dog"
#Roger is a good dog
We can combine the assignment operator with arithmetic operators:
Example:
age = 8
age += 1
# age is now 9
Comparison operators in Python
Python defines a few comparison operators:
You can use those operators to get a boolean value (True or False) depending on the result:
a = 1
b = 2
a == b #False
a != b #True
a > b #False
a <= b #True
Boolean operators in Python
Python gives us the following boolean operators:
When working with True or False attributes, those work like logical AND, OR and NOT, and are often used in the if conditional expression evaluation:
condition1 = True
condition2 = False
not condition1 #False
condition1 and condition2 #False
condition1 or condition2 #True
Otherwise, pay attention to a possible source of confusion:
or used in an expression returns the value of the first operand that is not a falsy value (False, 0, '', []..). Otherwise it returns the last operand.
print(0 or 1) ## 1
print(False or 'hey') ## 'hey'
print('hi' or 'hey') ## 'hi'
print([] or False) ## 'False'
print(False or []) ## '[]'
The Python docs describe it as if x is false, then y, else x.
and only evaluates the second argument if the first one is true. So if the first argument is falsy (False, 0, '', []..), it returns that argument. Otherwise it evaluates the second argument:
print(0 and 1) ## 0
print(1 and 0) ## 0
print(False and 'hey') ## False
print('hi' and 'hey') ## 'hey'
print([] and False ) ## []
print(False and [] ) ## False
The Python docs describe it as if x is false, then x, else y.
Bitwise operators in Python
Some operators are used to work on bits and binary numbers:
Bitwise operators are rarely used, only in very specific situations, but they are worth mentioning.
is and in in Python
is is called the identity operator. It is used to compare two objects and returns true if both are the same object. More on objects later.
in is called the membership operator. Is used to tell if a value is contained in a list, or another sequence. More on lists and other sequences later.
The Ternary Operator in Python
The ternary operator in Python allows you to quickly define a conditional.
Let's say you have a function that compares an age variable to the 18 value, and returns True or False depending on the result.
Instead of writing:
def is_adult(age):
if age > 18:
return True
else:
return False
You can implement it with the ternary operator in this way:
def is_adult(age):
return True if age > 18 else False
First you define the result if the condition is True, then you evaluate the condition, then you define the result if the condition is false:
<result_if_true> if <condition> else <result_if_false>
Strings in Python
A string in Python is a series of characters enclosed in quotes or double quotes:
"Roger"
'Roger'
You can assign a string value to a variable:
name = "Roger"
You can concatenate two strings using the + operator:
phrase = "Roger" + " is a good dog"
You can append to a string using +=:
name = "Roger"
name += " is a good dog"
print(name) #Roger is a good dog
You can convert a number to a string using the str class constructor:
str(8) #"8"
This is essential to concatenate a number to a string:
print("Roger is " + str(8) + " years old") #Roger is 8 years old
A string can be multi-line when defined with a special syntax, enclosing the string in a set of 3 quotes:
print("""Roger is
8
years old
""")
#double quotes, or single quotes
print('''
Roger is
8
years old
''')
A string has a set of built-in methods, like:
and many more.
None of those methods alter the original string. They return a new, modified string instead. For example:
name = "Roger"
print(name.lower()) #"roger"
print(name) #"Roger"
You can use some global functions to work with strings, too.
In particular I think of len(), which gives you the length of a string:
name = "Roger"
print(len(name)) #5
The in operator lets you check if a string contains a substring:
name = "Roger"
print("ger" in name) #True
Escaping is a way to add special characters into a string.
For example, how do you add a double quote into a string that's wrapped into double quotes?
name = "Roger"
"Ro"Ger" will not work, as Python will think the string ends at "Ro".
The way to go is to escape the double quote inside the string, with the \ backslash character:
name = "Ro\"ger"
This applies to single quotes too \', and for special formatting characters like \t for tab, \n for new line and \\ for the backslash.
Given a string, you can get its characters using square brackets to get a specific item, given its index, starting from 0:
name = "Roger"
name[0] #'R'
name[1] #'o'
name[2] #'g'
Using a negative number will start counting from the end:
name = "Roger"
name[-1] #"r"
You can also use a range, using what we call slicing:
name = "Roger"
name[0:2] #"Ro"
name[:2] #"Ro"
name[2:] #"ger"
Booleans in Python
Python provides the bool type, which can have two values: True and False (capitalized).
done = False
done = True
Booleans are especially useful with conditional control structures like if statements:
done = True
if done:
# run some code here
else:
# run some other code
When evaluating a value for True or False, if the value is not a bool we have some rules depending on the type we're checking:
You can check if a value is a boolean in this way:
done = True
type(done) == bool #True
Or using isinstance(), passing 2 arguments: the variable, and the bool class:
done = True
isinstance(done, bool) #True
The global any() function is also very useful when working with booleans, as it returns True if any of the values of the iterable (list, for example) passed as argument are True:
book_1_read = True
book_2_read = False
read_any_book = any([book_1_read, book_2_read])
The global all() function is same, but returns True if all of the values passed to it are True:
ingredients_purchased = True
meal_cooked = False
ready_to_serve = all([ingredients_purchased, meal_cooked])
Numbers in Python
Numbers in Python can be of 3 types: int, float and complex.
Integer numbers in Python
Integer numbers are represented using the int class. You can define an integer using a value literal:
age = 8
You can also define an integer number using the int() constructor:
age = int(8)
To check if a variable is of type int, you can use the type() global function:
type(age) == int #True
Floating point numbers in Python
Floating point numbers (fractions) are of type float. You can define an integer using a value literal:
fraction = 0.1
Or using the float() constructor:
fraction = float(0.1)
To check if a variable is of type float, you can use the type() global function:
type(fraction) == float #True
Complex numbers in Python
Complex numbers are of type complex.
You can define them using a value literal:
complexNumber = 2+3j
or using the complex() constructor:
complexNumber = complex(2, 3)
Once you have a complex number, you can get its real and imaginary part:
complexNumber.real #2.0
complexNumber.imag #3.0
Again, to check if a variable is of type complex, you can use the type() global function:
type(complexNumber) == complex #True
Arithmetic operations on numbers in Python
You can perform arithmetic operations on numbers, using the arithmetic operators: +, -, *, / (division), % (remainder), ** (exponentiation) and // (floor division):
1 + 1 #2
2 - 1 #1
2 * 2 #4
4 / 2 #2
4 % 3 #1
4 ** 2 #16
4 // 2 #2
and you can use the compound assignment operators
to quickly perform operations on variables, too:
age = 8
age += 1
Built-in Functions in Python
There are 2 built-in functions that help with numbers:
abs() returns the absolute value of a number.
round() given a number, returns its value rounded to the nearest integer:
round(0.12) #0
You can specify a second parameter to set the decimal point's precision:
round(0.12, 1) #0.1
Several other math utility functions and constants are provided by the Python standard library:
We'll explore some of those separately later on.
Constants in Python
Python has no way to enforce that a variable should be a constant.
The nearest you can get is to use an enum:
class Constants(Enum):
WIDTH = 1024
HEIGHT = 256
And get to each value using, for example, Constants.WIDTH.value.
No one can reassign that value.
Otherwise if you want to rely on naming conventions, you can adhere to this one: declare variables that should never change uppercase:
WIDTH = 1024
No one will prevent you from overwriting this value, and Python will not stop it.
That's what most Python code does that you will see.
Enums in Python
Enums are readable names that are bound to a constant value.
To use enums, import Enum from the enum standard library module:
from enum import Enum
Then you can initialize a new enum in this way:
class State(Enum):
INACTIVE = 0
ACTIVE = 1
Once you do so, you can reference State.INACTIVE and State.ACTIVE, and they serve as constants.
Now if you try to print State.ACTIVE for example:
print(State.ACTIVE)
it will not return 1, but State.ACTIVE.
The same value can be reached by the number assigned in the enum: print(State(1)) will return State.ACTIVE. Same for using the square brackets notation State['ACTIVE'].
You can, however, get the value using State.ACTIVE.value.
You can list all the possible values of an enum:
list(State) # [<State.INACTIVE: 0>, <State.ACTIVE: 1>]
You can count them:
len(State) # 2