Written by students who passed Immediately available after payment Read online or as PDF Wrong document? Swap it for free 4.6 TrustPilot
logo-home
Exam (elaborations)

Beginner-s_Python_Cheat_Sheet_-_PCC_Cheat_Sheet_for_Basics-1

Rating
-
Sold
-
Pages
28
Grade
A+
Uploaded on
26-10-2025
Written in
2025/2026

Beginner-s_Python_Cheat_Sheet_-_PCC_Cheat_Sheet_for_Basics-1

Institution
Beginners
Module
Beginners

Content preview

Lists (cont.) Dictionaries
Beginner's Python List comprehensions Dictionaries store connections between pieces of
information. Each item in a dictionary is a key-value pair.
squares = [x**2 for x in range(1, 11)]
Cheat Sheet Slicing a list
A simple dictionary
alien = {'color': 'green', 'points': 5}
finishers = ['sam', 'bob', 'ada', 'bea']
first_two = finishers[:2] Accessing a value
Variables and Strings
Copying a list print(f"The alien's color is {alien['color']}.")
Variables are used to assign labels to values. A string is a
series of characters, surrounded by single or double quotes. copy_of_bikes = bikes[:] Adding a new key-value pair
Python's f-strings allow you to use variables inside strings to
alien['x_position'] = 0
build dynamic messages.
Tuples
Hello world Looping through all key-value pairs
Tuples are similar to lists, but the items in a tuple can't be
print("Hello world!") modified. fav_numbers = {'eric': 7, 'ever': 4, 'erin': 47}

Hello world with a variable Making a tuple for name, number in fav_numbers.items():
dimensions = (1920, 1080) print(f"{name} loves {number}.")
msg = "Hello world!"
resolutions = ('720p', '1080p', '4K')
print(msg) Looping through all keys
f-strings (using variables in strings) If statements fav_numbers = {'eric': 7, 'ever': 4, 'erin': 47}
first_name = 'albert' If statements are used to test for particular conditions and for name in fav_numbers.keys():
last_name = 'einstein' respond appropriately. print(f"{name} loves a number.")
full_name = f"{first_name} {last_name}"
print(full_name) Conditional tests Looping through all the values
equal x == 42
fav_numbers = {'eric': 7, 'ever': 4, 'erin': 47}
Lists not equal x != 42
greater than x > 42
A list stores a series of items in a particular order. You for number in fav_numbers.values():
or equal to x >= 42
access items using an index, or within a loop. print(f"{number} is a favorite.")
less than x < 42
Make a list or equal to x <= 42
User input
bikes = ['trek', 'redline', 'giant'] Conditional tests with lists Your programs can prompt the user for input. All input is
Get the first item in a list 'trek' in bikes stored as a string.
'surly' not in bikes
first_bike = bikes[0] Prompting for a value
Assigning boolean values
Get the last item in a list name = input("What's your name? ")
game_active = True print(f"Hello, {name}!")
last_bike = bikes[-1]
can_edit = False
Prompting for numerical input
Looping through a list
A simple if test age = input("How old are you? ")
for bike in bikes: age = int(age)
if age >= 18:
print(bike)
print("You can vote!")
Adding items to a list pi = input("What's the value of pi? ")
If-elif-else statements pi = float(pi)
bikes = []
if age < 4:
bikes.append('trek')
ticket_price = 0
bikes.append('redline')
elif age < 18:
bikes.append('giant')
ticket_price = 10 Python Crash Course
Making numerical lists elif age < 65: A Hands-on, Project-Based
ticket_price = 40 Introduction to Programming
squares = [] else:
for x in range(1, 11): ticket_price = 15 ehmatthes.github.io/pcc_3e
squares.append(x**2)

