We use cookies to personalize content and ads, to offer features for social media and to analyze the access to our website. We also share information about your use of our website with our social media, weaving and analytics partners. Our partners may combine this information with other information that you have provided to them or that they have collected as part of your use of the Services. You accept our cookies when you click "Allow cookies" and continue to use this website.

# Ultimate Python Cheat sheet for Beginners

Are you ready to dive into the world of coding with Python? With this comprehensive cheat sheet, you'll learn everything you need to know to start coding with confidence. From basic data types to complex class structures, we've got you covered. You'll learn how to store and manipulate data using variables and data types, how to store collections of data using lists, tuples, and dictionaries, how to write reusable code using functions, control the flow of your program, read from and write to files, and much more.

Get ready to take your coding skills to the next level with our detailed explanations and creative examples of the topics including Exception Handling, Decorators, Generators and Iterators, Regular Expressions, API Requests, JSON and XML, Debugging and Testing, and more. Whether you're a complete beginner or looking to brush up on your skills, this cheat sheet will help you get ahead of the game and tackle any coding challenge that comes your way.

So, what are you waiting for? Let's get started!

Coding Be my Python Coding teacher and I want you to create me a coding examples to cover everything in a category for a python cheat-sheet. I want you to be creative in variables names. Here is my category:

### Variables and Data Types: Learn how to store and manipulate data using basic data types like integers, floats, strings, and booleans.

1. Integers
``````# declaring and assigning an integer value
age_of_universe = 14_000_000_000
light_years = age_of_universe + 5_000_000
# multiplying two integers
number_of_stars = age_of_universe * 100_000
# dividing two integers
galaxies_per_light_year = age_of_universe / light_years
# performing modulo operation on two integers
remaining_stars = number_of_stars % 100
print("Age of Universe (in years):", age_of_universe)
print("Light Years:", light_years)
print("Number of Stars:", number_of_stars)
print("Galaxies per Light Year:", galaxies_per_light_year)
print("Remaining Stars:", remaining_stars)
``````
1. Floats
``````# declaring and assigning a float value
temperature_of_sun = 5_500.0
total_heat = temperature_of_sun + 500.0
# multiplying two floats
joules = temperature_of_sun * 4.184
# dividing two floats
heat_ratio = temperature_of_sun / total_heat
# rounding a float
rounded_temperature = round(temperature_of_sun, 2)
print("Temperature of Sun (in Kelvin):", temperature_of_sun)
print("Total Heat:", total_heat)
print("Joules:", joules)
print("Heat Ratio:", heat_ratio)
print("Rounded Temperature:", rounded_temperature)
``````
1. Strings
``````# declaring and assigning a string value
planet = "Earth"
# concatenating two strings
full_name = planet + "ling"
# repeating a string
moons = planet * 3
# checking length of a string
planet_length = len(planet)
# accessing individual characters in a string
first_letter = planet
last_letter = planet[-1]
print("Planet:", planet)
print("Full Name:", full_name)
print("Moons:", moons)
print("Length of Planet:", planet_length)
print("First Letter:", first_letter)
print("Last Letter:", last_letter)
``````
1. Booleans
``````# declaring and assigning a boolean value
is_earth_flat = False
# negating a boolean value
is_earth_round = not is_earth_flat
# using booleans in control flow statements
if is_earth_flat:
print("Earth is flat.")
else:
print("Earth is round.")
print("Is Earth Flat?", is_earth_flat)
print("Is Earth Round?", is_earth_round)
``````

### Lists and Tuples: Learn how to store collections of data using lists and tuples, including indexing, slicing, and iteration.

1. Creating and Accessing Lists:
``````# declaring and initializing a list
planet_names = ["Mercury", "Venus", "Earth", "Mars", "Jupiter"]
# accessing values using indices
first_planet = planet_names
last_planet = planet_names[-1]
print("First Planet:", first_planet)
print("Last Planet:", last_planet)
``````
1. Modifying Lists:
``````# modifying values in a list
planet_names = "Terra"
planet_names.append("Saturn")
planet_names.insert(3, "Eris")
print("Planet Names:", planet_names)
``````
1. Removing Values:
``````# removing values from a list
planet_names.remove("Jupiter")
del planet_names
print("Planet Names:", planet_names)
``````
1. Looping Through Lists:
``````# using for loop to iterate through a list
for planet in planet_names:
print(planet)
# using enumerate to iterate through a list with indices
for i, planet in enumerate(planet_names):
print(f"{i}: {planet}")
``````
1. Creating and Accessing Tuples::
``````# declaring and initializing a tuple
planet_data = ("Earth", "Terrestrial", 1, 6371.0, 149.6)
# accessing values using indices
planet_name = planet_data
planet_type = planet_data
print("Planet Name:", planet_name)
print("Planet Type:", planet_type)
``````
1. Looping Through Tuples:
``````# using for loop to iterate through a tuple
for value in planet_data:
print(value)
# using enumerate to iterate through a tuple with indices
for i, value in enumerate(planet_data):
print(f"{i}: {value}")
``````

