Python Cheat Sheet: Essential Guide for Beginners

Photo by AltumCode on Unsplash

Python Cheat Sheet: Essential Guide for Beginners

Python Essentials: Quick Reference for New Learners

This cheat sheet is designed as a helpful guide for those who have a solid understanding of Python basics. It serves as a convenient reference while coding in Python.

Variables and Strings

Variables are used as containers to store data values in python. A string is a sequence of characters, enclosed in either single or double quotes, used for representing text data.

#Using a variable
greetings = "Good Morning!"
print(greetings)

f-strings (using variables in strings)

f-strings enable the inclusion of variables within strings to create dynamic messages.

first_name = 'Sakib'
last_name = 'Kamal'
full_name = f"{first_name} {last_name}
print(full_name)

Lists

Lists are ordered collections of items, mutable (can be changed), enclosed in square brackets.

#Make a list
cars = ['bmw', 'audi', 'volvo']

#Get the first item in a list
first_car = cars[0]

#Get the last item in a list
last_car = cars[-1]

#Looping through a list
for car in cars:
    print(cars)

#Adding items to a list
cars = []
cars.append('bmw')
cars.append('audi')
cars.append('volvo')

#Making numerical lists
cubed_numbers = []
for i in range(1, 12):
    cubed_numbers.append(i ** 3)

print(cubed_numbers)

#List comprehensions
cubed_numbers = [i ** 3 for i in range(1, 12)]
print(cubed_numbers)

#Slicing a list
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Get the first three elements
first_three = my_list[:3]
print(first_three)  # Output: [1, 2, 3]

# Get elements from index 2 to index 5 (exclusive)
middle_part = my_list[2:5]
print(middle_part)  # Output: [3, 4, 5]

# Get elements from index 5 to the end
last_part = my_list[5:]
print(last_part)  # Output: [6, 7, 8, 9, 10]

# Get every second element
every_second = my_list[::2]
print(every_second)  # Output: [1, 3, 5, 7, 9]

# Reverse the list
reversed_list = my_list[::-1]
print(reversed_list)  # Output: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Tuples

Tuples are ordered collections of items, immutable (cannot be changed), enclosed in parentheses.

#Making a tuple
candidates = ('Steve', 'Bill', 'Erwin')
scores = ('120', '116', '132')

If Statements

If statements are conditional statements that execute code based on whether a specified condition evaluates to true or false.

#equal
x == 78

#not equal
x ! = 78

#greater than
x > 78

#greater than or equal to
x >= 78

#less than
x < 78

#less than or equal to
x <= 78

#Conditional tests with lists
'audi' in cars
'toyota' not in cars

#Assigning boolean values
camera_on = True
can_record = False

#A simple if test
if age >= 18:
    print("You can drive!")

#if-elif-else statements
x = 10

if x > 10:
    print("x is greater than 10")
elif x == 10:
    print("x is equal to 10")
else:
    print("x is less than 10")

Dictionaries

Dictionaries are collections of key-value pairs, unordered and mutable, accessed by keys rather than by their position.

# A simple dictionary
student = {"name": "Alice","age": 20}

# Accessing values in the dictionary
print("Name:", student["name"])

# Adding a new key-value pair
student["university"] = "XYZ University"

# Removing a key-value pair from the dictionary
del student["age"]

#Looping through all key value pairs
top_speeds = {'audi': 120, 'bmw': '190', 'volvo': 170}

for car, speed in top_speeds.items()
    print(f"{name} top speed is {speed}.")

#Looping through all keys
top_speeds = {'audi': 120, 'bmw': '190', 'volvo': 170}

for car in top_speeds.keys():
    print(f"{car} has some speed.")

#Looping through all the values
top_speeds = {'audi': 120, 'bmw': '190', 'volvo': 170}

for speed in top_speed.values():
    print(f"{speed} is the top speed.")

User input

Data provided by the user during program execution. All inputs are used as strings

