Learn Python basics with our concise Python Cheatsheet for Beginners! Quick tips, syntax, and examples to kickstart your coding journey.
Numbers
Python handles various types of numbers, including integers, floats, and complex numbers. Here are some common operations:
# Basic Arithmetic
print(10 + 5) # Addition > 15
print(10 - 5) # Subtraction > 5
print(10 * 5) # Multiplication > 50
print(10 / 5) # Division (float result) > 2.0
print(10 // 3) # Floor Division (integer result) > 3
print(10 % 3) # Modulus (remainder) > 1
print(2 ** 3) # Exponentiation > 8
# Built-in Number Functions
print(round(2.9)) # Rounds to nearest integer > 3
print(round(2.1)) # Rounds to nearest integer > 2
print(abs(-2.9)) # Absolute value > 2.9
print(max(1, 5, 2)) # Returns the largest item > 5
print(min(1, 5, 2)) # Returns the smallest item > 1
# Using the 'math' module (requires 'import math')
import math
print(math.ceil(2.1)) # Rounds up > 3
print(math.floor(2.9)) # Rounds down > 2
print(math.sqrt(25)) # Square root > 5.0
print(math.pi) # Value of pi > 3.141592653589793
print(math.e) # Value of Euler's number > 2.718281828459045
Strings
Strings are sequences of characters. Python offers powerful ways to manipulate them.
# String Creation
my_string = "Hello, Python!"
another_string = 'Python is fun!'
multi_line_string = """This is a
multi-line string."""
# String Concatenation
print("Hello" + " " + "World") # Joins strings > Hello World
print("Python" * 3) # Repeats string > PythonPythonPython
# String Length
print(len("Hello")) # Returns the number of characters > 5
# String Indexing (starts at 0)
print("Python"[0]) # First character > P
print("Python"[5]) # Last character > n
print("Python"[-1]) # Last character (negative indexing) > n
# String Slicing (start:end:step)
print("Python"[0:2]) # Characters from index 0 up to (but not including) 2 > Py
print("Python"[:3]) # Characters from beginning up to (but not including) 3 > Pyt
print("Python"[3:]) # Characters from index 3 to the end > hon
print("Python"[::2]) # Every second character > Pto
print("Python"[::-1]) # Reverses the string > nohtyP
# Common String Methods
print("hello".upper()) # Converts to uppercase > HELLO
print("HELLO".lower()) # Converts to lowercase > hello
print(" hello ".strip()) # Removes leading/trailing whitespace > hello
print("hello world".replace("world", "Python")) # Replaces substrings > hello Python
print("apple,banana,cherry".split(',')) # Splits string into a list > ['apple', 'banana', 'cherry']
print("Python is fun".startswith("Python")) # Checks if string starts with prefix > True
print("Python is fun".endswith("fun")) # Checks if string ends with suffix > True
print("Python".find("th")) # Returns the lowest index of substring > 2
print("Python".count("o")) # Returns the number of occurrences of substring > 1
# F-strings (Formatted String Literals) - Python 3.6+
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.") # > My name is Alice and I am 30 years old.
Lists
Lists are ordered, mutable collections of items.
# List Creation
my_list = [1, 2, 3, "apple", "banana"]
empty_list = []
# Accessing Elements
print(my_list[0]) # First element > 1
print(my_list[-1]) # Last element > banana
# Slicing Lists
print(my_list[1:3]) # Elements from index 1 up to (but not including) 3 > [2, 3]
# Modifying Lists
my_list[0] = 10 # Change an element
print(my_list) # > [10, 2, 3, 'apple', 'banana']
# Adding Elements
my_list.append("orange") # Adds to the end
print(my_list) # > [10, 2, 3, 'apple', 'banana', 'orange']
my_list.insert(1, "grape") # Inserts at a specific index
print(my_list) # > [10, 'grape', 2, 3, 'apple', 'banana', 'orange']
# Removing Elements
my_list.remove("apple") # Removes the first occurrence of a value
print(my_list) # > [10, 'grape', 2, 3, 'banana', 'orange']
popped_item = my_list.pop() # Removes and returns the last item
print(popped_item) # > orange
print(my_list) # > [10, 'grape', 2, 3, 'banana']
del my_list[0] # Deletes an item by index
print(my_list) # > ['grape', 2, 3, 'banana']
# my_list.clear() # Removes all items from the list
# List Length
print(len(my_list)) # Returns the number of items > 4
# Checking for Membership
print("grape" in my_list) # Checks if item exists > True
# Sorting Lists
numbers = [3, 1, 4, 1, 5, 9]
numbers.sort() # Sorts in-place
print(numbers) # > [1, 1, 3, 4, 5, 9]
sorted_numbers = sorted([5, 2, 8, 1]) # Returns a new sorted list
print(sorted_numbers) # > [1, 2, 5, 8]
Tuples
Tuples are ordered, immutable collections of items. Once created, their contents cannot be changed.
# Tuple Creation
my_tuple = (1, 2, "apple", "banana")
single_item_tuple = (5,) # Comma is essential for single-item tuples
empty_tuple = ()
# Accessing Elements (similar to lists)
print(my_tuple[0]) # First element > 1
print(my_tuple[-1]) # Last element > banana
# Slicing Tuples (similar to lists)
print(my_tuple[1:3]) # Elements from index 1 up to (but not including) 3 > (2, 'apple')
# Immutability
# my_tuple[0] = 10 # This would raise a TypeError
# Tuple Length
print(len(my_tuple)) # Returns the number of items > 4
# Checking for Membership
print("apple" in my_tuple) # Checks if item exists > True
# Counting Occurrences
print(my_tuple.count(1)) # Counts how many times an item appears > 1
# Finding Index
print(my_tuple.index("apple")) # Returns the index of the first occurrence > 2
Dictionaries
Dictionaries are unordered collections of key-value pairs. Keys must be unique and immutable.
# Dictionary Creation
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
empty_dict = {}
# Accessing Values
print(my_dict["name"]) # Access by key > Alice
print(my_dict.get("age")) # Safely access, returns None if key not found > 30
print(my_dict.get("country", "Unknown")) # Returns default if key not found > Unknown
# Adding/Modifying Items
my_dict["email"] = "[email protected]" # Adds a new key-value pair
print(my_dict) # > {'name': 'Alice', 'age': 30, 'city': 'New York', 'email': '[email protected]'}
my_dict["age"] = 31 # Modifies an existing value
print(my_dict) # > {'name': 'Alice', 'age': 31, 'city': 'New York', 'email': '[email protected]'}
# Removing Items
del my_dict["city"] # Deletes a key-value pair
print(my_dict) # > {'name': 'Alice', 'age': 31, 'email': '[email protected]'}
popped_value = my_dict.pop("age") # Removes and returns the value for the key
print(popped_value) # > 31
print(my_dict) # > {'name': 'Alice', 'email': '[email protected]'}
# my_dict.clear() # Removes all items
# Dictionary Length
print(len(my_dict)) # Returns the number of key-value pairs > 2
# Getting Keys, Values, and Items
print(my_dict.keys()) # Returns a view of all keys > dict_keys(['name', 'email'])
print(my_dict.values()) # Returns a view of all values > dict_values(['Alice', '[email protected]'])
print(my_dict.items()) # Returns a view of all key-value pairs as tuples > dict_items([('name', 'Alice'), ('email', '[email protected]')])
# Checking for Key Existence
print("name" in my_dict) # Checks if key exists > True
Sets
Sets are unordered collections of unique, immutable items. They are useful for membership testing and eliminating duplicate entries.
# Set Creation
my_set = {1, 2, 3, 2, 1} # Duplicates are automatically removed
print(my_set) # > {1, 2, 3} (order is not guaranteed)
empty_set = set() # Use set() for an empty set, not {} (which creates an empty dictionary)
# Adding Elements
my_set.add(4) # Adds a single element
print(my_set) # > {1, 2, 3, 4}
my_set.update([5, 6]) # Adds multiple elements from an iterable
print(my_set) # > {1, 2, 3, 4, 5, 6}
# Removing Elements
my_set.remove(6) # Removes an element; raises KeyError if not found
print(my_set) # > {1, 2, 3, 4, 5}
my_set.discard(7) # Removes an element if present; does nothing if not found
print(my_set) # > {1, 2, 3, 4, 5}
popped_item = my_set.pop() # Removes and returns an arbitrary element
print(popped_item) # (e.g., 1)
print(my_set) # (e.g., {2, 3, 4, 5})
# my_set.clear() # Removes all elements
# Set Operations
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print(set1.union(set2)) # All unique elements from both sets > {1, 2, 3, 4, 5, 6}
print(set1 | set2) # Union operator > {1, 2, 3, 4, 5, 6}
print(set1.intersection(set2)) # Elements common to both sets > {3, 4}
print(set1 & set2) # Intersection operator > {3, 4}
print(set1.difference(set2)) # Elements in set1 but not in set2 > {1, 2}
print(set1 - set2) # Difference operator > {1, 2}
print(set1.symmetric_difference(set2)) # Elements unique to each set > {1, 2, 5, 6}
print(set1 ^ set2) # Symmetric difference operator > {1, 2, 5, 6}
# Membership Test
print(3 in my_set) # Checks if an element is in the set > True
Control Flow (If/Else, Loops)
These structures allow you to control the order in which your code executes.
# If/Else Statements
x = 10
if x > 5:
print("x is greater than 5") # > x is greater than 5
elif x == 5:
print("x is 5")
else:
print("x is less than 5")
# Ternary Operator (Conditional Expressions)
status = "Adult" if x >= 18 else "Minor"
print(status) # > Adult
# For Loops (Iterating over sequences)
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# > apple
# > banana
# > cherry
for i in range(3): # range(n) generates numbers from 0 to n-1
print(i)
# > 0
# > 1
# > 2
for i in range(1, 4): # range(start, stop)
print(i)
# > 1
# > 2
# > 3
for i in range(0, 10, 2): # range(start, stop, step)
print(i)
# > 0
# > 2
# > 4
# > 6
# > 8
# While Loops
count = 0
while count < 3:
print(f"Count: {count}")
count += 1
# > Count: 0
# > Count: 1
# > Count: 2
# Break and Continue
for i in range(5):
if i == 2:
continue # Skips the rest of the current iteration
if i == 4:
break # Exits the loop entirely
print(i)
# > 0
# > 1
# > 3
Functions
Functions are blocks of reusable code that perform a specific task.
# Defining a Function
def greet(name):
"""This function greets the person passed in as a parameter."""
return f"Hello, {name}!"
print(greet("Alice")) # Calling the function > Hello, Alice!
# Function with Default Parameters
def power(base, exponent=2):
return base ** exponent
print(power(3)) # Uses default exponent > 9
print(power(3, 3)) # Overrides default exponent > 27
# Arbitrary Arguments (*args)
def sum_all(*args):
total = 0
for num in args:
total += num
return total
print(sum_all(1, 2, 3, 4)) # > 10
# Keyword Arguments (**kwargs)
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Bob", age=25)
# > name: Bob
# > age: 25
# Lambda Functions (Anonymous Functions)
add_two = lambda x: x + 2
print(add_two(5)) # > 7
# Higher-order functions with lambda
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x*x, numbers))
print(squared_numbers) # > [1, 4, 9, 16, 25]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # > [2, 4]