,While loops Classes Working with files
A while loop repeats a block of code as long as a certain A class defines the behavior of an object and the kind of Your programs can read from files and write to files.
condition is true. While loops are especially useful when you information an object can store. The information in a class The pathlib library makes it easier to work with files and
can't know ahead of time how many times a loop should run. is stored in attributes, and functions that belong to a class directories. Once you have a path defined, you can work
are called methods. A child class inherits the attributes and with the read_text() and write_text() methods.
A simple while loop
methods from its parent class.
current_value = 1
Reading the contents of a file
while current_value <= 5: Creating a dog class The read_text() method reads in the entire contents of a file. You
can then split the text into a list of individual lines, and then process
print(current_value) class Dog: each line as you need to.
current_value += 1 """Represent a dog."""
from pathlib import Path
Letting the user choose when to quit def init (self, name):
msg = '' """Initialize dog object.""" path = Path('siddhartha.txt')
while msg != 'quit': self.name = name contents = path.read_text()
msg = input("What's your message? ") lines = contents.splitlines()
def sit(self):
if msg != 'quit': """Simulate sitting.""" for line in lines:
print(msg) print(f"{self.name} is sitting.") print(line)

my_dog = Dog('Peso')
Writing to a file
Functions
path = Path('journal.txt')
Functions are named blocks of code, designed to do one print(f"{my_dog.name} is a great dog!")
specific job. Information passed to a function is called an my_dog.sit() msg = "I love programming.")
argument, and information received by a function is called a path.write_text(msg)
parameter. Inheritance
A simple function class SARDog(Dog): Exceptions
"""Represent a search dog."""
def greet_user(): Exceptions help you respond appropriately to errors that are
"""Display a simple greeting.""" likely to occur. You place code that might cause an error in
def init (self, name):
print("Hello!") """Initialize the sardog.""" the try block. Code that should run in response to an error
super(). init (name) goes in the except block. Code that should run only if the try
greet_user() block was successful goes in the else block.
Passing an argument def search(self): Catching an exception
"""Simulate searching."""
def greet_user(username): print(f"{self.name} is searching.") prompt = "How many tickets do you need? "
"""Display a personalized greeting.""" num_tickets = input(prompt)
print(f"Hello, {username}!") my_dog = SARDog('Willie')
try:
greet_user('jesse') print(f"{my_dog.name} is a search dog.") num_tickets = int(num_tickets)
my_dog.sit() except ValueError:
Default values for parameters my_dog.search() print("Please try again.")
def make_pizza(topping='pineapple'): else:
print("Your tickets are printing.")
"""Make a single-topping pizza.""" Infinite Skills
print(f"Have a {topping} pizza!")
If you had infinite programming skills, what would you build?
Zen of Python
make_pizza() As you're learning to program, it's helpful to think Simple is better than complex
make_pizza('mushroom') about the real-world projects you'd like to create. It's a
If you have a choice between a simple and a complex
Returning a value good habit to keep an "ideas" notebook that you can
solution, and both work, use the simple solution. Your
refer to whenever you want to start a new project.
def add_numbers(x, y): code will be easier to maintain, and it will be easier
"""Add two numbers and return the sum.""" If you haven't done so already, take a few minutes
for you and others to build on that code later on.
return x + y and describe three projects you'd like to create. As
you're learning you can write small programs that
sum = add_numbers(3, 5) relate to these ideas, so you can get practice writing Weekly posts about all things Python
print(sum) code relevant to topics you're interested in. mostlypython.substack.com