### Dictionaries: Learn how to store key-value pairs using dictionaries, including accessing and modifying values.

1. Creating and Accessing Dictionaries:
``````# declaring and initializing a dictionary
planet_data = {
"name": "Earth",
"type": "Terrestrial",
"moons": 1,
"distance_from_sun": 149.6
}
# accessing values using keys
planet_name = planet_data["name"]
planet_type = planet_data["type"]
print("Planet Name:", planet_name)
print("Planet Type:", planet_type)
``````
1. Modifying Values:
``````# modifying values in a dictionary
planet_data["moons"] = 2
planet_data["distance_from_sun"] = 150.0
planet_data["mass"] = 5.97
planet_data["temperature"] = 15.0
print("Planet Data:", planet_data)
``````
1. Removing Key-Value Pairs:
``````# removing key-value pairs
# checking if a key exists in a dictionary
has_mass = "mass" in planet_data
print("Planet Data:", planet_data)
print("Has Mass?", has_mass)
``````
1. Looping Through Dictionaries:
``````# using for loop to iterate through key-value pairs
for key, value in planet_data.items():
print(f"{key}: {value}")
# using for loop to iterate through keys only
for key in planet_data.keys():
print(key)
# using for loop to iterate through values only
for value in planet_data.values():
print(value)
``````

### Functions: Learn how to write reusable code using functions, including defining, calling, and returning values.

1. Defining Functions:
``````# defining a function to calculate the area of a circle
area = 3.14 * (radius ** 2)
return area
# defining a function to concatenate two strings
def join_strings(string1, string2):
joined_string = string1 + string2
return joined_string
``````
1. Calling Functions:
``````# calling the function to calculate the area of a circle
print("Circle 1 Area:", circle1_area)
# calling the function to concatenate two strings
string1 = "Hello "
string2 = "World!"
joined_string = join_strings(string1, string2)
print("Joined String:", joined_string)
``````
1. Return Values:
``````# using the return value of a function in another function
volume = (4/3) * 3.14 * (radius ** 3)
return volume
surface_area = 4 * 3.14 * (radius ** 2)
return surface_area
print("Sphere Volume:", sphere_volume)
print("Sphere Surface Area:", sphere_surface_area)
``````
1. Arguments:
``````# using default arguments in a function
def greet(name, greeting="Hello"):
message = greeting + " " + name
return message
print(greet("John"))
print(greet("Jane", "Hi"))
# using variable length arguments in a function
def sum_numbers(*numbers):
total = 0
for number in numbers:
total += number
print(sum_numbers(1, 2, 3, 4))
print(sum_numbers(10, 20, 30))
``````
1. Scope:
``````# demonstrating scope of variables in a function
def modify_variable():
global x
x = 10
y = 5
return x + y
x = 5
result = modify_variable()
print("Result:", result)
print("X:", x)
``````

### Control Flow: Learn how to control the flow of a program using if-else statements, for and while loops, and break and continue statements.

``````# If-Else statements
is_raining = True
if is_raining:
print("Better bring an umbrella!")
else:
print("The sun is shining, let's go for a walk!")
# For loops
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# While loops
counter = 0
while counter < 5:
print(counter)
counter += 1
# Break statement
fruits = ["apple", "banana", "cherry", "date"]
for fruit in fruits:
if fruit == "date":
break
print(fruit)
# Continue statement
fruits = ["apple", "banana", "cherry", "date"]
for fruit in fruits:
if fruit == "banana":
continue
print(fruit)
``````

### File I/O: Learn how to read from and write to files, including opening and closing files, reading and writing data, and handling exceptions.