#Prompting for a value
name = input("What's your name?")
print(f"Hello, {name}!")

age = input("How old are you?")
age = int(age)

pi = input("What's the value of pi? ")
pi = float(pi)

While loops

While loops repeatedly executes a block of code as long as a specified condition is true.

# A simple while loop
count = 1

while count <= 5:
    print(count)
    count += 1

#Letting the user choose when to quit
message = ''
while message != 'quit':
    message = input("What's your message? ")
    print(message)

Functions

Functions are blocks of reusable code that perform a specific task. They take inputs, perform operations and return outputs.

# A simple function
def print_hello():
    """Display a simple greeting."""
    print("Hello, welcome to the world of Python!")

print_hello()

# Passing an argument
def greet_user(username):
    """Display a personalized greeting"""
    print(f"Hello, {username}!")

greet_user('Reid')

# Default values for parameters
def icecream_flavors(flavor = 'strawberry')
    """Choose your favorite icecream flavor"""
    print(f"Have a {flavor} icecream!")

icecream_flavors()
icecream_flavors('vanilla')

# Returning a value
def add_numbers(x, y):
    """Add two numbers and return the sum"""
    return x+y

sum = add_numbers(2,8)
print(sum)

Classes

Classes are blueprints for creating objects in Python. They define the properties and behaviors of objects. The information in a class is stored in attributes and functions that belong to a class are called methods. A child class inherits the attributes and methods from its parent class.

#Creating a drone class
class Drone:
    """Represent a Drone."""

    def __init__(self,model)
    """Initialize user object"""
        self.model = model

    def fly(self):
        """Simulate flying"""
        print(f"{self.model} is flying.")

my_drone = Drone('QuadCopter')

print(f"{my_drone.model) is capable of long flights!")
my_drone.fly()
#Inheritance
class SearchDrone(Drone):
    """Represent a search and rescue drone."""
    def __init__(self,model):
    """Initialize the search and rescue drone."""
    super().__init__(name)

    def search(self):
        """Simulate search and rescue operation."""
        print(f"{self.model) is carrying a search and rescue mission")

my_drone = SearchDrone('UAV')

print(f"{my_drone.model} is a search and rescue drone.")
my_drone.fly()
my_drone.search()

Working with files

Working with files in Python involves reading from and writing to files on your computer's filesystem. Python provides built-in functions and methods for opening, reading, writing, and closing files. Files are opened in read mode ('r') by default, but can also be opened in write mode ('w') and append mode ('a').

#Reading a file and storingits lines
filename = "example.txt"
with open(filename, 'r') as file:
        lines = file.readlines()
        print("Lines in the file:")
for line in lines:
    print(line)

#Writing to a file
#The variable referring to the file object is often shortened to f.
filename = 'notes.txt'
with open(filename, 'w') as f:
    f.write("I love programming.")

#Appending to a file
filename = 'notes.txt'
with open(filename, 'a') as f:
    f.write("n\I love coding in python.")

Exceptions

Exception helps you respond to possible errors that are likely to occur. The code that might cause an error is put in the try block. Code that should run in response to an error goes in the except block. Code that should run only if the try block is successful goes in the else block.

try:
    # Code that may raise an exception
    x = 10 / 0  # Attempting to divide by zero
except ZeroDivisionError:
    # Handling the specific exception (division by zero)
    print("Error: You cannot divide by zero!")
else:
    # This block will execute if no exception occurs
    print("Division successful!")
finally:
    # This block will execute whether an exception occurs or not
    print("End of the program.")

Conclusion

This Python cheat sheet provides a concise yet comprehensive overview of essential concepts for beginners. By leveraging this guide, you can quickly reference key topics such as variables, strings, lists, tuples, if statements, dictionaries, user input, loops, functions, classes, file handling, and exceptions. Keep this cheat sheet handy to reinforce your understanding and enhance your coding efficiency in Python.