Python Cheat Sheet

Python Cheat Sheet

Variables and Strings

Variables are utilized to store values, such as strings, which are sequences of characters surrounded by single or double quotation marks. Strings are an essential component of programming, as they allow developers to store and manipulate textual data.

Hello world

print("Hello world!")

Hello world with a variable

msg = "Hello world!"
print(msg)

Concatenation (combining strings)

first_name = 'albert

last_name = 'einstein'
full_name = first_name+ ' ' + last name 
print(full_name)

Lists

A list preserves a sequence of elements in a specific order. You can access the elements using an index or within a looping structure. This makes it an incredibly useful tool for organizing and manipulating data.

Make a list

foods = ['rice', 'porridge', 'beans']

Get the first item in a list

first_food = foods[0]

Get the last item in a list

last_food = foods[-1]

Looping through a list

for food in foods:
    print(food)

Adding items to a list

foods.append('yam')
foods.append('noodles')
foods.append('wheat')

Making numerical lists

squares = []
for x in range(1, 11):
    squares.append(x**2)

List comprehensions

squares = [x+*2 for x in range(1, 11)]

Slicing a list

finishers = ['sam', 'bob', 'ada', 'marc'] 
first_two = finishers[:2]

Copying a list

copy_of_foodss = foods[:]

Tuples

Tuples are similar to lists, but the items in a tuple are immutable, meaning they cannot be modified. This makes tuples a great choice for storing data that should remain unchanged. Additionally, tuples are more efficient than lists, as they require less memory to store.

Making a tuple

dimensions = (1920, 1080)

If Statements

If statements are utilized to evaluate specific conditions and respond accordingly. By doing so, they enable programs to make decisions and execute the appropriate action.

Conditional tests

# equals 
x == 42

# not equal 
x != 42

# greater than 
x > 42

# greater than or equal to 
x >= 42

# less than 
x < 42

# less than or equal to 
x <= 42

Conditional test with lists

'rice' in foods
'spaghetti' not in foods

Assigning boolean values

game_active = True
can_edit = False

A simple if test

if age >= 18:
    print("You can vote!")

If-elif-else statements

if age < 4:
    ticket price = 0
elif age < 18:
    ticket price = 10
else:
    ticket_price = 15

Dictionaries

Dictionaries store associations between pieces of data. Each entry in a dictionary is a key-value pair, which provides a link between a specific key and its corresponding value. This relationship between the key and value allows for quick and easy access to the desired information.

A simple dictionary

alien = {'color': 'green',
         "points":5}

Accessing a value

print("The alien's color is " + alien['color'])

Adding a new key-value pair

alien['x_position'] = 0

Looping through all key-value pairs

fav_numbers = {
                 'eric': 17, 
                 'ever': 4
             }

for name, number in fav_numbers.items():
    print(name + 'loves' + str(number))

Looping through all keys

fav_numbers = {
                "eric": 17, 
                "eva": 4
            }

for name in fav_numbers.keys():
    print(name + "loves a number')

Looping through all the values

fav_numbers = {
            'eric': 17, 
            'eva': 4
        }

for number in fav_numbers.values():
    print(str(number)+' is a favorite')

User Input

Your programs can prompt the user for input, storing all responses as strings. This allows you to capture and store user input in a convenient and efficient manner.

Prompting for a value

name = input("What's your name?") 
print("Hello," + name + "!")

Prompting for numerical input

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

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

White Loops

A while loop iterates a block of code as long as a specified condition remains true. This looping process continues until the condition is no longer satisfied, allowing for efficient and effective execution of code.

A simple while loop

current_value = 1

while current value <= 5:
    print(current value) 
    current value += 1

Letting the user choose when to quit

msg=""

while msg!= "quit":
    msg = input("What's your message?")
    print(msg)

Functions

Functions are named blocks of code, designed to perform a specific task. Information passed to a function is referred to as an argument, and information received by a function is known as a parameter. Functions are an essential part of programming, allowing developers to create efficient and reusable code.

A simple function

def greet_user():
    # Display a simple greeting.
    print("Hello!") 

greet_user()

Passing an argument

def greet user(username):
# Display a personalized greeting 
    print("Hello," + username + "!")

greet_user('jesse')

Default values for parameters

def make_pizza(topping='bacon'):
    # Make a single-topping pizza
    print("Have a " + topping + "pizza!")

make pizza()
make pizza("pepperoni")

Returning a value

def add_numbers(x, y);
    # Add two numbers and return the sum
    return x + y

sum = add numbers(3, 5)
print(sum)

Classes

A class defines the behaviour and characteristics of an object, including the information it can store. This information is stored in attributes, and functions that belong to a class are referred to as methods. A child class inherits the attributes and methods from its parent class, allowing it to build upon the existing functionality. This inheritance of attributes and methods allows for the efficient reuse of code, making object-oriented programming a powerful tool for developers.

# Creating a dog class 
class Dog():
    # Represent a dog.
    def init(self, name):
        # Initialize dog object.
        self.name = name 

    def sit(self):
        print(self.name + " is sitting.")

# Simulate sitting.
my_dog = Dog('Peso')
print(my_dog.name + " is a great dog!")

my_dog.sit()

Inheritance

class SARDog(Dog):
    # Represent a search dog.
    def init(self, name): 
    # Initialize the sardog."
    super().__init__(name)

    def search(self):
    # Simulate searching."
        print(self.name + " is searching.") 

my_dog = SARDog("Willie")
print(my_dog.name + " is a search dog.")

my_dog.sit()
my_dog.search()

Working with files

Your programs can read from and write to files. By default, files are opened in read mode (r), but they can also be opened in write mode (w) and append mode (a). This allows for greater flexibility and control when working with files.

Reading a file and storing its lines

filename = "newfile.txt"

with open(filename) as file_object:
    lines = file_object.readlines()
    for line in lines:
        print(line)

Writing to a file

filename = "journal.txt"
with open(filename, w) as file_object: 
    file_object.write("I love python.")

Appending to a file

filename = 'journal.txt'

with open(filename, 'a') as file_object:
    file_object.write("\nI love writing code.")

Exceptions

Exceptions enable you to handle errors that are likely to occur in an appropriate manner. You can place code that may cause an error in the try block, while code that should be executed in response to an error should be placed in the except block. Finally, code that should only be executed if the try block is successful should be placed in the else block.

Catching an exception

prompt = "How many tickets do you need? " 
num_tickets = input(prompt)

try:
    num_tickets = int(num_tickets) 
except ValueError:
    print("Please try again.")
else:
    print("Your tickets are printing.")

Simple is better than complex

If you have a choice between a simple and a complex solution, and both work, use the simple solution. Your code will be easier to maintain, and it will be easier for you and others to build on that code later on