``````# Opening and closing files
file = open("fruits.txt", "w")
file.write("apple\nbanana\ncherry\n")
file.close()
file = open("fruits.txt", "r")
for fruit in fruits:
print(fruit)
file.close()
# Writing to files
file = open("veggies.txt", "w")
file.write("carrot\ncelery\npepper\n")
file.close()
# Handling exceptions
try:
file = open("nonexistent.txt", "r")
print(contents)
except FileNotFoundError:
print("The file does not exist.")
finally:
file.close()
# Writing to a .csv file
import csv
with open('employees.csv', 'w', newline='') as csvfile:
fieldnames = ['Name', 'Department', 'Position']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writerow({'Name': 'John Doe', 'Department': 'Marketing', 'Position': 'Manager'})
writer.writerow({'Name': 'Jane Doe', 'Department': 'Engineering', 'Position': 'Developer'})
# Reading from a .csv file
import csv
with open('employees.csv', 'r') as csvfile:
print(row['Name'], row['Department'], row['Position'])
# Writing to a .sql file
with open("employees.sql", "w") as sql_file:
sql_file.write("INSERT INTO employees (Name, Department, Position) VALUES\n")
sql_file.write("('John Doe', 'Marketing', 'Manager'),\n")
sql_file.write("('Jane Doe', 'Engineering', 'Developer');\n")
# Reading from a .sql file
with open("employees.sql", "r") as sql_file:
``````

### Modules and Packages: Learn how to organize your code into reusable modules and packages, and how to import and use code from other modules.

``````# Defining a module named `my_module` that contains a function `greet`
def greet(name):
return f"Hello, {name}!"
# Importing the `greet` function from the `my_module` module
import my_module
print(my_module.greet("Alice")) # Output: Hello, Alice!
# Using an alias for the imported module
import my_module as mm
print(mm.greet("Bob")) # Output: Hello, Bob!
# Importing only the desired function from the module
from my_module import greet
print(greet("Charlie")) # Output: Hello, Charlie!
# Creating a package named `my_package` with two modules `module_1` and `module_2`
# my_package/
#     __init__.py
#     module_1.py
#     module_2.py
# Importing a function from a module in the package
from my_package.module_1 import say_hi
print(say_hi()) # Output: Hi from module 1!
# Importing multiple functions from multiple modules in the package
from my_package.module_1 import say_hi, say_bye
from my_package.module_2 import say_hello
print(say_hi()) # Output: Hi from module 1!
print(say_bye()) # Output: Bye from module 1!
print(say_hello()) # Output: Hello from module 2!
``````

### Exception Handling: Learn how to handle exceptions and errors in your code, including raising and catching exceptions, and using try-except blocks.

``````# Example 1: Raising an exception
def divide(numerator, denominator):
if denominator == 0:
raise ValueError("Cannot divide by zero.")
return numerator / denominator
try:
result = divide(5, 0)
print(result)
except ValueError as e:
print("Error:", e)
# Output: Error: Cannot divide by zero.
# Example 2: Catching multiple exceptions
def open_file(filename):
try:
with open(filename, "r") as f:
except FileNotFoundError:
except PermissionError:
print("Error: Permission denied.")
file_content = open_file("nonexistent.txt")
# Example 3: Catching any exception
def parse_integer(value):
try:
return int(value)
except:
print("Error: Cannot parse value as integer.")
parsed_integer = parse_integer("abc")
# Output: Error: Cannot parse value as integer.
# Example 4: Using finally
def handle_file(filename):
try:
with open(filename, "r") as f:
except:
finally:
print("Closing file.")
file_content = handle_file("nonexistent.txt")
# Output: Error: Cannot read file.
#         Closing file.
``````

### Classes and Objects: Learn how to create and use objects and classes in Python, including defining and instantiating classes, and using class methods and attributes.

