This cheat sheet covers the fundamental syntax of Python, including variables, data types, operators, conditionals, loops, functions, and common built-in functions. It serves as a quick reference guide for both beginners and experienced Python developers.
Variables and Data Types
Assigning Variables
x = 10 # Integer
y = 3.14 # Float
name = "John" # String
is_valid = True # Boolean
Data Types
type(10) # <class 'int'> type(3.14) # <class 'float'> type("Hello") # <class 'str'> type(True) # <class 'bool'>
Multiple Assignment
a, b, c = 1, 2, 3
x = y = z = 0 # Assign the same value to multiple variables
Type Conversion
int("10") # 10
float("3.14") # 3.14
str(100) # "100"
bool(0) # False
Operators
Arithmetic Operators
5 + 3 # Addition -> 8
5 - 3 # Subtraction -> 2
5 * 3 # Multiplication -> 15
5 / 3 # Division -> 1.666...
5 // 3 # Floor Division -> 1
5 % 3 # Modulus -> 2
5 ** 3 # Exponentiation -> 125
Comparison Operators
5 == 3 # False
5 != 3 # True
5 > 3 # True
5 < 3 # False
5 >= 3 # True
5 <= 3 # False
Logical Operators
True and False # False
True or False # True
not True # False
Assignment Operators
x = 10
x += 5 # x = x + 5
x -= 2 # x = x - 2
x *= 3 # x = x * 3
x /= 2 # x = x / 2
x %= 4 # x = x % 4
Conditionals
If-Else Statements
x = 10
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is 5")
else:
print("x is less than 5")
Loops
For Loop
for i in range(5): # 0 to 4
print(i)
While Loop
x = 0
while x < 5:
print(x)
x += 1
Loop Control Statements
for i in range(10):
if i == 5:
break # Stops the loop
if i % 2 == 0:
continue # Skips even numbers
print(i)
Functions
Defining Functions
def greet(name):
return "Hello, " + name
print(greet("Alice")) # "Hello, Alice"
Default Parameters
def greet(name="User"):
return "Hello, " + name
print(greet()) # "Hello, User"
Lambda Functions
square = lambda x: x * x
print(square(4)) # 16
Lists
Creating and Accessing Lists
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # "apple"
print(fruits[-1]) # "cherry"
List Methods
fruits.append("orange") # Add item
fruits.remove("banana") # Remove item
fruits.pop() # Remove last item
fruits.sort() # Sort list
Dictionaries
Creating and Accessing Dictionaries
person = {"name": "John", "age": 30}
print(person["name"]) # "John"
Dictionary Methods
person.keys() # Get all keys
person.values() # Get all values
person.items() # Get key-value pairs
Tuples
Creating and Accessing Tuples
colors = ("red", "green", "blue")
print(colors[1]) # "green"
Immutable Nature
# colors[1] = "yellow" # TypeError: 'tuple' object does not support item assignment
Sets
Creating and Using Sets
numbers = {1, 2, 3, 4}
numbers.add(5)
numbers.remove(2)
print(numbers)
String Manipulation
String Methods
text = "hello world"
print(text.upper()) # "HELLO WORLD"
print(text.lower()) # "hello world"
print(text.title()) # "Hello World"
print(text.replace("world", "Python")) # "hello Python"
String Formatting
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
File Handling
Reading a File
with open("file.txt", "r") as file:
content = file.read()
print(content)
Writing to a File
with open("file.txt", "w") as file:
file.write("Hello, world!")
Exception Handling
Try-Except Block
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Handling Multiple Exceptions
try:
num = int(input("Enter a number: "))
print(10 / num)
except (ValueError, ZeroDivisionError):
print("Invalid input!")
Tips and Sources
Useful Tips
- Indentation is crucial in Python. Use 4 spaces per indent.
- Use list comprehensions for concise code:
squares = [x**2 for x in range(10)]
- Use enumerate() to get index-value pairs in loops:
for index, value in enumerate(["a", "b", "c"]): print(index, value)
- Use zip() to iterate over multiple lists:
names = ["Alice", "Bob"] scores = [85, 92] for name, score in zip(names, scores): print(name, score)