Introduction to Python
Print, variables, control flow, etc.
This is a Jupyter notebook in which you can mix cells of Python code and cells of text. You can add boxes with the + button above, and move the boxes with the Up/Down arrows.
Cell execution
To execute a Python code in a cell, you can click on it and then do one of the following:
- Click on the Run/Play button in the toolbar
- Click on the menu Cell > Run Cells
- Click on the menu Tools > Keyboard shortcuts
- Discover that you can also press Alt Enter or Ctrl Enter
The type of a cell is either Code or Markdown, where Markdown is a simple method to format text (https://en.wikipedia.org/wiki/Markdown).
The current cell is a Markdown text. To access the original Markdown text, double-click on this cell. To pretty visualize this Markdown cell, you have to follow the same steps illustrated above for a code cell, asking for running the cell.
Upload and run notebooks
You can UPLOAD and RUN this and other notebooks by using the Google cloud services. For example, open with Chrome and connect with your stud.unive.it account to: https://colab.research.google.com.
If you don't want to use Google Colab, you can use pip to install the jupyter-notebook library, download the notebook, and run it locally as explained in this tutorial.
A simple program
People usually introduce courses on computer programming with a simple program that prints "Hello, World!" on the screen.
hello.py python3 hello.py
Just write the following in a text file, save the file, and then execute the command in a console.
In [ ]: print('Hello World!')
Hello World!
A program that prints multiple lines
You can also print many lines. Python will execute a line after the other, following the sequential order fixed by the programmer. The sequence of characters between a pair of double/single quotation marks are called strings, and are printed on the screen as they are. For example:
"Hello, World!" 'Hello, World!'
The function print can be invoked with many parameters, e.g., multiple strings. Python concatenates them one after another, thus producing a single string. Then it appends a newline character at the end (newline), and print on the screen the final result.
In [ ]:
print('Hello!', 'Giulio!') # This is a comment.
print("I'm a computer...") # This is another comment.
print('How are you?')
Hello! Giulio!
I'm a computer...
How are you?
Print function
print() is a built-in function. A function is a small sub-program with a name, its own input parameters, an output, just like a mathematical function. The input is delimited by parentheses. Function print does not have an output, but it has a side-effect: it displays its input parameters on the screen. Built-in means that someone else wrote its code, and it is now provided to you for free as part of Python.
You can define your own functions. We will do this a bit later. Whenever you encounter a function, you should ask yourself which are the input parameters, what is the output, and what is the function doing. The answer can be found within the documentation. Check https://docs.python.org/3/library/functions.html#print.
print() takes an arbitrary number of parameters, which is not usual; normally, functions take a maximum number of parameters. Parameters can be named or not named, meaning that when you pass them to the function, you define them with an ' ' expression. With the not named parameters, strings that will be printed, one after the other in the order they were passed, are separated by space. The named parameters are modifiers of the behavior of the function, or of the printed string. Parameters are separated by a comma. After the last item to print, a newline is added.
In [ ]:
print('Hello', 'World', 'Paolo', 'University', sep="?", end='\n')
print('Hello', 'World', sep='--') # change the separator of the output words
print('Hello World', end=' ') # remove the newline at the end
print('Hello World')
Hello?World?Paolo?University
Hello--World
Hello World Hello World
Syntax of print()
The actual syntax of the function accepts 5 parameters:
print(object=..., sep=..., end=..., file=..., flush=...)
Where:
- object: value(s) to be printed
- sep (optional): allows us to separate multiple objects inside
- end (optional): allows us to add specific values to the end of each object, like new line "\n", tab "\t", space " "
- file (optional): where the values are printed. Its default value is sys.stdout (screen)
- flush (optional): boolean specifying if the output is flushed or buffered. Default: False
Control flow
We wrote your first program, i.e., a sequence of instructions that specifies a computation. The computer starts off by executing the first instruction, then the next, and so on, in the order that they appear in the program. It only stops executing the program after the last instruction is completed. We refer to the order in which the computer executes instructions as the control flow. When the computer is executing (or running) a particular instruction, we can say that control is at that instruction.
Try to use Python Tutor (http://pythontutor.com/) to run the code above, to see how the sequential control flow works, passing from a statement to the next, and so on. In this example, we only wrote some output on the screen by exploiting the function print, but a computation can be much more complex, such as solving equations, searching text in a document, applying a filter to an image, etc.
Arithmetic expressions
You can use Python to compute mathematical expressions by applying operators:
- + : sum
- - : subtraction
- / : division
- * : multiplication
- ** : power
- // : integer division
- % : modulo
Arithmetic expressions have precedences in their execution, which are pretty easy to remember:
- Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first: 2 * (3-1) is 4, and (1+1)*(5-2) is 8.
- Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27, and 2 ** 3*2 is 18, not 36.
- Multiplication and Division have higher precedence than Addition and Subtraction. So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.
Operators with the same precedence are evaluated from left to right. So in the expression degrees / 2 * pi, the division happens first, and the result is multiplied by pi. The result is different from (minute * 100) / 60. You can also use parentheses to make an expression easier to read, as in (minute * 100) / 60, even if it doesn’t change the result. This is a good practice, as it will help you read your code in the future.
When you print some expression, the expressions built using the above operators are first evaluated, transformed into strings, and then printed.
In [ ]:
# Difference between the integer division (//) and the module (%)
a = 5
b = 3
print('The integer division between a and b is', a // b, 'with a rest of', a % b)
The integer division between a and b is 1 with a rest of 2
Python operations
Operators are special symbols that perform operations on variables and values.
Types of Python operators
Here's a list of different types of Python operators:
- Arithmetic operators
- Assignment Operators
- Comparison Operators
- Logical Operators
- Bitwise Operators
- Special Operators
Python arithmetic operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc. For example:
In [ ]:
# Arithmetic Operators in Python
a = 7
b = 2
# addition
print('Sum: ', a + b)
# subtraction
print('Subtraction: ', a - b)
# multiplication
print('Multiplication: ', a * b)
# division
print('Division: ', a / b)
# floor division
print('Floor Division: ', a // b)
# modulo
print('Modulo: ', a % b)
# a to the power b
print('Power: ', a ** b)
Sum: 9
Subtraction: 5
Multiplication: 14
Division: 3.5
Floor Division: 3
Modulo: 1
Power: 49
Explanation
In the above example, we have used multiple arithmetic operators:
- + to add a and b
- - to subtract b from a
- * to multiply a and b
- / to divide a by b
- // to integer divide a by b
- % to get the remainder
- ** to get a to the power b
Python assignment operators
Assignment operators are used to assign values to variables.
In [ ]: # Assignment Operators # assign 10 to a a = 10 # assign 5 to b b = 5 # assign the sum of a and b to a a += b # a = a + b print(a)
15
Python comparison operators
Comparison operators compare two values/variables and return a boolean result: True or False.
In [ ]:
# Comparison Operators
a = 5
b = 2
# equal to operator
print('a == b =', a == b)
# not equal to operator
print('a != b =', a != b)
# greater than operator
print('a > b =', a > b)
# less than operator
print('a < b =', a < b)
# greater than or equal to operator
print('a >= b =', a >= b)
# less than or equal to operator
print('a <= b =', a <= b)
a == b = False
a != b = True
a > b = True
a < b = False
a >= b = True
a <= b = False
Python logical operators
Logical operators are used to check whether an expression is True or False. They are used in decision-making.
In [ ]: # Logical Operators # logical AND print(True and True) # True print(True and False) # False # logical OR print(True or False) # True # logical NOT print(not True) # False
True
False
True
False
Python bitwise operators
Bitwise operators act on operands as if they were strings of binary digits. They operate bit by bit, hence the name.
In [ ]: # Bitwise operators x = 10 y = 4 print(x & y) print(x | y) # is equivalent to x ∪ y print(x ^ y)
0
14
6
Python special operators
Python language offers some special types of operators like the identity operator and the membership operator. They are described below with examples.
Identity operators
In Python, is and is not are used to check if two values are located on the same part of the memory. Two variables that are equal does not imply that they are identical.
In [ ]: # Identity operators x1 = 5 y1 = 5 x2 = 'Hello' y2 = 'Hello' x3 = [1, 2, 3] y3 = [1, 2, 3] print(x1 is not y1) # prints False print(x2 is y2) # prints True print(x3 is y3) # prints False
False
True
False
Explanation
Here, we see that x1 and y1 are integers of the same values, so they are equal as well as identical. Same is the case with x2 and y2 (strings). But x3 and y3 are lists. They are equal but not identical. It is because the interpreter locates them separately in memory although they are equal.
Membership operators
In Python, in and not in are the membership operators. They are used to test whether a value or variable is found in a sequence (string, list, tuple, set and dictionary).
In [ ]:
# Membership operators
x = 'Hello world'
y = {1: 'a', 2: 'b'}
# check if 'H' is present in x string
print('H' in x) # prints True
# check if 'hello' is present in x string
print('hello' not in x) # prints True
# check if '1' key is present in y
print(1 in y) # prints True
# check if 'a' key is present in y
print('a' in y) # prints False
True
True
True
False
Explanation
'H' is in x but 'hello' is not present in x (remember, Python is case sensitive). 1 is a key and 'a' is the value in dictionary y. Hence, 'a' in y returns False.
Python documentation
I have a terrible memory, as soon as I stop using something I forget its syntax. I hope you have a better memory, but anyway, everything about Python is publicly documented. In the docs.python.org website every bit of the language is documented, so you'd better become familiar with it as soon as possible.
Examples:
- The table of the precedence of the operators: https://docs.python.org/3/reference/expressions.html#operator-precedence
- All the built-in functions: https://docs.python.org/3/library/functions.html
In [ ]:
# you can mix input strings and number expression when you invoke print.
print(1 + 2)
print("Try the result of 4 + 8 =", 4 + 8)
print("4 - 8 = ", 4 - 8)
print("4 * 8 = ", 4 * 8)
print('8 / 3 = ', 8 / 3)
print('8 raised to the power of 3 = ', 8 ** 3)
print("8 // 3 = ", 8 // 3, " (integer division)")
print("8 % 3 = ", 8 % 3, " (rest of the integer division)")
print()
print("2*4 + 4*2 = ", 2 * 4 + 4 * 2, end='\n\n')
print("2 * (4 + 4) * 2 = ", 2 * (4 + 4) * 2)
3
Try the result of 4 + 8 = 12
4 - 8 = -4
4 * 8 = 32
8 / 3 = 2.6666666666666665
8 raised to the power of 3 = 512
8 // 3 = 2 (integer division)
8 % 3 = 2 (rest of the integer division)
2*4 + 4*2 = 16
2 * (4 + 4) * 2 = 32
Values and types
All programs deal with expression values that can have different types. In the past lessons we have talked about three types:
- Text (encoded in ASCII)
- Integer numbers
- Float numbers (encoded in mantissa/exponent form)
Inspecting types
You can inspect the type of variables with the type() function. You can also ask for the length of a string with the len() function, which provides the length of several different kinds of objects.
In [ ]:
print(type(2))
print(type(4.5))
print(type('Hello'))
print(type("Ciao"))
print(len("Ciao"))
<class 'int'>
<class 'float'>
<class 'str'>
<class 'str'>
4
Variables and values
To manipulate expression values, you can refer to them with a name. We call this name a variable. You can refer to a variable to access the associated value, but you can also reassign a variable. The statement that creates or reassigns a variable is the assignment, which exploits the '=' symbol.
var = expression value
We see below three examples of variable creation, and then we refer to them to inspect their types.
In [ ]:
message = 'I would like to say goodbye'
n = 17.0
pi = 3.141592653589793
print(message, '--->', type(message))
print('n ->', n, type(n))
print(pi, '--->', type(pi))
print(pi * n)
n = 17 + 1 # reassign a variable to some other data
print('n->', n, type(n))
I would like to say goodbye ---> <class 'str'>
n -> 17.0 <class 'float'>
3.141592653589793 ---> <class 'float'>
53.40707511102649
n-> 18 <class 'int'>
A fundamental concept in coding is that every variable is associated with a data, and data has a type (meaning that its content is encoded with a specific representation in the memory), so normally we say that the variable is of some type. Some languages make it explicit, and force you to declare the type of the variable when you create it, and normally the same variable does not change its type during the execution of the program. Some others, like Python, do not force you to declare a type, but internally, the data has a type and when the code is executed, a check is made to ensure that the operation you are trying to execute can be executed on data of that type.
In Python, every variable is thus, just a label. A name that is attributed to some content in the memory of the system. This is extremely important to understand the behavior of Python, so let me state it again:
In Python, a variable is just a label pointing to some data stored in the memory. The data has a type, but the variable does not have a type. Variables can point to different data during the evolution of the program. Colloquially, we ask "of what type is variable x?" meaning: "of what type is the data pointed by variable x?" We also say "the variable was modified/incremented/decremented". These are just forms we use, that do not mean variables have a fixed type or a fixed content.
In [ ]: n = 17
Scarica il documento per vederlo tutto.
Scarica il documento per vederlo tutto.
Scarica il documento per vederlo tutto.
Scarica il documento per vederlo tutto.
Scarica il documento per vederlo tutto.
Scarica il documento per vederlo tutto.
Scarica il documento per vederlo tutto.
Scarica il documento per vederlo tutto.
-
Fondamenti di informatica
-
Appunti Fondamenti teorici e programmazione (con quasi tutti esercizi risolti e indice)
-
Fondamenti cpp
-
Teoria Fondamenti di Automatica