Python course 2022

Introduction to Python

POuL logo

Mirko <mroik@poul.org>

Why use Python¶

  • Easy to learn
  • Nonexistent boilerplate
  • Big and active community --> Lots of libraries
  • The best documentation
  • And honestly, docstrings done right.

What we will talk about¶

The basics of Python:

  • Variables
  • Control-flow
  • Functions
  • Data Structures

What you will need in order to use Python¶

I would suggest starting at Python's website... in the download section, you will find instructions to download Python for your operating system.

A good text editor I recommended if you're writing scripts/programs is PyCharm. It's an excellent choice, it performs well on popular OSes (Though, note that it really isn't a text editor but an IDE).

If PyCharm is too heavy you may also want to try Visual Studio Code (which is an editor).

Whatever you choose just make sure to install a vim plugin. Just kidding, that's just my thing.

Let's start!¶

In [1]:
variable = 12  # Integer
print(variable)
12
In [2]:
variable = "dodici"  # String
variable2 = 'tredici'  # Another string
print(variable)
dodici
In [3]:
alfa, beta = 12, 3  # Fancy way to declare
theta = alfa + beta  # a third variable containing the sum of the other two
print(theta)
15

Easy to use.. and VERSATILE¶

It adapts to the programmer:

  • Complex architectures
  • Command Line applications
  • Scraping
  • Telegram bots
  • Data science
  • And more...

In Python there are many ways to do the same thing¶

The complicated way¶

In [4]:
def greet(what):
    def decorator(foo):
        def hello():
            print(what, end=", ")
            foo()
        return hello
    return decorator

@greet("hello")
def hello_world():
    print("world")

hello_world()
hello, world

The modular one¶

In [5]:
class Class_hello:
    def __init__(self, who):
        self.who = who

    def hello(self):
        print(f"hello, {self.who}")
        
clss = Class_hello("world")
clss.hello()
hello, world

The simple one¶

In [6]:
print("Hello, world!")
Hello, world!

How do I start coding in Python?¶

First of all, create a file with the dot py extenstion (.py). Then open it up with your favorite editor.

If you have experience with code, usually you'll know that before starting to code we'll need to write down some boilerplate. In Python that's not a thing. You can start writing right away.

The language¶

Variables¶

Python is a weakly-typed language, meaning that we can get away with assigning a different type of value in a already defined variable.

Once declared, the variable type in a language like C, cannot change:

int x;
x = 2.5;

The decimal part will be pruned 'cause x is declared as Integer.

In [7]:
x = 12
print(x)
x = "a string"
print(x)
12
a string

"Storing Values in Variables"¶

A variable is like a box in the computer’s memory where you can store a single value.

If you want to use the result of an evaluated expression later in your program, you can save it inside a variable.

@AlSweigart python books

Types/Operators¶

Variables can contain many different types of data, here are some...

We can form expressions that the python interpreter will solve for us.

...this is for those who want to deepen the topic...

Name Exampl
Integer 11
Float 2.3
Boolean True/False
String "apple"
...... ....
Operator Name Example
/ Division 5 / 2 ⇒ 2.5
// Floor Divis 5 // 2 ⇒ 2
% Modulo 5 % 2 ⇒ 1
* Multiplic. 2 * 3 ⇒ 6
+ Sum 2 + 2 ⇒ 4
- Subtraction 3 - 2 ⇒ 1
** Power 2 ** 3 ⇒ 8
In [8]:
## Order of operations
x = 10
y = 5

print((x % y) + 1**2 / 2)  ## What is the result?
0.5

A program using the things we just demonstrated¶

In [9]:
basket = 14
print(f"🍎 The basket contains {basket} apples.")
added_apples = 6
basket += added_apples   # basket = basket + added_apples
print(f"🍎 {added_apples} apples were added, for a total of {basket} apples.")

print(f"🍎 Sharing them with 3 people would leave {basket % 3} apples in the basket")
🍎 The basket contains 14 apples.
🍎 6 apples were added, for a total of 20 apples.
🍎 Sharing them with 3 people would leave 2 apples in the basket

Control-Flow¶

A block of code can be executed based on the evaluation of a logical expression.

We will talk about:

  • Logical expressions
  • Conditionals
  • Iterations
  • Code Blocks <-- let's be precise

...the title is also a link

Logical expressions¶

Evaluate the logical outcome of two or more statements.

In [10]:
print(True != False)  #True
print(not True)  #False
print(1 == True)  #True
print(0 == False)  #True
print(1 > 1.1)  #False
print(2 <= 2)  #True
print(True and not False)  #True
print(True or False)  #True
True
False
True
True
False
True
True
True

Conditional execution¶

  • if: checks the expression, executes the code block if True
  • elif: checks another expression, executes code block if True
  • else: executes the code block if the previous are False
In [11]:
basket = 10

if basket == 10:
    print("[*] The basket contains 10 apples")
elif basket > 10:
    print("[*] The basket contains more than 10 apples")
else:
    print("[*] The basket contains less than 10 apples")
[*] The basket contains 10 apples
In [12]:
basket = 0

if basket == 0:
    print("[*] The basket is empty")
else:
    print("[*] The basket contains something")
[*] The basket is empty

Execution by Iteration¶

  • while: Executes the code block while the expression results True.
  • for: Executes the code block in a loop for every item in a sequence.
while expression_is_true:
    # Do something

for some_index in this_sequence:
    # Do something
In [13]:
basket = 4
while basket > 0:
    basket = basket - 1
    print(f"Gnam, we now have {basket} 🍏")
print("\nNo more apples :(")
Gnam, we now have 3 🍏
Gnam, we now have 2 🍏
Gnam, we now have 1 🍏
Gnam, we now have 0 🍏

No more apples :(
In [14]:
# Multiplication table
i, base = 1, 9
while i <= 10:
    print(f"{base} * {i} = {i*base}")
    i += 1
9 * 1 = 9
9 * 2 = 18
9 * 3 = 27
9 * 4 = 36
9 * 5 = 45
9 * 6 = 54
9 * 7 = 63
9 * 8 = 72
9 * 9 = 81
9 * 10 = 90
In [15]:
for value in ["apples", "bananas", "pears", "turkeys"]:
    print(value)
apples
bananas
pears
turkeys
In [16]:
for i in range(5):
    print(f"{i} {'🍎' * i}")
0 
1 🍎
2 🍎🍎
3 🍎🍎🍎
4 🍎🍎🍎🍎

Break & Continue¶

In [17]:
for value in ["😀","😁","😂","🤬","🤣","😃"]:
    print(value, end=" ")
    if value == "🤬":
        print("Error")
        break
    print("Happy")
😀 Happy
😁 Happy
😂 Happy
🤬 Error
In [18]:
for value in ["😀","😁","😂","🤬","🤣","😃"]:
    print(value, end=" ")
    if value == "🤬":
        continue
        print("Error")
    print("Happy")
😀 Happy
😁 Happy
😂 Happy
🤬 🤣 Happy
😃 Happy

Functions¶

"Black boxes", functions take input parameters, give output data (not always).

Functions allow you to reuse code you have already written, saving up time (most of the time, with code written by other people).

def name_of_function():
    some_variable = "an instruction"
    some_other_variable = "another instruction"
    a_third_instruction()
    # and so on....

name_of_function()
In [19]:
def say_hello():
    print("Hello, world!")

say_hello()
say_hello()
Hello, world!
Hello, world!
In [20]:
def add_10(number):
    number += 10
    print(number)
    
add_10(2)
add_10(1)
12
11
In [21]:
def add_10(number):
    number += 10
    return number

base = 15
result = add_10(base)

print(f"I had {base}, now I have {result}")
print(f"Look mom! Without auxiliary variables: {add_10(base)}")
I had 15, now I have 25
Look mom! Without auxiliary variables: 25
In [22]:
def add_10(number=0):
    number += 10
    print(number)
    
add_10(2)
add_10(1)
add_10()
12
11
10
In [23]:
### Rewritten the previous while example as a function
def tables(x, length=10, show_title=False):
    if show_title:
        print(f"Multiplication Table of {x}")

    for i in range(length):
        print(f"{x} x {i+1} = {x * (i+1)}")
        i += 1


tables(2, 4)
print()
tables(8, show_title=True, length=3)
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8

Multiplication Table of 8
8 x 1 = 8
8 x 2 = 16
8 x 3 = 24

Scope, or code visibility¶

Variables and functions have their own context, for pragmatic reasons.

  • name collision
  • unexpected behaviours
In [24]:
x = "abercrombie"  #Global 🌍

def fun1():
    print(f"fun1: x = {x}")

def fun2():
    x = "2️"
    print(f"fun2: x = {x}")
    
def fun3():
    global x
    x = "3️"
    print(f"fun3: x = {x}")
In [25]:
print(f"🌍: x = {x}")
fun1()
fun2()
print(f"🌍: x = {x}")

fun3()
fun1()
fun2()
print(f"🌍: x = {x}")
🌍: x = abercrombie
fun1: x = abercrombie
fun2: x = 2️
🌍: x = abercrombie
fun3: x = 3️
fun1: x = 3️
fun2: x = 2️
🌍: x = 3️

Data Structures¶

Data organized in a structure to facilitate processing.

Sequences¶

List -- mutable sequences¶

  • ordered collections
  • defined inside squared brackets
list_name = ["first item", "second item", ...]

Sequences¶

Tuple -- immutable sequences¶

  • ordered collections
  • defined inside parenthesis
tuple_name = (item, item, ...)
tuple_name = (item, )  # If a tuple only has 1 item
In [26]:
# Function definition
def print_sequence(seq):
    for i in seq:
        print(i)
        
def modify_sequence(seq):
    seq[0] = "[*!!!*]"
    print_sequence(seq)
        
# Structures
lst = ["dog", "cat", "eleven", 13]
tpl = ("dog", "cat", "eleven", 13)

# Execute functions with structures as parameters
print_sequence(lst)
print()
modify_sequence(lst)
dog
cat
eleven
13

[*!!!*]
cat
eleven
13

Dictionaries -- key/value pairs¶

  • mutable sequences
  • defined inside { }
dict_name = {key : value,  key : value,...}
In [27]:
dct =  {1: "cane", 2: "gatto", 3: "alpaca"}
dct2 = {"alfabeto": "alpaca", "cane": 1}
In [28]:
# A more pragmatic one...

def return_person_list():
    lst = []
    lst.append("Mario")
    lst.append("Rossi")
    lst.append(27)
    return lst

def return_person_dict():
    d = {}
    d["firstname"] = "Mario"
    d["lastname"]  = "Rossi"
    d["age"] =  27
    return d

print(return_person_list())
print(return_person_dict())
['Mario', 'Rossi', 27]
{'firstname': 'Mario', 'lastname': 'Rossi', 'age': 27}

Other data types...¶

For other unmentioned data types...

  • Strings (str)
  • Complex numbers (complex)
  • Bytes (bytes)
  • Queues (queue.Queue, multiprocessing.Queue)
  • ...

For everything you don't know/remember about the language..
there is a section in the docs for that.

In this case: python - Data Model .

I/O -- or Input/Output¶

User interaction, or the thing that makes your program useful..
it is also very dangerous.

In [29]:
name = input("Whats your name?")
print("Hello, world with inputs --> Hello, {}!".format(name))
Whats your name?Mirko
Hello, world with inputs --> Hello, Mirko!
In [30]:
print("Simple Addition:")
add1 = int(input("First term: "))
add2 = int(input("Second term: "))
print(f"{add1} + {add2} = {add1 + add2}") # with f-strings!

# or
print("{} + {} = {}".format(add1, add2, add1 + add2))
Simple Addition:
First term: 2
Second term: 3
2 + 3 = 5
2 + 3 = 5

Modules¶

A big advantage of Python is the quantity of libraries that are available. So how do we write/use a library?

If you want to reference a python script you already wrote simply use the import statement.

Let's say that we have a script called test.py, to reference it we simply type import test.

What this will do is execute that script, so if we want to make a "library" of our own, we simply make a python file with only function definitions.

In [31]:
# test.py
def hello_world():
    print("Hello world!")

def add_10(n):
    return n + 10

print("Module loaded successfully")
Module loaded successfully
In [ ]:
# test2.py
import test

test.hello_world()
n = test.add_10(5)
print(n)

If the name of a module is too long, we can rename the namespace by using the keyword as after the import followed by the new name.

In [ ]:
import test as ts

Another thing we can do is import specific functions, values or classes that we might need instead of importing the entire module.

In [ ]:
from test import hello_world
hello_world()
# Note that here we didn't need begin with test.

Lastly, if the project gets too big we might want to structure our files in subdirectories.

You're free to do that, when you want to import them you'll need to go into the directories as if you had a module inside a module.

In [ ]:
# Let's say that test.py is under "libs/utils/"
# So libs/utils/test.py
import libs.utils.test

# or
from lib.utils import test

Thank you!

POuL logo

Creative Commons License

Licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
Notebook source code available in this repo

Mirko <mroik@poul.org>