Mirko <mroik@poul.org>
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.
variable = 12 # Integer
print(variable)
12
variable = "dodici" # String
variable2 = 'tredici' # Another string
print(variable)
dodici
alfa, beta = 12, 3 # Fancy way to declare
theta = alfa + beta # a third variable containing the sum of the other two
print(theta)
15
It adapts to the programmer:
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
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
print("Hello, world!")
Hello, world!
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.
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.
x = 12
print(x)
x = "a string"
print(x)
12 a string
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.
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 |
## Order of operations
x = 10
y = 5
print((x % y) + 1**2 / 2) ## What is the result?
0.5
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
A block of code can be executed based on the evaluation of a logical expression.
We will talk about:
...the title is also a link
Evaluate the logical outcome of two or more statements.
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
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
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
basket = 0
if basket == 0:
print("[*] The basket is empty")
else:
print("[*] The basket contains something")
[*] The basket is empty
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
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 :(
# 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
for value in ["apples", "bananas", "pears", "turkeys"]:
print(value)
apples bananas pears turkeys
for i in range(5):
print(f"{i} {'🍎' * i}")
0 1 🍎 2 🍎🍎 3 🍎🍎🍎 4 🍎🍎🍎🍎
for value in ["😀","😁","😂","🤬","🤣","😃"]:
print(value, end=" ")
if value == "🤬":
print("Error")
break
print("Happy")
😀 Happy 😁 Happy 😂 Happy 🤬 Error
for value in ["😀","😁","😂","🤬","🤣","😃"]:
print(value, end=" ")
if value == "🤬":
continue
print("Error")
print("Happy")
😀 Happy 😁 Happy 😂 Happy 🤬 🤣 Happy 😃 Happy
"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()
def say_hello():
print("Hello, world!")
say_hello()
say_hello()
Hello, world! Hello, world!
def add_10(number):
number += 10
print(number)
add_10(2)
add_10(1)
12 11
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
def add_10(number=0):
number += 10
print(number)
add_10(2)
add_10(1)
add_10()
12 11 10
### 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
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}")
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️
# 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
dict_name = {key : value, key : value,...}
dct = {1: "cane", 2: "gatto", 3: "alpaca"}
dct2 = {"alfabeto": "alpaca", "cane": 1}
# 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}
For other unmentioned data types...
str
)complex
)bytes
)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 .
name = input("Whats your name?")
print("Hello, world with inputs --> Hello, {}!".format(name))
Whats your name?Mirko Hello, world with inputs --> Hello, Mirko!
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
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.
# test.py
def hello_world():
print("Hello world!")
def add_10(n):
return n + 10
print("Module loaded successfully")
Module loaded successfully
# 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.
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.
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.
# 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
Licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
Notebook source code available in this repo
Mirko <mroik@poul.org>