Python Cheat Sheet - Basics

Are you learning to write Python code? Are you a beginner in Python or do you just need a refresher on how to accomplish a specific task? With this Python Cheat Sheet, you get a full list of the basics in Python along with examples and their runtime results.

If you got any suggestions for this Python Cheat Sheet, please let me know in the comments below or by sending me a message at the contact tab. I will update this page continuously when I receive requests.

Happy coding! 🐍 In Python of course.

Back to basics with Python - The ultimate Python Cheat Sheet

Variables and Strings

If you would like to store a value, you can do that with a variable. In my example below about variables, you will learn to store the name of a person along with their age.

Hello World

print('Hello World!')
# Result = Hello World!

Hello World using a variable

helloFromTwc = 'Hello from Tech with Christian' # Variable is named helloFromTwc
print(helloFromTwc)

# Result = Hello from Tech with Christian

Concatenate variables are the operation of combining strings. Let's do that to print out the name and age.

firstName = 'Christian'
lastName = 'Schou'
age = 26

print(f'Hello, my name is {firstName} {lastName}, and I am {age} years old.')

# Result = Hello, my name is Christian Schou, and I am 26 years old.

In the snippet (code above) above I am doing a literal string interpolation to make up a string of my variables.

PEP 498 – Literal String Interpolation | peps.python.org
Python Enhancement Proposals (PEPs)

Lists

A list in Python is a series of items in a particular order. You are accessing the items in your list using an index or by using a loop. I have included a more details section about lists on this page if you scroll down, it is named "Working with Lists".

Create a new list

It is very easy to create a new list, this can be done using the following code.

cars = ['Volkswagen', 'Audi', 'Porsche']

Retrieve/get the first item in the list

When you work with list items, you have to remember that they are accessed using an index. The index is always starting at the position 0.

cars = ['Volkswagen', 'Audi', 'Porsche']
firstCar = cars[0]

# Result = Volkswagen

Retrieve/get the last item in the list

To access the last item in our list, we can enter -1 in the index position.

cars = ['Volkswagen', 'Audi', 'Porsche']
firstCar = cars[-1]

# Result = Porsche

Loop over items in your list

Looping items in a list is very easy. We can use something called a for loop. I will not explain for loops here but in another article.

cars = ['Volkswagen', 'Audi', 'Porsche']

for car in cars:
	print(f'Car manufacturer is: {car}')

# Result:
# Car manufacturer is: Volkswagen
# Car manufacturer is: Audi
# Car manufacturer is: Porsche

Add more items to your list

Often when working with lists, they start empty and you then have to fill in data in the list. Let's append (add) a few more items to our cars list.

Create a numeric list

cars = ['Volkswagen', 'Audi', 'Porsche']

cars.append('BMW')
cars.append('Tesla')
cars.append('Ford')

Create a numeric list

triangleAreas = []

for x in range(1,5):
	triangleAreas.append(0.5 * x * 3) # We assume all triangles have a height of 3

# Result = [1.5, 3.0, 4.5, 6.0] 

List Comprehensions

When making a list comprehension you can create a list using a loop based on a range of numbers. This might look complicated for beginners. When you get used to writing Python code, you can begin using comprehensions instead of for loops.

Until you get comfortable with Python I would recommend you to use for loops. Below is an example of a comprehension storing 10 items in a numeric list.

triangles = [0.5 * x * 3 for x in range(1,11)]

# Result = [1.5, 3.0, 4.5, 6.0, 7.5, 9.0, 10.5, 12.0, 13.5, 15.0]

Slicing lists

Python can work with any set of items inside a list. When working with a portion of a list we call it a slice (think of it as pizza, we can cut that into slices).

When making a slice we start by defining the index where we would like the first item and then a : followed by a number (integer), defining how many items you want from the start position.

runners = ['Anne', 'Mathias', 'Tina', 'Andreas', 'John', 'Jane', 'Tom', 'Kenya']

firstTwoRunners = runners[:2]

# Result = ['Anne', 'Mathias']

Copy lists

When you would like to copy a list, you have to make a slice of the part you would like to copy. If you do not make a slice, the copied list will be affected when you update the original list. Below is an example.