, Adding elements Sorting a list
Beginner's Python You can add elements to the end of a list, or you can insert
them wherever you like in a list. This allows you to modify
The sort() method changes the order of a list permanently.
The sorted() function returns a copy of the list, leaving the
existing lists, or start with an empty list and then add items to original list unchanged.
Cheat Sheet - Lists it as the program develops.
Adding an element to the end of the list
You can sort the items in a list in alphabetical order, or
reverse alphabetical order. You can also reverse the original
order of the list. Keep in mind that lowercase and uppercase
What are lists? users.append('amy') letters may affect the sort order.
A list stores a series of items in a particular order. Lists Starting with an empty list Sorting a list permanently
allow you to store sets of information in one place, users = [] users.sort()
whether you have just a few items or millions of items. users.append('amy')
Lists are one of Python's most powerful features users.append('val') Sorting a list permanently in reverse alphabetical order
readily accessible to new programmers, and they tie users.append('bob') users.sort(reverse=True)
together many important concepts in programming. users.append('mia')
Sorting a list temporarily
Inserting elements at a particular position
Defining a list print(sorted(users))
users.insert(0, 'joe') print(sorted(users, reverse=True))
Use square brackets to define a list, and use commas to users.insert(3, 'bea')
separate individual items in the list. Use plural names for Reversing the order of a list
lists, to make it clear that the variable represents more than
one item. Removing elements users.reverse()
You can remove elements by their position in a list, or by the
Making a list value of the item. If you remove an item by its value, Python Looping through a list
users = ['val', 'bob', 'mia', 'ron', 'ned'] removes only the first item that has that value. Lists can contain millions of items, so Python provides an
Deleting an element by its position efficient way to loop through all the items in a list. When
Accessing elements you set up a loop, Python pulls each item from the list one
del users[-1] at a time and assigns it to a temporary variable, which
Individual elements in a list are accessed according to their
position, called the index. The index of the first element is 0, Removing an item by its value you provide a name for. This name should be the singular
the index of the second element is 1, and so forth. Negative version of the list name.
users.remove('mia') The indented block of code makes up the body of the
indices refer to items at the end of the list. To get a particular
element, write the name of the list and then the index of the loop, where you can work with each individual item. Any
element in square brackets. Popping elements lines that are not indented run after the loop is completed.
If you want to work with an element that you're removing Printing all items in a list
Getting the first element from the list, you can "pop" the item. If you think of the list as
first_user = users[0] a stack of items, pop() takes an item off the top of the stack. for user in users:
By default pop() returns the last element in the list, but print(user)
Getting the second element you can also pop elements from any position in the list. Printing a message for each item, and a separate
second_user = users[1] message afterwards
Pop the last item from a list
Getting the last element most_recent_user = users.pop() for user in users:
newest_user = users[-1] print(most_recent_user) print(f"\nWelcome, {user}!")
print("We're so glad you joined!")
Pop the first item in a list
Modifying individual items first_user = users.pop(0) print("\nWelcome, we're glad to see you all!")
Once you've defined a list, you can change the value of print(first_user)
individual elements in the list. You do this by referring to the
index of the item you want to modify.
List length
Changing an element The len() function returns the number of items in a list. Python Crash Course
users[0] = 'valerie' A Hands-on, Project-Based
Find the length of a list
users[1] = 'robert' Introduction to Programming
users[-2] = 'ronald' num_users = len(users)
print(f"We have {num_users} users.") ehmatthes.github.io/pcc_3e

Written for

Institution
Beginners
Module
Beginners

Document information

Uploaded on
October 26, 2025
Number of pages
28
Written in
2025/2026
Type
Exam (elaborations)
Contains
Questions & answers

Subjects

£9.27
Get access to the full document:

Wrong document? Swap it for free Within 14 days of purchase and before downloading, you can choose a different document. You can simply spend the amount again.
Written by students who passed
Immediately available after payment
Read online or as PDF

Get to know the seller
Seller avatar
Cleverman

Get to know the seller

Seller avatar
Cleverman NURSING
Follow You need to be logged in order to follow users or courses
Sold
2
Member since
5 months
Number of followers
0
Documents
646
Last sold
1 month ago

0.0

0 reviews

5
0
4
0
3
0
2
0
1
0

Trending documents

Recently viewed by you

Why students choose Stuvia

Created by fellow students, verified by reviews

Quality you can trust: written by students who passed their exams and reviewed by others who've used these revision notes.

Didn't get what you expected? Choose another document

No problem! You can straightaway pick a different document that better suits what you're after.

Pay as you like, start learning straight away

No subscription, no commitments. Pay the way you're used to via credit card and download your PDF document instantly.

Student with book image

“Bought, downloaded, and smashed it. It really can be that simple.”

Alisha Student

Frequently asked questions