+
-
*
/
//
%
**
a = 10
b = 3
print(a + b) # 13
print(a - b) # 7
print(a * b) # 30
print(a / b) # 3.3333333333333335
print(a // b) # 3
print(a % b) # 1
print(a ** b) # 1000
==
!=
>
<
>=
<=
a = 10
b = 20
print(a == b) # False
print(a != b) # True
print(a > b) # False
print(a < b) # True
print(a >= b) # False
print(a <= b) # True
and
or
not
x = True
y = False
print(x and y) # False
print(x or y) # True
print(not x) # False
=
+=
-=
*=
/=
//=
%=
**=
a = 10
a += 5 # a = a + 5
print(a) # 15
x = 5 # Global variable
def func():
y = 10 # Local variable
global x
x = 20 # Modify global variable
func()
print(x) # 20
Python supports type hints to specify the expected type of variables.
def greeting(name: str) -> str:
return "Hello, " + name
name: str = "Alice"
age: int = 30
Formatted string literals for easy string interpolation.
name = "Alice"
age = 30
print(f"Hello, {name}. You are {age} years old.")
Small anonymous functions.
add = lambda x, y: x + y
print(add(2, 3)) # 5
Extracting values from collections.
a, b, c = (1, 2, 3)
print(a, b, c) # 1 2 3
lst = [4, 5, 6]
x, y, z = lst
print(x, y, z) # 4 5 6
gap1
enumerate
functionEnumerate adds a counter to an iterable.
for index, value in enumerate(['a', 'b', 'c']):
print(index, value)
zip
functionCombining iterables.
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old.")
map
functionApply a function to all items in an input list.
nums = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, nums))
print(squares) # [1, 4, 9, 16, 25]
filter
functionFilter items out of a list.
nums = [1, 2, 3, 4, 5]
even_nums = list(filter(lambda x: x % 2 == 0, nums))
print(even_nums) # [2, 4]
reduce
functionApply a function of two arguments cumulatively.
from functools import reduce
nums = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, nums)
print(product) # 120
gap1end
x = 10
result = "Greater than 5" if x > 5 else "5 or less"
print(result)
x = 5
increment = 3
x += increment
print(x) # 8
any()
and all()
any()
: Returns True
if any element in an iterable is True
.
conditions = [False, True, False]
if any(conditions):
print("At least one condition is true")
all()
: Returns True
if all elements in an iterable are True
.
conditions = [True, True, True]
if all(conditions):
print("All conditions are true")