1. Defining a Class:
``````class Kite:
wings = 2
def fly(self):
print("The kite is soaring high!")
red_kite = Kite()
print(red_kite.wings) # Output: 2
red_kite.fly() # Output: The kite is soaring high!
``````
1. Initializing Objects:
``````class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
print(fido.name) # Output: Fido
``````
1. Class Methods:
``````class Circle:
pi = 3.14
def area(self):
return Circle.pi * (self.radius ** 2)
my_circle = Circle(5)
print(my_circle.area()) # Output: 78.5
``````
1. Class Attributes:
``````class Car:
wheels = 4
def __init__(self, make, model):
self.make = make
self.model = model
my_car = Car("Toyota", "Camry")
print(my_car.wheels) # Output: 4
print(Car.wheels) # Output: 4
``````
1. Inheritance:
``````class Animal:
def __init__(self, name, species):
self.name = name
self.species = species
def make_sound(self, sound):
print(f"{self.name} makes a {sound} sound.")
class Dog(Animal):
def __init__(self, name, breed):
Animal.__init__(self, name, species="Dog")
self.breed = breed
fido.make_sound("bark") # Output: Fido makes a bark sound.
``````

### Decorators: Learn how to modify the behavior of functions and classes using decorators, including defining and applying decorators.

1. `TimeWarp` - a decorator that records the time it takes for a function to run, and prints the result:
``````import time
def TimeWarp(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"Time elapsed in {func.__name__}: {end - start} seconds")
return result
return wrapper
@TimeWarp
def power_numbers(base, exponent):
return base**exponent
power_numbers(2, 10)
# Output:
# Time elapsed in power_numbers: 3.814697265625e-06 seconds
# 1024
``````
1. `shiny_badge` - a decorator that adds a shiny gold badge to the result of a function:
``````def shiny_badge(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return f"🥇 {result}"
return wrapper
def greet(name):
return f"Hello, {name}!"
greet("John")
# Output:
# 🥇 Hello, John!
``````
1. `sugar_coat` - a decorator that adds a sweet message to the result of a function:
``````def sugar_coat(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return f"❤️ {result} ❤️"
return wrapper
@sugar_coat
def compliment():
return "You look gorgeous today!"
compliment()
# Output:
# ❤️ You look gorgeous today! ❤️
``````
1. `double_trouble` - a decorator that doubles the result of a function:
``````def double_trouble(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result * 2
return wrapper
@double_trouble
def count_apples():
return 5
count_apples()
# Output: 10
``````
1. `secret_decoder` - a decorator that applies a secret code to the result of a function:
``````def secret_decoder(secret_code):
def decorator(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
coded_result = ""
for char in result:
coded_result += chr(ord(char) + secret_code)
return coded_result
return wrapper
return decorator
@secret_decoder(3)
def send_message():
return "Meet me at the park at 4 PM"
send_message()
# Output:
# Phhw ph dw wkh sdun dw 7 QR
``````

### Generators and Iterators: Learn how to generate sequences of values using generators, and how to iterate over sequences using iterators.

``````# Defining a generator function that yields values one at a time
def rainbow_generator():
yield "red"
yield "orange"
yield "yellow"
yield "green"
yield "blue"
yield "indigo"
yield "violet"
# Creating an iterator from the generator
spectrum = rainbow_generator()
# Accessing values in the iterator one at a time
print(next(spectrum)) # Output: "red"
print(next(spectrum)) # Output: "orange"
# Using a for loop to iterate over the values in the iterator
for color in rainbow_generator():
print(color)
# Output:
# red
# orange
# yellow
# green
# blue
# indigo
# violet
# Defining a generator expression that yields values one at a time
squared_numbers = (num**2 for num in range(1, 6))
# Accessing values in the generator expression one at a time
print(next(squared_numbers)) # Output: 1
print(next(squared_numbers)) # Output: 4
# Using a for loop to iterate over the values in the generator expression
for squared_num in (num**2 for num in range(1, 6)):
print(squared_num)
# Output:
# 1
# 4
# 9
# 16
# 25
``````

### Regular Expressions: Learn how to match and extract patterns in text using regular expressions, including using the re module in Python.

``````import re
# Match a word in a string using regular expressions
poem = "Roses are red, violets are blue"
word = re.search(r"\bviolets\b", poem)
print("Matched word:", word.group())
# Extract all the words starting with a specific letter
words = re.findall(r"\b[rR]\w+", poem)
print("Words starting with 'r' or 'R':", words)
# Replace specific pattern in a string
replaced_poem = re.sub(r"\bviolets\b", "sunflowers", poem)
print("Replaced poem:", replaced_poem)
# Split a string using a regular expression
split_poem = re.split(r",\s", poem)
print("Split poem:", split_poem)
# Check if a string matches a pattern
is_match = re.match(r"Roses\sare\sred", poem)
print("String matches pattern:", bool(is_match))
``````

In this example, we used the `re` module in Python to perform various operations with regular expressions such as matching, extracting, replacing, splitting and checking if a string matches a pattern. The `re` module provides various methods such as `search`, `findall`, `sub`, `split`, and `match` to perform these operations.

The `r` before the regular expression pattern in the examples is used to indicate a raw string, which helps to avoid escape sequences in the pattern.

### API Requests: Learn how to make API requests using the requests library in Python, including GET and POST requests, and handling response data.

``````import requests
# Making a GET request to retrieve data from an API
url = "https://api.example.com/endpoint"
response = requests.get(url)
# Check the status code of the response to ensure the request was successful
if response.status_code == 200:
# Extract the data from the response
data = response.json()
# Do something with the data
print(data)
else:
# Handle error if the request was unsuccessful
print("Request failed with status code:", response.status_code)
# Making a POST request to send data to an API
url = "https://api.example.com/endpoint"
"key1": "value1",
"key2": "value2",
}
# Check the status code of the response to ensure the request was successful
if response.status_code == 201:
# Extract the data from the response
data = response.json()
# Do something with the data
print(data)
else:
# Handle error if the request was unsuccessful
print("Request failed with status code:", response.status_code)
``````

In the above examples, `requests.get()` is used to make a GET request to the API endpoint, and `requests.post()` is used to make a POST request to the API endpoint. The `json` parameter is used to send data in the request body. The `response.status_code` property is used to check the status code of the response, and the `response.json()` method is used to extract the data from the response in JSON format.

### JSON and XML: Learn how to parse and generate JSON and XML data in Python, including using the json and xml libraries.

1. Parsing and Generating JSON:
``````import json
# Parsing JSON data
json_data = '{"name": "John", "age": 30, "city": "New York"}'
print("Parsed JSON data: ", parsed_data)
# Generating JSON data
data = {"name": "Jane", "age": 25, "city": "London"}
json_string = json.dumps(data, indent=4)
print("\nGenerated JSON data:")
print(json_string)
``````
1. Parsing and Generating XML:
``````import xml.etree.ElementTree as ET
# Parsing XML data
xml_data = """
<data>
<person>
<name>John</name>
<age>30</age>
<city>New York</city>
</person>
</data>
"""
parsed_xml = ET.fromstring(xml_data)
for child in parsed_xml:
print("Person details:")
print("Name:", child.find("name").text)
print("Age:", child.find("age").text)
print("City:", child.find("city").text)
# Generating XML data
root = ET.Element("data")
person = ET.SubElement(root, "person")
name = ET.SubElement(person, "name")
name.text = "Jane"
age = ET.SubElement(person, "age")
age.text = "25"
city = ET.SubElement(person, "city")
city.text = "London"
xml_string = ET.tostring(root, encoding="unicode")
print("\nGenerated XML data:")
print(xml_string)
``````

### Debugging and Testing: Learn how to debug your code using the Python debugger, and how to write tests for your code using the unittest library.

1. Debugging
``````def tasty_cake(ingredients):
for ingredient in ingredients:
if ingredient == 'love':
return 'This cake is made with love and is therefore delicious!'
elif ingredient == 'poison':
import pdb; pdb.set_trace() # Debugging code
return 'This cake is made with poison and is therefore dangerous!'
else:
return 'This cake is made with unknown ingredients and may not be safe to eat.'
ingredients = ['flour', 'sugar', 'love']
print(tasty_cake(ingredients))
``````

In the above example, if the `ingredient` is 'poison', we start a debug session with the Python debugger (pdb) using `pdb.set_trace()`. This allows us to step through the code and inspect variables to figure out what's going wrong.

1. Testing
``````
import unittest
def sum_numbers(a, b):
return a + b
class TestSumNumbers(unittest.TestCase):
def test_sum_numbers(self):
result = sum_numbers(3, 4)
self.assertEqual(result, 7)
if __name__ == '__main__':
unittest.main()
``````

In the above example, we define a function `sum_numbers` that takes two arguments `a` and `b`, and returns their sum. We then define a test case `TestSumNumbers` that tests this function using the `unittest` library. The `test_sum_numbers` method tests that the `sum_numbers` function returns the correct result for the inputs `3` and `4`. To run the tests, we use `unittest.main()`. If all tests pass, the output will be `.`, indicating that one test has been run and passed. If a test fails, the output will indicate which test has failed and why. 