Python: reference
A simple language to start with: variables, branching and loops.
Output and input
print and comments
print outputs values separated by a space. The sep and end parameters change the separator and the line ending.
print("Hello, world!") # comment
print("Sum:", 2 + 3)
print("a", "b", sep="-", end="!\n")input
input always returns a string; convert numbers with int() or float().
name = input("Name: ")
age = int(input("Age: "))
print(f"{name}, you are {age}")Variables and types
Basic types
You do not need to declare a type: a variable is created by assignment.
n = 42 # int x = 3.14 # float s = "text" # str ok = True # bool nothing = None # no value print(type(n), type(x))
Operations
/ gives a fraction, // divides without a remainder, % returns the remainder, ** raises to a power.
print(7 / 2, 7 // 2, 7 % 2, 2 ** 10) # 3.5 3 1 1024
x = 5
x += 2 # x = x + 2
print(int("12"), float("1.5"), str(7), bool(0))Strings
Slices and methods
Strings are immutable: methods return a new string.
s = "Python"
print(len(s), s[0], s[-1], s[1:4]) # 6 P n yth
print(s.upper(), s.lower(), s.replace("P", "J"))
print("a,b,c".split(","), " ".join(["a", "b"]))f-strings
Expressions in {} are evaluated, and the format is set after the colon.
name, price = "Bread", 24.5
print(f"{name}: {price:.2f} UAH") # Bread: 24.50 UAHConditions
if / elif / else
Blocks are marked by indentation (usually 4 spaces), not by braces.
age = 17
if age < 12:
print("child")
elif age < 18:
print("teenager")
else:
print("adult")Logic and comparison
Comparisons can be chained: 1 < x < 10.
x = 5
print(1 < x < 10, x == 5, x != 3)
print(x > 3 and x < 8, not (x > 3), x < 0 or x > 4)
print("a" in "cat", 3 in [1, 2, 3])Loops
for and range
range(a, b, step) does not include b.
for i in range(3): # 0 1 2
print(i)
for i in range(1, 10, 2): # 1 3 5 7 9
print(i)
for ch in "abc":
print(ch)while, break, continue
break ends the loop, continue moves on to the next iteration.
n = 0
while True:
n += 1
if n % 2 == 0:
continue # skip this step
if n > 7:
break # leave the loop
print(n)Collections
List
A list is mutable. A list comprehension [expression for x in ...] creates a new list.
nums = [3, 1, 2] nums.append(5) nums.sort() print(nums, len(nums), nums[0], nums[-1]) print([x * 2 for x in nums]) # list from an expression
Tuple and set
A tuple cannot be changed; a set does not keep order or duplicates.
point = (3, 4) # tuple: immutable
x, y = point
tags = {"a", "b", "a"} # set: unique elements
print(len(tags), "a" in tags)Dictionary
get returns a default value if the key is missing and does not raise an error.
user = {"name": "Alex", "age": 16}
user["city"] = "Dnipro"
print(user["name"], user.get("phone", "none"))
for key, value in user.items():
print(key, value)Functions
def, return, parameters
Parameters can have default values, and arguments can be passed by name.
def area(w, h=1):
return w * h
print(area(3, 4), area(5))
print(area(h=2, w=6))*args, **kwargs and lambda
*args collects positional arguments into a tuple, **kwargs collects named ones into a dictionary.
def total(*nums):
return sum(nums)
print(total(1, 2, 3))
square = lambda x: x * x
print(list(map(square, [1, 2, 3])))Errors and files
try / except
Catch specific error types, not everything at once.
try:
n = int(input("Number: "))
print(10 / n)
except ValueError:
print("That is not a number")
except ZeroDivisionError:
print("You cannot divide by zero")
finally:
print("Done")Reading and writing files
The with block closes the file itself, even if an error occurs.
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("string 1\n")
with open("notes.txt", encoding="utf-8") as f:
for line in f:
print(line.strip())Classes
Class and method
__init__ is called when an object is created, and self is the object itself.
class Dog:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name}: woof!"
rex = Dog("Rex")
print(rex.speak())Learn Python with practice
- 110 lessons, 80 of them base
- Tasks with in-browser code checking
- 3 projects from a specification, each requirement checked
- Free, nothing to install