runners = ['Anne', 'Mathias', 'Tina', 'Andreas', 'John', 'Jane', 'Tom', 'Kenya']

copyOfRunners = runners[:] # Selecting the whole list using the slicing approach

Result = ['Anne', 'Mathias', 'Tina', 'Andreas', 'John', 'Jane', 'Tom', 'Kenya']

Tuples

A tuple is similar to a list, except for the fact that you can't change the values inside the tuple once you have defined it. A tuple is a good way to store information that won't change during the lifecycle of an application or script.

It is very easy to use tuples, see my example below.

# Define a tuple
people = ('John', 48)

# Loop through a tuple
for person in people:
	print(person)
    
# Overwrite a tuple at runtime
person = ('John', 48)
print(person)

person = ('Christian', 26) # Overwrite original tuple
print(person)

If Statements

When you need to test if a value meets a particular condition you specify and respond in accordance with the result, you can use an if statement.

# Simple conditional tests

x == 26 	# Equal test
x != 26		# Not equal
x > 26		# Greater than
x >= 26 	# Greater than or equal to
x < 26		# Less than
x <= 26		# Less than or equal to

# Conditional tests with lists
runners = ['Anne', 'Mathias', 'Tina', 'Andreas', 'John', 'Jane', 'Tom', 'Kenya']
'Tina' in runners # Evaluates to True
'Ben' in runners # Evaluates to False

# Simple if statement
if runnerAge >= 12:
	print('You can participate!')
    
# If-elif-else statement
if runnerAge < 4:
	runningFee = 0
elif runnerAge < 18:
	runningFee = 8
else:
	runningFee = 12

Dictionaries

You can think of a dictionary as key-value pairs. Each time you got a key, it will be associated with a corresponding value. A dictionary is responsible for storing the connection between two pieces of information (key-value). Below is example code on how to work with dictionaries in Python.

# Create a simple dictionary
dog = { 'name' : 'kenya', 'age' : 1.5 } # name (key) kenya (value)

# Access value in a dictionary
print('The dog is named ' + dog['name'] + ' and it is ' + dog['age'] + ' years old.')

# Result = The dog is named kenya and it is 1.5 years old.

# Add a new key value pair to the existing dictionary
dog['color'] = 'blue'
# Loop over multiple key value pairs
runnerAges = { 'nicoline': 25, 'christian': 26 }
for name, age in runnerAges.items():
	print(f'Runner: {name} is {age} years old.')

# Result
# Runner nicoline is 25 years old.
# Runner christian is 26 years old.
# Loop over all keys

runnerAges = { 'nicoline': 25, 'christian': 26 }
for name in runnerAges.keys():
	print(f'{name} loves to run.')
    
# Result
# nicoline loves to run.
# christian loves to run.
# Loop over all values

runnerAges = { 'nicoline': 25, 'christian': 26 }
for age in runnerAges.values():
	print(f'This runner is {age} years old.')
    
# Result
# This runner is 25 years old.
# This runner is 26 years old.

User Input

If your program is running in a terminal, you can prompt the user for input at runtime. All inputs are stored as strings in your program. If you expect an integer, you have to convert it into an integer type.

# Ask/prompt the user for input
name = input('What is your name? ')
print(f'Hello {name}!')

# Hello Christian!

# Ask/prompt the user for a numeric input
age = input('How old are you?')
age = int(age) # Casting the input age of type string to age of type int

## One more example with a float
height = input('How tall are you in meters?')
heigh = float(height)

While Loops

A while loop will keep repeating a block as long as a condition is true. The only way to stop it from running is by turning a certain boolean to false.

# A simple while loop
value = 1

while value <= 5:
	print(value)
    value += 1
    
# Result
1
2
3
4
5
# While loop stop depending on user input

message = ''
while message != 'quit':
	message = input('What would you like to say?')
    print(message)
    
# Result
# What would you like to say?My name is Christian
# My name is Christian
# What would you like to say?I have a dog named Kenya
# I have a dog named Kenya

Functions

A function is a named block of code. A function is designed to do one specific task. When you pass information to a function it's called an argument and the information you receive back from a function when the task is done is called a parameter.

# Simple function

def helloUser():
	"""Show a welcome message to the user"""
    print('Hello, and welcome!')

helloUser()

