Python
Conditionnals
x = 1
if x == 2:
a = 3
else:
a = 2
a
2
One-line ternary condition
In languages with a C-syntax, it is possible to write an conditional ternary expression: a = (x == 2) ? 3 : 2. It Python, we can do the same with a more understandable syntax:
a = 3 if x == 2 else 2
a
Easy-to-read conditions
In Python, conditions can be written for normal people.
age = 5
print("young" if 0 < age < 18 else "old")
invitationList = ["Alan", "Bob", "Christine", "Dylan", "Emeline", "Franck"]
me = "John"
if me not in invitationList:
print("you cannot enter")
Assignments in conditions
According to https://peps.python.org/pep-0572/, it is possible to make an assignment in a condition, like in C. To do that, we use the Walrus operator :=.
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
if (n := len(a) > 10):
print(f"List is too long ({n} elements, expected <= 10)")
No switch, sorry
There is no switch in Python, contrary to C. See https://peps.python.org/pep-3103/
Pattern matching
Here is an example of pattern matching (available in Python 3.10, https://docs.python.org/3/reference/compound_stmts.html#match).
i = 0
match i:
case 0: print("zero")
case _: print("non zero")
While loops
x = 0
while x < 10:
x += 1
For loops
In Python, it is possible to write for loops. They take the form of for i in BLOUP where BLOUP is an iterable. It matches somehow the theory of primitive recursive functions: we know that for loops terminates if the iterable object produces a finite number of elements.
for i in range(10):
print(i)
Generators
A generator is a special kind of function that contains the keyword yield. It returns an iterator (and thus in Python also an iterable object).
def squares(start, stop):
for i in range(start, stop):
yield i * i
for i in squares(1, 6):
print(i)
1
4
9
16
25
Comparing C and Python
| C | Python | |
|---|---|---|
| Use case | System | Prototyping, scripting, data science, etc. |
| Users | Computer scientists | Computer scientists, Biologists, etc. |
| Usage | Compiled to machine code | Compiled to bytecode, interpreted |
| Typing | Static, weak | Dynamic, strong (somehow static with mypy) |
| Memory usage | By hand (malloc/free) | Automatic via a garbage collector |