Variables & Assignment
name = "Alice" # string
age = 25 # integer
gpa = 3.85 # float
is_student = True # boolean
# Multiple assignment
a, b, c = 1, 2, 3
# Reassignment
x = 10
x = x + 5 # x is now 15
x += 5 # shorthand, x is now 20
Naming Rules
| Rule | Example |
| Start with letter or _ | name, _count |
| Letters, numbers, _ only | item2, my_var |
| No spaces | first_name (not first name) |
| Case-sensitive | Name ≠ name |
| No reserved words | Cannot use if, class, etc. |
Convention: use snake_case for variables.
Arithmetic Operators
| Operator | Name | Example | Result |
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 10 - 4 | 6 |
* | Multiply | 6 * 7 | 42 |
/ | Division | 15 / 4 | 3.75 |
// | Int Division | 15 // 4 | 3 |
% | Modulo | 15 % 4 | 3 |
** | Exponent | 2 ** 3 | 8 |
/ always returns a float! 10 / 2 = 5.0
Data Types
| Type | Example | Description |
int | 42, -7 | Whole numbers |
float | 3.14, 2.0 | Decimal numbers |
str | "hello" | Text |
bool | True, False | Boolean |
NoneType | None | No value |
type(42) # <class 'int'>
type(3.14) # <class 'float'>
type("hello") # <class 'str'>
type(True) # <class 'bool'>
String Basics
# Single or double quotes
msg = "Hello"
msg = 'Hello'
# Escape characters
\n newline \t tab
\\ backslash \' single quote
\" double quote
# Operations
"Hi " + "there" # "Hi there"
"Go! " * 3 # "Go! Go! Go! "
len("Python") # 6
# Indexing (zero-based)
word = "Python"
word[0] # 'P'
word[-1] # 'n'
Type Conversion
int("42") # 42
float("3.14") # 3.14
str(42) # "42"
bool(1) # True
int(float("3.7")) # 3
int() truncates, does NOT round. int(9.9) = 9
Truthy / Falsy
| Falsy | Truthy (everything else) |
0, 0.0 | Any non-zero number |
"" (empty string) | Any non-empty string |
None | "0", " ", etc. |
False | True |
Useful Functions
abs(-15) # 15
round(3.14159, 2) # 3.14
max(10, 20, 5) # 20
min(10, 20, 5) # 5