# Result
# Hello, and welcome!
# Function with an argument passed

def helloUser(name: string):
	"""Show a personal welcome message to the user"""
    print(f'Hello {name}, how are you?')
    
helloUser('Christian')

# Result
# Hello Christian, how are you?
# Function with an argument passed including default values

def whatToEat(dish='pizza'):
	"""Return a dish to eat"""
    print('Tonights dinner is {dish}')
    
whatToEat()
# Tonights dinner is pizza

whatToEat('Lasagne')
# Tonights dinner is Lasagne
# Return a value from a function

def divideNumbers(x: int, y: int) -> float:
	"""Divide two numbers and return the sum."""
    return float(x / y)
    
sum = divideNumbers(11, 2)
print(sum)
# Result
# 5.5

Classes

Classes are responsible for defining the behavior of an object and the kind of information a particular object is storing. All information inside a class is stored as attributes, and functions that belong (are inside) a class is what we call methods.

If you declare a child class it will inherit all attributes and methods from its parent class. Below are a few examples of working with classes.

# Creating a new dog class

class Dog():
	"""A class to represent a dog"""
    
    def __init__(self, name):
    	"""Initialize the dog object"""
        self.name = name
    
    def walk(self):
    	"""Simulate walking"""
        print(self.name + ' is walking.')

dog = Dog('Kenya')

print(f'{dog.name} is a sweet dog!')
# Result = Kenya is a sweet dog!

dog.walk()
# Result = Kenya is walking.
# Working with inheritance in classes

class FrenchBulldog(Dog)
	"""Represents a french bulldog"""
    def __init__(self, name):
    	"""Initialize the french bulldog"""
        super().__init__(name)
        
    def ratMode(self):
    	"""Simulate rat mode"""
        print(f'{self.name} is now keeping the home free of rats and other vermin.')
        
frenchDog = FrenchBulldog('Kenya')

print (f'{frenchDog.name} is a french bulldog')
# Result = Kenya is a french bulldog

frenchDog.walk()
# Result = Kenya is walking.

frenchDog.ratMode()
# Result = Kenya is keeping the home free of rats and other vermin.

Files

Files are a crucial part of every computer. Python programs are also capable of reading and writing files. By default, a file is always opened in read-only mode 'r', but you can change that to write 'r' and append 'a' mode if you need to update the file.

# Read a file and store the data from it
fileName = 'runnerAttendees.txt'

with open(fileName) as file_object:
	runners = file_object.readlines()
    
for runner in runners:
	print(runner)

# Result
# Nicoline
# Christian
# John
# Tina
# Write text to a file

fileName = 'programmer.txt'

with open(fileName, 'w') as file_object:
	file_object.write('I love to write Python code.')
# Append data to a file

fileName = 'runnerAttendees.txt'

with open(fileName, 'a') as file_object:
	file_object.write('\nKenya')

Exceptions

Exceptions are a way for programmers to handle errors that are likely to occur during the runtime of an application/script. Often we use something called a try/except inside our function to catch the errors. Below is an example of that.

# Imagine you are asking for an input from a user in your program.
# The user enters a non allowed value, but the program should not break
# because of that. Here we can use a try/catch

# Create an exception

prompt = 'How many people would you like to buy a ticket for?'
runnerTickets = input(prompt)

try:
	runnerTickets = int(runnerTickets)
except ValueError:
	print(f'{runnerTickets} is not a number. Please try again.')
else:
	print(f'Printing {runnerTickets} tickets for the run.')

Summary

Python is probably one of the best languages to learn as a new programmer is it is very easy to write. It is almost the same as writing normal text. This Python Cheat Sheet is based on the basics of Python.

If you would like to expand your knowledge about other Python topics, I have created other Python Cheat Sheets you can have a look at to get better at writing Python code.

If you got any questions about the above Python code examples, please let me know in the comments. Until next time - Happy coding! ✌️

You've successfully subscribed to Tech with Christian
Great! Next, complete checkout to get full access to all premium content.
Error! Could not sign up. invalid link.
Welcome back! You've successfully signed in.
Error! Could not sign in. Please try again.
Success! Your account is fully activated, you now have access to all content.
Error! Stripe checkout failed.
Success! Your billing info is updated.
Error! Billing info update failed.