logo.png

Python Cheat Sheet

Saturday, September 21, 2024

Articles/Python Cheat Sheet

It's kind of like a cheat code list, but for Python

What? I didn’t ask for your email just to send you countless messages trying to sell you something. I don’t want to start our relationship like this. Just enjoy the free Python cheat sheet without any strings attached!

Variables and Strings

Variables: Assign labels to values.
greeting = "Hi there!"

Strings: Series of characters in quotes.
greeting = "Hi there!"
print(greeting)

f-strings: Embed variables in strings.
first_name = 'charles'
last_name = 'darwin'
full_name = f"{first_name} {last_name}"
​print(full_name)

Lists

Create a list:
fruits = ['apple', 'banana', 'cherry']

Accessing items:
first_fruit = fruits[0]
last_fruit = fruits[-1]

Loop through a list:
for fruit in fruits:
    print(fruit)

Add items:
fruits.append('orange')
fruits.append('grape')

Numerical lists:
cubes = [x**3 for x in range(1, 6)]

Slicing:
top_three = fruits[:3]

Copy a list:
copy_of_fruits = fruits[:]

Turples

Create a tuple:
coordinates = (2560, 1440)
​formats = ('HD', 'Full HD', '4K')

If statements

Conditional tests:
y == 100
y != 100
y > 100
y >= 100
y < 100
y <= 100

Conditional tests with lists:
'apple' in fruits
'pear' not in fruits

Boolean values:
is_active = True
can_delete = False

Simple if statement:
if age >= 21:
    print("You are a donkey!")

If-elif-else:
if age < 5:
    ticket_cost = 0
elif age < 12:
    ticket_cost = 5
elif age < 60:
    ticket_cost = 20
else:
​    ticket_cost = 10

Dictionaries

Create a dictionary:
car = {'make': 'Toyota', 'model': 'Camry'}

Access a value:
print(f"The car's model is {car['model']}.")

Add a key-value pair:
car['year'] = 2020

Loop through key-value pairs:
favorite_colors = {'alice': 'blue', 'bob': 'green', 'carol': 'red'}
for person, color in favorite_colors.items():
    print(f"{person} loves {color}.")

Loop through keys:
for person in favorite_colors.keys():
    print(f"{person} has a favorite color.")

Loop through values:
for color in favorite_colors.values():
​    print(f"{color} is a favorite color.")

User Input

Prompting for input:
name = input("What's your name? ")
print(f"Hi, {name}!")

Numerical input:
age = int(input("How old are you? "))
​pi_value = float(input("What's the value of pi? "))

While Loops

Simple while loop:
count = 1
while count <= 3:
    print(count)
    count += 1

User decides when to quit:
message = ''
while message != 'exit':
    message = input("What's your message? ")
    if message != 'exit':
​        print(message)

Functions

Define a function:
def say_hello():
    """Display a simple greeting."""
    print("Hello there!")
say_hello()

Function with argument:
def greet_user(name):
    """Display a personalized greeting."""
    print(f"Hello, {name}!")
greet_user('alex')

Default parameter value:
def make_burger(topping='lettuce'):
    """Make a burger with a single topping."""
    print(f"Have a burger with {topping}!")
make_burger()
make_burger('tomato')

Returning a value:
def multiply_numbers(a, b):
    """Multiply two numbers and return the result."""
    return a * b
result = multiply_numbers(4, 5)
​print(result)

Classes

Create a class:
class Cat:
    """Represent a cat."""
    def __init__(self, name):
        """Initialize cat object."""
        self.name = name
    def meow(self):
        """Simulate meowing."""
        print(f"{self.name} says meow!")
my_cat = Cat('Whiskers')
print(f"{my_cat.name} is a lovely cat!")
my_cat.meow()

Inheritance:
class RescueCat(Cat):
    """Represent a rescue cat."""
    def __init__(self, name):
        """Initialize the rescue cat."""
        super().__init__(name)
    def play(self):
        """Simulate playing."""
        print(f"{self.name} is playing.")
my_rescue_cat = RescueCat('Shadow')
print(f"{my_rescue_cat.name} is a rescue cat.")
my_rescue_cat.meow()
​my_rescue_cat.play()

Working with Files

Read a file:
from pathlib import Path
path = Path('novel.txt')
contents = path.read_text()
lines = contents.splitlines()
for line in lines:
    print(line)

Write to a file:
path = Path('diary.txt')
entry = "Today was a great day."
​path.write_text(entry)

Exceptions

Catch an exception:
prompt = "Enter a number: "
number = input(prompt)
try:
    number = int(number)
except ValueError:
    print("Invalid input. Please enter a number.")
else:
​    print(f"Your number is {number}.")