19.1. Python syntax cheat sheet
Table of Contents
Basic Script Structure
- A Python file ends with
.py - Run top‑to‑bottom
- Indentation uses spaces (PEP 8 recommends 4 spaces)
# This is a comment
def main():
print("Hello")
if __name__ == "__main__":
main()Comments
- Single line:
# comment - Inline comment:
code # comment
Variables and Basic Types
- Assignment:
name = value - No declaration keyword; type is inferred.
Common literals:
- Integers:
0,1,-5,10 - Floats:
0.0,3.14,-2.5,1e3 - Strings:
"hello",'world' - Booleans:
True,False - None:
None
Multiple assignment:
x, y = 1, 2
a = b = 0Check type:
type(42) # <class 'int'>
type("hi") # <class 'str'>Arithmetic Operators
- Addition:
a + b - Subtraction:
a - b - Multiplication:
a * b - Division (float):
a / b - Floor division:
a // b - Modulo (remainder):
a % b - Power:
a ** b
Augmented assignment:
x += 1 # x = x + 1
x -= 2 # x = x - 2
x *= 3
x /= 4Comparison and Logical Operators
Comparison (result is True or False):
- Equal:
a == b - Not equal:
a != b - Less than:
a < b - Greater than:
a > b - Less or equal:
a <= b - Greater or equal:
a >= b
Logical:
andornot
age = 20
is_adult = age >= 18 and age < 65Identity / membership (common usage):
is,is notin,not in
x is None
"py" in "python"Strings
Create:
text = "Hello"
other = 'World'Concatenation and repetition:
"Hello" + " " + "World"
"ha" * 3 # "hahaha"Indexing and slicing:
s = "python"
s[0] # 'p'
s[-1] # 'n'
s[1:4] # 'yth'
s[:3] # 'pyt'
s[3:] # 'hon'Basic string methods (pattern):
s.lower()
s.upper()
s.strip()
s.split(",")
",".join(["a", "b"])Input and Output
Input from user (always str):
name = input("Enter your name: ")Convert input:
age = int(input("Enter age: "))
price = float(input("Enter price: "))Printing:
print("Hello")
print("Name:", name, "Age:", age)
print(f"Name: {name}, Age: {age}")
print("a", "b", sep="-", end="!\n")if / elif / else
Basic structure:
if condition:
# block
...
elif other_condition:
...
else:
...Example:
age = 18
if age < 18:
print("Minor")
elif age == 18:
print("Just adult")
else:
print("Adult")One‑line conditional expression:
status = "adult" if age >= 18 else "minor"while Loops
Structure:
while condition:
# repeated block
...Example with counter:
count = 0
while count < 5:
print(count)
count += 1for Loops
Loop over a sequence:
for char in "abc":
print(char)
for item in [1, 2, 3]:
print(item)Ranges:
range(stop) # 0 .. stop-1
range(start, stop)
range(start, stop, step)
for i in range(5): # 0..4
print(i)
for i in range(1, 6, 2): # 1,3,5
print(i)break and continue
for i in range(10):
if i == 5:
break # exit loop
if i % 2 == 0:
continue # skip to next iteration
print(i)Lists
Create:
numbers = [1, 2, 3]
mixed = [1, "a", True]
empty = []Index and slice:
numbers[0] # first
numbers[-1] # last
numbers[1:3] # sliceModify:
numbers.append(4)
numbers.insert(1, 10)
numbers.remove(2)
popped = numbers.pop() # last elementIterate:
for n in numbers:
print(n)Check membership:
if 3 in numbers:
print("found")Tuples
Create (immutable sequences):
coords = (10, 20)
single = (5,) # note commaIndex:
coords[0]Tuple unpacking:
x, y = coordsDictionaries
Create:
person = {
"name": "Alice",
"age": 30
}Access and modify:
person["name"]
person["age"] = 31
person["city"] = "Paris"Safe get:
person.get("country", "Unknown")Iterate:
for key in person:
print(key, person[key])
for key, value in person.items():
print(key, value)Sets
Create:
items = {1, 2, 3}
empty_set = set()Basic operations:
items.add(4)
items.remove(2)
3 in items # membership
a = {1, 2, 3}
b = {3, 4}
a | b # union
a & b # intersection
a - b # differenceFunctions
Define and call:
def greet(name):
print("Hello", name)
greet("Alice")Return values:
def add(a, b):
return a + b
result = add(2, 3)Default parameters:
def power(base, exp=2):
return base ** exp
power(3) # 9
power(3, 3) # 27Imports and Modules
Basic import:
import math
x = math.sqrt(16)Import specific names:
from math import sqrt, pi
r = sqrt(9)Alias:
import numpy as npWorking with Files (Text)
Basic pattern:
with open("data.txt", "r", encoding="utf-8") as f:
text = f.read()
with open("out.txt", "w", encoding="utf-8") as f:
f.write("Hello\n")
Common modes: "r" (read), "w" (write, overwrite), "a" (append).
Exceptions (try / except)
Basic structure:
try:
x = int(input("Enter number: "))
except ValueError:
print("Not a valid integer")Multiple excepts and finally:
try:
with open("file.txt") as f:
data = f.read()
except FileNotFoundError:
print("File not found")
except PermissionError:
print("No permission")
finally:
print("Done")Raise an exception:
raise ValueError("Invalid value")Simple Classes (OOP Syntax)
Define a class:
class Person:
def __init__(self, name, age):
self.name = name # attribute
self.age = age
def greet(self):
print(f"Hi, I'm {self.name}")
p = Person("Alice", 30)
p.greet()Inheritance:
class Employee(Person):
def __init__(self, name, age, role):
super().__init__(name, age)
self.role = roleCommon Built‑in Functions (Syntax Shape)
Some useful built‑ins (names only, detailed meaning in other chapters):
len(obj)print(...)input(prompt)int(x),float(x),str(x),bool(x)list(iterable),tuple(iterable),set(iterable),dict(...)sum(iterable)min(iterable),max(iterable)sorted(iterable)range(...)enumerate(iterable)zip(iter1, iter2, ...)
Example patterns:
for index, value in enumerate(["a", "b"]):
print(index, value)
for a, b in zip([1, 2], [3, 4]):
print(a, b)Basic Boolean and None Checks
if value is None:
...
if value: # truthy check
...
else:
...List Comprehensions (Syntax Form)
squares = [x * x for x in range(5)]
evens = [x for x in range(10) if x % 2 == 0]Quick Style Reminders (Syntax‑Related)
- Indentation: 4 spaces, no tabs mixed with spaces.
- Block headers end with
::if,elif,else,for,while,def,class,try,except,finally,with. - Strings: prefer quotes in pairs
"..."or'...'. - Variable and function names:
lowercase_with_underscores.
Views: 0
Where to Move
Move chapter:
- ☰ 1. Chapter 1: What Is Programming?
- ☰ 1.1. What is a computer program?
- ☰ 1.2. What is Python?
- ☰ 1.3. Where is Python used?
- ☰ 1.4. How programming helps solve problems
- ☰ 1.5. Your first Python program
-
- ☰ 2. Chapter 2: Setting Up Python
- ☰ 2.1. Installing Python (Windows / macOS / Linux)
- ☰ 2.2. Using Python in the terminal
- ☰ 2.3. Using an IDE (IDLE / VS Code)
- ☰ 2.4. Running Python scripts
- ☰ 2.5. Python interactive mode
-
- ☰ 3. Chapter 3: Variables and Data Types
- ☰ 3.1. What is a variable?
- ☰ 3.2. Creating variables
- ☰ 3.3. Numbers
- ☰ 3.4. Test
- ☰ 3.5. Boolean values
- ☰ 3.6. Type checking
-
- ☰ 4. Chapter 4: Basic Operations
- ☰ 4.1. Arithmetic operations
- ☰ 4.2. Working with numbers
- ☰ 4.3. String operations
- ☰ 4.4. Combining text and variables
- ☰ 4.5. Comments in Python
-
- ☰ 5. Chapter 5: User Input and Output
- ☰ 5.1. Getting input from the user
- ☰ 5.2. Converting input to numbers
- ☰ 5.3. Formatting output
- ☰ 5.4. Writing interactive programs
-
- ☰ 6. Chapter 6: Conditions
- ☰ 6.1. Comparison operators
- ☰ 6.2. Logical operators
- ☰ 6.3. if, elif, else
- ☰ 6.4. Nested conditions
- ☰ 6.5. Common beginner mistakes
-
- ☰ 7. Chapter 7: Loops
- ☰ 7.1. Why loops are useful
- ☰ 7.2. for loops
- ☰ 7.3. while loops
- ☰ 7.4. Loop counters
- ☰ 7.5. break and continue
- ☰ 7.6. Loop exercises
-
- ☰ 8. Chapter 8: Data Collections
- ☰ 8.1. Lists
- ☰ 8.2. Tuples
- ☰ 8.3. Dictionaries
- ☰ 8.4. Sets (basics)
- ☰ 8.5. Choosing the right data structure
-
- ☰ 9. Chapter 9: Functions
- ☰ 9.1. Why functions matter
- ☰ 9.2. Defining functions
- ☰ 9.3. Parameters and arguments
- ☰ 9.4. Return values
- ☰ 9.5. Scope (local vs global)
- ☰ 9.6. Reusing code
-
- ☰ 10. Chapter 10: Working with Files
- ☰ 10.1. What is a file?
- ☰ 10.2. Reading text files
- ☰ 10.3. Writing and appending files
- ☰ 10.4. File paths
- ☰ 10.5. Simple file-based programs
-
- ☰ 11. Chapter 11: Errors and Debugging
- ☰ 11.1. Types of errors
- ☰ 11.2. Reading error messages
- ☰ 11.3. Common beginner errors
- ☰ 11.4. try and except
- ☰ 11.5. Debugging strategies
-
- ☰ 12. Chapter 12: Using Python Libraries
- ☰ 12.1. What is a library?
- ☰ 12.2. Importing modules
- ☰ 12.3. Standard libraries
- ☰ 12.3.1. math
- ☰ 12.3.2. random
- ☰ 12.3.3. datetime
-
- ☰ 12.4. Installing external libraries with pip
-
- ☰ 13. Chapter 13: Object-Oriented Programming
- ☰ 13.1. What is object-oriented programming?
- ☰ 13.2. Classes and objects
- ☰ 13.3. The `__init__` method
- ☰ 13.4. Attributes and methods
- ☰ 13.5. Encapsulation
- ☰ 13.6. Inheritance (basics)
- ☰ 13.7. Simple OOP examples
-
- ☰ 14. Chapter 14: Automation with Python
- ☰ 14.1. What is automation?
- ☰ 14.2. Automating simple tasks
- ☰ 14.3. Working with files and folders
- ☰ 14.4. Automating text processing
- ☰ 14.5. Scheduling scripts
- ☰ 14.6. Practical automation examples
-
- ☰ 15. Chapter 15: Web Development with Python
- ☰ 15.1. How the web works (basic overview)
- ☰ 15.2. Introduction to Flask
- ☰ 15.3. Creating a simple web server
- ☰ 15.4. Routing and templates
- ☰ 15.5. Handling user input (forms)
- ☰ 15.6. Very basic APIs
-
- ☰ 16. Chapter 16: Data Science with Python
- ☰ 16.1. What is data science?
- ☰ 16.2. Working with data
- ☰ 16.3. Introduction to NumPy
- ☰ 16.4. Introduction to pandas
- ☰ 16.5. Data visualization with matplotlib
- ☰ 16.6. Simple data analysis examples
-
- ☰ 17. Chapter 17: Mini Projects
- ☰ 17.1. Number guessing game
- ☰ 17.2. Simple calculator
- ☰ 17.3. To-do list
- ☰ 17.4. Password generator
- ☰ 17.5. Quiz application
- ☰ 17.6. Small web or data project
-
- ☰ 18. Chapter 18: Next Steps
- ☰ 18.1. How to practice Python
- ☰ 18.2. Writing clean and readable code
- ☰ 18.3. Choosing a specialization
- ☰ 18.3.1. Web development
- ☰ 18.3.2. Data science
- ☰ 18.3.3. Automation
- ☰ 18.3.4. Software development
-
- ☰ 18.4. Learning resources and communities
-
- ☰ 19. Appendix
- ☰ 19.1. Python syntax cheat sheet
- ☰ 19.2. Common errors and solutions
- ☰ 19.3. Glossary of terms
-
Comments
Please login to add a comment.
Don't have an account? Register now!