Python - Basics
In questa pagina 11
Python is the language of the course (see Programming FundamentalsThe CPU only executes machine instructions (opcodes) of its own instruction set; assembly languages give them mnemonic names and an assembler translates them one-to-one, but they are CPU specific; high-level languages are CPU independent and are translated by a compiler (executable code is CPU specific) or run by an interpreter; compiled languages are generally more efficient, interpreted languages more portable, and Java aims at both.Programming Fundamentals → for the general notions of programming). This note covers the language background, how programs are run, variables, data types, input, operators and boolean logic. Conditions, loops, lists, functions and files are in Python - Control Flow, Lists, Functions and FilesA program makes decisions with if, elif and else, whose blocks are defined by the colon and by four-space indentation (an IndentationError otherwise). It repeats statements with while loops (condition, counter, update; infinite loops and sentinel loops) and for loops over range or over a sequence. A list is an ordered mutable container with zero-based indices, len, append, insert, pop, remove, the in operator, slicing, and sorted versus sort. Functions are defined with def, take parameters, return values with return (print is not return; no return gives None), have local variables, must be defined before being called and can live in separate modules imported with import. Text files are opened with the with statement in modes r, w or a with utf-8 encoding and read as strings.Python - Control Flow, Lists, Functions and Files →. The number formats behind int, float and str are in Representation of InformationEverything in a computer is a sequence of bits, so each kind of information needs a coding. Natural numbers use positional notation in base 2 (conversion by repeated division by 2); signed integers use two's complement (range from minus 2 to the n minus 1 up to 2 to the n minus 1, minus 1), where negation is invert-all-bits-and-add-1, sums are plain binary sums and overflow is detected on the two top carries; hexadecimal groups bits in fours; fractions use fixed point or IEEE 754 floating point (sign, exponent in excess 127, 23-bit fraction) and are only approximate; characters are unsigned integers in a code table (ASCII, Unicode); images, video and sound are stored as numbers too (pixels, frame differences, samples).Representation of Information →.
1. Background
- Created in the late 1980s by Guido van Rossum, a Dutch programmer at CWI in Amsterdam; first public release in 1991. Aim: a language that is powerful yet readable, suitable for real work and accessible to beginners.
- The name comes from the comedy group Monty Python, not from snakes (short, memorable, irreverent).
- Central idea: code is read many more times than it is written, so readability comes first. The philosophy is summed up in the Zen of Python (shown with
import this): simple is better than complex; beautiful is better than ugly; there should be one (preferably only one) obvious way to do things. - Python 3 was released in 2008 and is not fully backward compatible with Python 2. Python 2 has not been maintained since January 1, 2020. In the course "Python" always means Python 3 (online examples with
printwithout parentheses are old Python 2 code). - Python is a high-level languagefar from the minute details of how a machine works and close to the way a human would describe a procedure and general purposenot specialised in just one area: data analysis, artificial intelligence, scientific computing, web, automation, research. The TIOBE Programming Community index (a popularity indicator) puts it first, ahead of C, C++, Java.
- Strengths for beginners: concise syntax close to everyday English, so one can focus on variables, conditions, loops, functions and algorithms; rich ecosystem of libraries; strong community; cross-platform (Windows, macOS, Linux with no or minimal changes); high productivity. It is not a toy: the skills are those used in industry and research.
2. The first program
# My program in Python
print("Hello, world!")- The first line is a comment: it starts with
#, is ignored by the interpreter and is used to explain the code to the reader. print()is a built-in functiona ready-to-use function that comes with Python by default, with no need to define or import it that displays on the screen the text written inside the parentheses;"Hello, world!"is the argument passed to it. A function is a sequence of statements associated with a name that performs a specific task.- A function is called by writing its name followed by round brackets, which may contain arguments. The brackets are mandatory.
"Hello, world!"is a string, a sequence of characters. It is enclosed in double or single quotes (print('Hello, world!')is the same), but the same type of quote must be used at the start and at the end. The quotes only tell Python where the text begins and ends: they are not printed.
Output:
Hello, world!3. The Python interpreter
- A Python program is not executed by the operating system but by a program called the interpreter. The source code is written in a high-level language; the computer understands only very simple instructions in machine language, so a "bridge" is needed.
- Compiled languages (like C): a compiler translates the whole program into machine language and produces an executable file.
- Interpreted languages (like Python): no executable is created beforehand; the interpreter reads and executes the code one statement at a time. Convenient for learning because code can be tried right away; in return it can be slower than a compiled program.
- Execution (slide diagram): source code in a
.pyfile, then the interpreter translates it into bytecode (a low-level representation kept in memory, not a file), then the interpreter executes the bytecode and produces the output.
Installing Python
- Interpreter from the official site python.org.
- Windows: download the installer and select "Add Python to PATH", so that
pythoncan be typed in the command prompt. - macOS: official installer or Homebrew; the command is
python3, because the system may contain older preinstalled versions. - Linux: Python 3 is often already present; otherwise use the package manager (
apton Debian/Ubuntu,dnfon Fedora).
- Windows: download the installer and select "Add Python to PATH", so that
- Check from the terminal:
python --versionorpy --version; on macOS/Linuxpython3 --version. Any Python 3.9 or later is fine.
Interactive mode (REPL)
Typing python (or python3, or py) in the terminal starts the interpreter, which shows the prompt >>>: Python is ready to receive a statement.
>>> print("Hello, world!")
Hello, world!
>>> 2 + 3
5This loop is called REPL: Read, Eval, Print, Loop (Python reads the statement, evaluates it, prints the result and starts over). The notes add that exit() ends the session (Ctrl-D on macOS and Linux, Ctrl-Z then Enter on Windows). Interactive mode is useful for quick tests, but what is written is lost when the interpreter is closed.
The edit/run loop
For longer programs the code is written in a plain text file with the .py extension (not in a word processor such as Word), for example greeting.py, and run from the terminal:
python greeting.pyPython reads the file from start to finish and executes the statements in order; unlike interactive mode, only what is printed explicitly appears on screen. The normal way of working is the edit/run loop:
write, save, run, observe, fix, run again.
A program almost never works on the first attempt: programming also means trying, reading errors and fixing them.
4. Variables
- A variable stores a value for later reuse. The
=sign is not mathematical equality: it is an assignment, read from right to left (take the value 10 and assign it to the variable namedprice). A variable is a name linked to a value stored in memory, and its value can change during execution.
price = 10
quantity = 3
print(price * quantity) # prints 30score = score + 1is not a mathematical equality: first Python computes the value on the right, then assigns it back to the variable.
>>> score = 0
>>> score = 5
>>> score = score + 1
>>> score
6Variable names (identifiers)
- The name of a variable is an identifierthe name given to a variable, which may contain letters, digits and the underscore: letters, digits and
_(underscore). - It cannot start with a digit and cannot contain spaces or punctuation marks.
- It is case sensitive:
price,Price,PRICEare three different variables. wonder7and_wonderare valid;7wonderand?whyare not.- Convention: snake case for names of several words (
rectangle_area,number_of_students). The most important rule is to choose meaningful names: bettertotal = price * quantity, worsex = p * q. - Some words are reserved and cannot be used as identifiers:
if,for,def,Trueand others.
5. Arithmetic operators
| operator | name | example |
|---|---|---|
+ |
addition (or string concatenation) | 5 + 3 gives 8 |
- |
subtraction | 10 - 4 gives 6 |
* |
multiplication | 6 * 7 gives 42 |
/ |
true division, returns a float | 7 / 2 gives 3.5 |
// |
floor division, integer part rounded down | 7 // 2 gives 3 |
% |
modulus, remainder of the division | 7 % 2 gives 1 |
** |
exponentiation | 2 ** 3 gives 8 |
17 / 5 # 3.4 true division
17 // 5 # 3 floor division
17 % 5 # 2 remainder
2 ** 5 # 32 power- The true division
/always returns a float, even when both operands are integers (10 / 2is5.0). - Floor division
//returns the largest integer less than or equal to the result (it rounds down); the slides state that it always returns an integer result. %is the remainder: 17 = 5 x 3 + 2, so17 % 5is 2. Typical use:number % 2 == 0tests whether a number is even (see Python - Control Flow, Lists, Functions and FilesA program makes decisions with if, elif and else, whose blocks are defined by the colon and by four-space indentation (an IndentationError otherwise). It repeats statements with while loops (condition, counter, update; infinite loops and sentinel loops) and for loops over range or over a sequence. A list is an ordered mutable container with zero-based indices, len, append, insert, pop, remove, the in operator, slicing, and sorted versus sort. Functions are defined with def, take parameters, return values with return (print is not return; no return gives None), have local variables, must be defined before being called and can live in separate modules imported with import. Text files are opened with the with statement in modes r, w or a with utf-8 encoding and read as strings.Python - Control Flow, Lists, Functions and Files →).
Precedence and associativity
| level | operators | associativity |
|---|---|---|
| 1 (highest) | ** |
right to left |
| 2 | *, /, //, % |
left to right |
| 3 | +, - |
left to right |
- Higher precedence is evaluated first:
a + b * cisa + (b * c);2 + 3 * 4= 2 + 12 = 14. - Operators with the same precedence are evaluated according to their associativity:
a * b / cis(a * b) / c;8 / 2 * 3= (8 / 2) * 3 = 4 * 3 = 12;10 / 2 * 3= 15 but10 / (2 * 3)= 1.666... - Advice: always use round brackets to make the intended order explicit and the expression easy to read.
6. Data types
Every value has a data type that determines what it represents and which operations are allowed. type() shows it:
>>> type(42)
<class 'int'>
>>> type("hello")
<class 'str'>| type | meaning | examples |
|---|---|---|
int |
integers | 0, 42, -7 |
float |
decimal numbers | 3.14, -0.5 |
str |
text | "hello", "good morning" |
bool |
boolean values | True, False |
- In Python the decimal separator is a dot, not a comma. The notes add that
3,14is not a number but two distinct values separated by a comma; also that Python integers can grow as large as desired. TrueandFalsemust be written with a capital initial.- The same operator behaves differently depending on the type:
'good' + 'morning' # 'goodmorning' - concatenation does not insert spaces!
'good' + ' ' + 'morning' # 'good morning'
'ab' * 3 # 'ababab' - a string times an integer
10 / 2 # 5.0 - division with float result
10 // 2 # 5 - integer division
5 > 3 # True - boolean constant
10 == 7 # False - boolean constant7. Converting one type into another
Conversion functions are named after the target type: int(), float(), str(), bool(). The conversion must make sense.
>>> str(42)
'42'
>>> int("42")
42
>>> float("3.14")
3.14
>>> int(3.9)
3- Converting a float to
inttruncates the decimal part, it does not round:int(3.9)is 3. str(42)gives'42': no longer a number, but the text formed by two digits.int("hello")makes no sense and produces an error:
>>> int("hello")
Traceback (most recent call last):
File "<python-input-0>", line 1, in <module>
int("hello")
ValueError: invalid literal for int() with base 10: 'hello'- Strings are concatenated with
+. If a string is concatenated with a number, Python refuses the conversion because the two types are different; the number must be converted withstr:
>>> age = 20
>>> "I am " + age + " years old"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
>>> "I am " + str(age) + " years old"
'I am 20 years old'Reading and understanding error messages is important: Python tells where the program stopped and what problem it found.
8. Swapping variables
Goal: if a is 10 and b is 20, end with a equal to 20 and b equal to 10. The naive attempt fails:
a = 10
b = 20
a = b
b = a
print(a, b)Output: 20 20. a = b copies 20 into a and the 10 is lost forever; then b = a gives b the 20 it already had. Solution: set aside the value of a in an auxiliary variable (traditionally tmp):
a = 10
b = 20
tmp = a
a = b
b = tmp
print(a, b)Output: 20 10. State after each step: after tmp = a (10, 20, 10); after a = b (20, 20, 10); after b = tmp (20, 10, 10) for (a, b, tmp). General lesson: every assignment erases the previous value of the variable, so if the value is still needed it must be stored elsewhere before overwriting it.
9. Reading input
input()reads text typed by the user on the keyboard. The message inside is the prompt, which tells the user what to enter.input()always returns text (a string), even when the user types a number.
name = input("What is your name? ")
print("Hello,", name)What is your name? Ann
Hello, AnnWithout conversion the numbers are strings, so + concatenates:
a = input("First number: ")
b = input("Second number: ")
print("The sum is:", a + b)With 3 and 4 the output is The sum is: 34. To actually add, convert:
a = int(input("First number: "))
b = int(input("Second number: "))
print("The sum is:", a + b)With 3 and 4 the output is The sum is: 7 (use float for decimal numbers).
10. Boolean logic
- Boolean values are
TrueandFalse. They often arise from comparisons using relational operators.
| operator | name | example |
|---|---|---|
> |
greater than | 5 > 3 is True |
< |
less than | 5 < 3 is False |
>= |
greater than or equal to | 5 >= 5 is True |
<= |
less than or equal to | 3 <= 5 is True |
== |
equal to | 5 == 5 is True |
!= |
not equal to | 5 != 3 is True |
- Use
==to check equality (=is the assignment operator) and!=for inequality. Strings can be compared too, by lexicographic (dictionary) order:"apple" < "banana"is True. - Boolean logic combines several conditions with three operators, which in Python are words:
and: true only if both conditions are true;or: true if at least one condition is true (inclusive or);not: inverts the truth value.
>>> True and True
True
>>> True and False
False
>>> 5 > 3 and 10 > 7
True
>>> False or True
True
>>> False or False
False
>>> 2 > 7 or 4 == 4
True
>>> not True
False
>>> not 5 > 3
FalseTruth tables
A truth tablea table listing the result of a logical operator for every possible combination of the values of its operands summarizes the three operators:
| a | b | a and b | a or b |
|---|---|---|---|
| False | False | False | False |
| False | True | False | True |
| True | False | False | True |
| True | True | True | True |
| a | not a |
|---|---|
| False | True |
| True | False |
Precedence of logical operators
Without parentheses: not first (right to left), then and (left to right), finally or (left to right).
>>> True or False and False
Truex > a or x < b and x < cis evaluated asx > a or (x < b and x < c), becauseandhas precedence overor.not a or b and cis(not a) or (b and c): firstnot a, thenb and c, thenor.not (a or b) and c: firsta or b, thennoton the result, thenandwithc.- Advice: always use round brackets to make logical expressions easy to read. The notes suggest
(age >= 18) and (age < 65)to check thatageis in an interval.
De Morgan's laws
They establish how negation distributes over a conjunction and a disjunction:
not (a and b)is equivalent to(not a) or (not b);not (a or b)is equivalent to(not a) and (not b).
Negating that both conditions are true is equivalent to asserting that at least one is not true; negating that at least one is true is equivalent to asserting that neither is true. If "it rains and it's cold" is false, then "it does not rain or it is not cold". Negation, when moved inside the parentheses, swaps and with or.
>>> a = True
>>> b = False
>>> not (a and b)
True
>>> (not a) or (not b)
TrueExample: not (x > 0 and x < 10) corresponds to x <= 0 or x >= 10. The mistake to avoid is negating only the single comparisons without also swapping the connecting operator.
11. Self-check questions (from the slides)
Who created Python and in what context; Python 2 versus Python 3; what print does and why the parentheses; what a string is; in what sense Python is interpreted; interactive mode versus edit/run loop; what >>> indicates; what a variable is and how it differs from a mathematical one; why x = x + 1 makes sense; the main arithmetic operators and the difference between / and //; what % returns; the main data types; string versus number with the same characters; what input does and why its result is often converted; the values True and False; how and, or, not work; what a truth table is.
Versione ripasso
Background. Python 3 (first release 1991, created by Guido van Rossum) is high-level and general-purpose; Python 2 is unmaintained since 1 January 2020. Zen of Python (import this): readability first, one obvious way to do things.
Running programs.
- The interpreter translates source code into bytecode in memory and executes it: Python is interpreted, not compiled to an executable.
- Interactive mode (
>>>, REPL): quick tests, lost when the session ends (exit()). - Edit/run loop: write
greeting.py, runpython greeting.py; only explicitprintoutput appears. Expect to read errors and fix them.
# comment, ignored by the interpreter
print("Hello, world!") # print() is a built-in function; the string is the argumentVariables. = is assignment, read right to left; the right side is evaluated first (score = score + 1). Names: letters, digits, _; no leading digit, no spaces or punctuation, case sensitive, snake_case, no reserved words. Every assignment overwrites the old value.
Operators. + - * / // % **. / always returns a float; // floor division; % remainder (17 % 5 is 2). Precedence: **, then * / // %, then + -; same level left to right (** right to left). Use brackets.
Types and conversion. int, float (decimal dot, not comma), str, bool (True, False). type() shows the type. Same operator, different meaning: 'ab' * 3, 'good' + 'morning' (no space). int() truncates (int(3.9) is 3); int("hello") gives ValueError; "I am " + age gives TypeError, fixed with str(age).
Input. input() always returns a string: convert with int() or float() before arithmetic.
Swap pattern. a = b then b = a loses the first value; store it first:
tmp = a
a = b
b = tmpBoolean logic. Comparisons == != < > <= >= give booleans. and (both true), or (at least one), not (inverts). Precedence: not, then and, then or; brackets make it clear, e.g. (age >= 18) and (age < 65). Use the truth tables to check any combination.
De Morgan. not (a and b) is (not a) or (not b); not (a or b) is (not a) and (not b). Negation swaps and with or. Example: not (x > 0 and x < 10) is x <= 0 or x >= 10.
Common mistakes: = used for equality (use ==); / where // was meant; forgetting that input returns text; str + int without conversion; negating single comparisons without swapping and/or.
Teoria collegata
- Java - Language Basics
- Python - Control Flow, Lists, Functions and Files
- Representation of Information
- Introduction to Machine Learning - Learning, Data and Tasks
- Introduction to Machine Learning - Program Map
- Python Notebooks - Random Samples, Plots and Linear Algebra with NumPy
- Python Notebooks - Strings and Regular Expressions