0% found this document useful (0 votes)
36 views

beginners_python_cheat_sheet_pcc_all

python

Uploaded by

dickslayer8235
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

beginners_python_cheat_sheet_pcc_all

python

Uploaded by

dickslayer8235
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

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
A list stores a series of items in a particular order. You greater than x > 42
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.""" def __init__(self, name): likely to occur. You place code that might cause an error in
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
The range() function Copying a list Tuples
You can use the range() function to work with a set of To copy a list make a slice that starts at the first item and A tuple is like a list, except you can't change the values
numbers efficiently. The range() function starts at 0 by ends at the last item. If you try to copy a list without using in a tuple once it's defined. Tuples are good for storing
default, and stops one number below the number passed to this approach, whatever you do to the copied list will affect information that shouldn't be changed throughout the life of a
it. You can use the list() function to efficiently generate a the original list as well. program. Tuples are usually designated by parentheses.
large list of numbers. You can overwrite an entire tuple, but you can't change
Making a copy of a list
the values of individual elements.
Printing the numbers 0 to 1000 finishers = ['kai', 'abe', 'ada', 'gus', 'zoe']
for number in range(1001): copy_of_finishers = finishers[:] Defining a tuple
print(number) dimensions = (800, 600)
Printing the numbers 1 to 1000 List comprehensions Looping through a tuple
You can use a loop to generate a list based on a range of
for number in range(1, 1001): for dimension in dimensions:
numbers or on another list. This is a common operation,
print(number) print(dimension)
so Python offers a more efficient way to do it. List
Making a list of numbers from 1 to a million comprehensions may look complicated at first; if so, use Overwriting a tuple
the for loop approach until you're ready to start using
numbers = list(range(1, 1_000_001)) dimensions = (800, 600)
comprehensions.
print(dimensions)
To write a comprehension, define an expression for the
Simple statistics values you want to store in the list. Then write a for loop to dimensions = (1200, 900)
There are a number of simple statistical operations you can generate input values needed to make the list. print(dimensions)
run on a list containing numerical data.
Using a loop to generate a list of square numbers
Finding the minimum value in a list squares = [] Visualizing your code
ages = [93, 99, 66, 17, 85, 1, 35, 82, 2, 77] for x in range(1, 11): When you're first learning about data structures such as
youngest = min(ages) square = x**2 lists, it helps to visualize how Python is working with the
squares.append(square) information in your program. Python Tutor is a great tool for
Finding the maximum value seeing how Python keeps track of the information in a list.
Using a comprehension to generate a list of square
ages = [93, 99, 66, 17, 85, 1, 35, 82, 2, 77] Try running the following code on pythontutor.com, and then
oldest = max(ages) numbers run your own code.
squares = [x**2 for x in range(1, 11)]
Finding the sum of all values Build a list and print the items in the list
ages = [93, 99, 66, 17, 85, 1, 35, 82, 2, 77] Using a loop to convert a list of names to upper case dogs = []
total_years = sum(ages) names = ['kai', 'abe', 'ada', 'gus', 'zoe'] dogs.append('willie')
dogs.append('hootz')
Slicing a list upper_names = [] dogs.append('peso')
for name in names: dogs.append('goblin')
You can work with any subset of elements from a list. A
upper_names.append(name.upper())
portion of a list is called a slice. To slice a list start with the for dog in dogs:
index of the first item you want, then add a colon and the Using a comprehension to convert a list of names to print(f"Hello {dog}!")
index after the last item you want. Leave off the first index upper case print("I love these dogs!")
to start at the beginning of the list, and leave off the second
index to slice through the end of the list. names = ['kai', 'abe', 'ada', 'gus', 'zoe']
print("\nThese were my first two dogs:")
old_dogs = dogs[:2]
Getting the first three items upper_names = [name.upper() for name in names]
for old_dog in old_dogs:
finishers = ['kai', 'abe', 'ada', 'gus', 'zoe'] print(old_dog)
first_three = finishers[:3] Styling your code
Readability counts del dogs[0]
Getting the middle three items dogs.remove('peso')
middle_three = finishers[1:4] Follow common Python formatting conventions: print(dogs)
• Use four spaces per indentation level.
Getting the last three items • Keep your lines to 79 characters or fewer.
last_three = finishers[-3:] • Use single blank lines to group parts of your
program visually. Weekly posts about all things Python
mostlypython.substack.com
Adding new key-value pairs Looping through a dictionary
Beginner's Python You can store as many key-value pairs as you want in a
dictionary, until your computer runs out of memory. To add a
You can loop through a dictionary in three ways: you can
loop through all the key-value pairs, all the keys, or all the
new key-value pair to an existing dictionary give the name of values.
Cheat Sheet - the dictionary and the new key in square brackets, and set it
equal to the new value.
Dictionaries keep track of the order in which key-value
pairs are added. If you want to process the information in a
This also allows you to start with an empty dictionary and different order, you can sort the keys in your loop, using the
Dictionaries add key-value pairs as they become relevant.
Adding a key-value pair
sorted() function.
Looping through all key-value pairs
What are dictionaries? alien_0 = {'color': 'green', 'points': 5} # Store people's favorite languages.
fav_languages = {
Python's dictionaries allow you to connect pieces of alien_0['x'] = 0 'jen': 'python',
related information. Each piece of information in a alien_0['y'] = 25 'sarah': 'c',
dictionary is stored as a key-value pair. When you alien_0['speed'] = 1.5 'edward': 'ruby',
provide a key, Python returns the value associated 'phil': 'python',
Starting with an empty dictionary }
with that key. You can loop through all the key-value
alien_0 = {}
pairs, all the keys, or all the values. # Show each person's favorite language.
alien_0['color'] = 'green'
alien_0['points'] = 5 for name, language in fav_languages.items():
Defining a dictionary print(f"{name}: {language}")
Use curly braces to define a dictionary. Use colons to
connect keys and values, and use commas to separate
Modifying values Looping through all the keys
individual key-value pairs. You can modify the value associated with any key in a # Show everyone who's taken the survey.
dictionary. To do so give the name of the dictionary and the for name in fav_languages.keys():
Making a dictionary key in square brackets, then provide the new value for that print(name)
alien_0 = {'color': 'green', 'points': 5} key.
Looping through all the values
Modifying values in a dictionary
Accessing values alien_0 = {'color': 'green', 'points': 5}
# Show all the languages that have been chosen.
for language in fav_languages.values():
To access the value associated with an individual key give print(alien_0) print(language)
the name of the dictionary and then place the key in a set
of square brackets. If the key you provided is not in the # Change the alien's color and point value. Looping through all the keys in reverse order
dictionary, an error will occur. alien_0['color'] = 'yellow'
# Show each person's favorite language,
You can also use the get() method, which returns alien_0['points'] = 10
# in reverse order by the person's name.
None instead of an error if the key doesn't exist. You can print(alien_0)
for name in sorted(fav_languages.keys(),
also specify a default value to use if the key is not in the reverse=True):
dictionary. Removing key-value pairs language = fav_languages[name]
Getting the value associated with a key You can remove any key-value pair you want from a print(f"{name}: {language}")
dictionary. To do this use the del keyword and the dictionary
alien_0 = {'color': 'green', 'points': 5}
name, followed by the key in square brackets. This will Dictionary length
print(alien_0['color']) delete the key and its associated value. You can find the number of key-value pairs in a dictionary
print(alien_0['points']) Deleting a key-value pair using the len() function.
Getting the value with get() alien_0 = {'color': 'green', 'points': 5} Finding a dictionary's length
print(alien_0) num_responses = len(fav_languages)
alien_0 = {'color': 'green'}
del alien_0['points']
alien_color = alien_0.get('color')
alien_points = alien_0.get('points', 0)
print(alien_0)
Python Crash Course
alien_speed = alien_0.get('speed') A Hands-on, Project-Based
Visualizing dictionaries
Introduction to Programming
print(alien_color) Try running some of these examples on pythontutor.com,
print(alien_points) and then run one of your own programs that uses ehmatthes.github.io/pcc_3e
print(alien_speed) dictionaries.
Nesting - A list of dictionaries Nesting - Lists in a dictionary Dictionary Comprehensions
It's sometimes useful to store a number of dictionaries in a Storing a list inside a dictionary allows you to associate more A comprehension is a compact way of generating a
list; this is called nesting. than one value with each key. dictionary, similar to a list comprehension. To make a
dictionary comprehension, define an expression for the
Storing dictionaries in a list Storing lists in a dictionary
key-value pairs you want to make. Then write a for loop to
# Start with an empty list. # Store multiple languages for each person. generate the values that will feed into this expression.
users = [] fav_languages = { The zip() function matches each item in one list to each
'jen': ['python', 'ruby'], item in a second list. It can be used to make a dictionary
# Make a new user, and add them to the list. 'sarah': ['c'], from two lists.
new_user = { 'edward': ['ruby', 'go'],
'last': 'fermi', 'phil': ['python', 'haskell'], Using a loop to make a dictionary
'first': 'enrico', } squares = {}
'username': 'efermi', for x in range(5):
} # Show all responses for each person. squares[x] = x**2
users.append(new_user) for name, langs in fav_languages.items():
print(f"{name}: ") Using a dictionary comprehension
# Make another new user, and add them as well. for lang in langs:
squares = {x:x**2 for x in range(5)}
new_user = { print(f"- {lang}")
'last': 'curie', Using zip() to make a dictionary
'first': 'marie', Nesting - A dictionary of dictionaries group_1 = ['kai', 'abe', 'ada', 'gus', 'zoe']
'username': 'mcurie',
} You can store a dictionary inside another dictionary. In this group_2 = ['jen', 'eva', 'dan', 'isa', 'meg']
users.append(new_user) case each value associated with a key is itself a dictionary.
pairings = {name:name_2
Storing dictionaries in a dictionary for name, name_2 in zip(group_1, group_2)}
# Show all information about each user.
print("User summary:") users = {
for user_dict in users: 'aeinstein': { Generating a million dictionaries
for k, v in user_dict.items(): 'first': 'albert',
You can use a loop to generate a large number of
print(f"{k}: {v}") 'last': 'einstein',
'location': 'princeton', dictionaries efficiently, if all the dictionaries start out with
print("\n") similar data.
},
You can also define a list of dictionaries directly, A million aliens
without using append(): 'mcurie': {
'first': 'marie', aliens = []
# Define a list of users, where each user 'last': 'curie',
# is represented by a dictionary. 'location': 'paris', # Make a million green aliens, worth 5 points
users = [ }, # each. Have them all start in one row.
{ } for alien_num in range(1_000_000):
'last': 'fermi', new_alien = {
'first': 'enrico', for username, user_dict in users.items(): 'color': 'green',
'username': 'efermi', full_name = f"{user_dict['first']} " 'points': 5,
}, full_name += user_dict['last'] 'x': 20 * alien_num,
{ 'y': 0
'last': 'curie', location = user_dict['location'] }
'first': 'marie',
'username': 'mcurie', print(f"\nUsername: {username}") aliens.append(new_alien)
}, print(f"\tFull name: {full_name.title()}")
] print(f"\tLocation: {location.title()}") # Prove the list contains a million aliens.
num_aliens = len(aliens)
# Show all information about each user.
print("User summary:") Levels of nesting print("Number of aliens created:")
for user_dict in users: Nesting is extremely useful in certain situations. However, print(num_aliens)
for k, v in user_dict.items(): be aware of making your code overly complex. If you're
print(f"{k}: {v}") nesting items much deeper than what you see here there
print("\n") are probably simpler ways of managing your data, such as Weekly posts about all things Python
using classes. mostlypython.substack.com
Numerical comparisons If statements
Beginner's Python Testing numerical values is similar to testing string values. Several kinds of if statements exist. Your choice of which to
use depends on the number of conditions you need to test.
Testing equality and inequality
You can have as many elif blocks as you need, and the
Cheat Sheet - >>> age = 18
>>> age == 18
else block is always optional.
Simple if statement
True
If Statements >>> age != 18
False
age = 19

if age >= 18:


Comparison operators
and While Loops >>> age
>>> age
= 19
< 21
print("You're old enough to vote!")
If-else statements
True age = 17
What are if statements? What are while >>> age <= 21
loops? True if age >= 18:
>>> age > 21 print("You're old enough to vote!")
Python's if statements allow you to examine the False else:
current state of a program and respond appropriately >>> age >= 21 print("You can't vote yet.")
to that state. You can write a simple if statement that False
checks one condition, or you can create a complex The if-elif-else chain
series of statements that identify the exact conditions Checking multiple conditions age = 12
you're interested in. You can check multiple conditions at the same time. The and
while loops run as long as certain conditions operator returns True if all the conditions listed are true. The if age < 4:
price = 0
remain true. You can use while loops to let your or operator returns True if any condition is true.
elif age < 18:
programs run as long as your users want them to. Using and to check multiple conditions price = 25
else:
Conditional Tests >>> age_0 = 22
price = 40
>>> age_1 = 18
A conditional test is an expression that can be evaluated
>>> age_0 >= 21 and age_1 >= 21
as true or false. Python uses the values True and False False
print(f"Your cost is ${price}.")
to decide whether the code in an if statement should be >>> age_1 = 23
executed. >>> age_0 >= 21 and age_1 >= 21 Conditional tests with lists
Checking for equality True You can easily test whether a certain value is in a list. You
A single equal sign assigns a value to a variable. A double equal can also test whether a list is empty before trying to loop
Using or to check multiple conditions
sign checks whether two values are equal. through the list.
If your conditional tests aren't doing what you expect them to, >>> age_0 = 22
make sure you're not accidentally using a single equal sign. >>> age_1 = 18 Testing if a value is in a list
>>> car = 'bmw' >>> age_0 >= 21 or age_1 >= 21 >>> players = ['al', 'bea', 'cyn', 'dale']
>>> car == 'bmw' True >>> 'al' in players
True >>> age_0 = 18 True
>>> car = 'audi' >>> age_0 >= 21 or age_1 >= 21 >>> 'eric' in players
>>> car == 'bmw' False False
False Testing if two values are in a list
Boolean values
Ignoring case when making a comparison >>> 'al' in players and 'cyn' in players
A boolean value is either True or False. Variables with
>>> car = 'Audi' boolean values are often used to keep track of certain
>>> car.lower() == 'audi' conditions within a program.
True
Simple boolean values
Python Crash Course
Checking for inequality A Hands-on, Project-Based
game_active = True Introduction to Programming
>>> topping = 'mushrooms' is_valid = True
>>> topping != 'anchovies' can_edit = False ehmatthes.github.io/pcc_3e
True
Conditional tests with lists (cont.) While loops (cont.) While loops (cont.)
Testing if a value is not in a list Letting the user choose when to quit Using continue in a loop
banned_users = ['ann', 'chad', 'dee'] prompt = "\nTell me something, and I'll " banned_users = ['eve', 'fred', 'gary', 'helen']
user = 'erin' prompt += "repeat it back to you."
prompt += "\nEnter 'quit' to end the program. " prompt = "\nAdd a player to your team."
if user not in banned_users: prompt += "\nEnter 'quit' when you're done. "
print("You can play!") message = ""
while message != 'quit': players = []
Checking if a list is empty message = input(prompt) while True:
An empty list evaluates as False in an if statement. player = input(prompt)
players = [] if message != 'quit':
print(message) if player == 'quit':
if players: break
Using a flag elif player in banned_users:
for player in players:
Flags are most useful in long-running programs where code from print(f"{player} is banned!")
print(f"Player: {player.title()}")
other parts of the program might need to end the loop. continue
else:
print("We have no players yet!") prompt = "\nTell me something, and I'll " else:
prompt += "repeat it back to you." players.append(player)
prompt += "\nEnter 'quit' to end the program. "
Accepting input print("\nYour team:")
You can allow your users to enter input using the input() active = True for player in players:
function. All input is initially stored as a string. If you want to while active: print(player)
accept numerical input, you'll need to convert the input string message = input(prompt)
value to a numerical type. Avoiding infinite loops
Simple input if message == 'quit':
Every while loop needs a way to stop running so it won't
active = False
name = input("What's your name? ") else: continue to run forever. If there's no way for the condition
print(f"Hello, {name}.") print(message) to become false, the loop will never stop running. You can
usually press Ctrl-C to stop an infinite loop.
Accepting numerical input using int() Using break to exit a loop
An infinite loop
age = input("How old are you? ") prompt = "\nWhat cities have you visited?"
age = int(age) while True:
prompt += "\nEnter 'quit' when you're done. "
name = input("\nWho are you? ")
if age >= 18: print(f"Nice to meet you, {name}!")
while True:
print("\nYou can vote!") city = input(prompt)
else: Removing all instances of a value from a list
print("\nSorry, you can't vote yet.") if city == 'quit': The remove() method removes a specific value from a
break list, but it only removes the first instance of the value you
Accepting numerical input using float() else: provide. You can use a while loop to remove all instances of
tip = input("How much do you want to tip? ") print(f"I've been to {city}!") a particular value.
tip = float(tip)
Removing all cats from a list of pets
print(f"Tipped ${tip}.") Accepting input with Sublime Text
Sublime Text, and a number of other text editors can't run pets = ['dog', 'cat', 'dog', 'fish', 'cat',
While loops programs that prompt the user for input. You can use these 'rabbit', 'cat']
A while loop repeats a block of code as long as a condition editors to write programs that prompt for input, but you'll print(pets)
is true. need to run them from a terminal.
while 'cat' in pets:
Counting to 5 pets.remove('cat')
Breaking out of loops
current_number = 1
You can use the break statement and the continue print(pets)
while current_number <= 5: statement with any of Python's loops. For example you can
print(current_number) use break to quit a for loop that's working through a list or a
current_number += 1 dictionary. You can use continue to skip over certain items Weekly posts about all things Python
when looping through a list or dictionary as well. mostlypython.substack.com
Positional and keyword arguments Return values
Beginner's Python The two main kinds of arguments are positional and keyword
arguments. When you use positional arguments Python
A function can return a value or a set of values. When a
function returns a value, the calling line should provide
matches the first argument in the function call with the first a variable which the return value can be assigned to. A
Cheat Sheet - parameter in the function definition, and so forth.
With keyword arguments, you specify which parameter
function stops running when it reaches a return statement.
Returning a single value
each argument should be assigned to in the function
Functions call. When you use keyword arguments, the order of the
arguments doesn't matter.
def get_full_name(first, last):
"""Return a neatly formatted full name."""
full_name = f"{first} {last}"
Using positional arguments return full_name.title()
What are functions?
def describe_pet(animal, name):
Functions are named blocks of code designed to do """Display information about a pet.""" musician = get_full_name('jimi', 'hendrix')
one specific job. Functions allow you to write code print(f"\nI have a {animal}.") print(musician)
once that can then be run whenever you need to print(f"Its name is {name}.")
Returning a dictionary
accomplish the same task.
describe_pet('hamster', 'harry') def build_person(first, last):
Functions can take in the information they need,
describe_pet('dog', 'willie') """Return a dictionary of information
and return the information they generate. Using about a person.
functions effectively makes your programs easier to Using keyword arguments """
write, read, test, and maintain. def describe_pet(animal, name): person = {'first': first, 'last': last}
"""Display information about a pet.""" return person
Defining a function print(f"\nI have a {animal}.")
The first line of a function is its definition, marked by the print(f"Its name is {name}.") musician = build_person('jimi', 'hendrix')
keyword def. The name of the function is followed by a set print(musician)
of parentheses and a colon. A docstring, in triple quotes, describe_pet(animal='hamster', name='harry')
Returning a dictionary with optional values
describes what the function does. The body of a function is describe_pet(name='willie', animal='dog')
indented one level. def build_person(first, last, age=None):
To call a function, give the name of the function followed Default values """Return a dictionary of information
about a person.
by a set of parentheses. You can provide a default value for a parameter. When """
Making a function function calls omit this argument the default value will be person = {'first': first, 'last': last}
used. Parameters with default values must be listed after if age:
def greet_user(): parameters without default values in the function's definition person['age'] = age
"""Display a simple greeting.""" so positional arguments can still work correctly.
print("Hello!")
Using a default value return person
greet_user() def describe_pet(name, animal='dog'): musician = build_person('jimi', 'hendrix', 27)
"""Display information about a pet.""" print(musician)
Passing information to a function print(f"\nI have a {animal}.")
Information that's passed to a function is called an argument; print(f"Its name is {name}.") musician = build_person('janis', 'joplin')
information that's received by a function is called a print(musician)
parameter. Arguments are included in parentheses after the describe_pet('harry', 'hamster')
describe_pet('willie')
function's name, and parameters are listed in parentheses in Visualizing functions
the function's definition. Using None to make an argument optional Try running some of these examples, and some of your own
Passing a simple argument def describe_pet(animal, name=None): programs that use functions, on pythontutor.com.
def greet_user(username): """Display information about a pet."""
"""Display a simple greeting.""" print(f"\nI have a {animal}.")
print(f"Hello, {username}!") if name: Python Crash Course
print(f"Its name is {name}.")
A Hands-on, Project-Based
greet_user('jesse') Introduction to Programming
greet_user('diana') describe_pet('hamster', 'harry')
greet_user('brandon') describe_pet('snake') ehmatthes.github.io/pcc_3e
Passing a list to a function Passing an arbitrary number of arguments Modules
You can pass a list as an argument to a function, and the Sometimes you won't know how many arguments a function You can store your functions in a separate file called a
function can work with the values in the list. Any changes the will need to accept. Python allows you to collect an arbitrary module, and then import the functions you need into the
function makes to the list will affect the original list. You can number of arguments into one parameter using the * file containing your main program. This allows for cleaner
prevent a function from modifying a list by passing a copy of operator. A parameter that accepts an arbitrary number of program files. Make sure your module is stored in the same
the list as an argument. arguments must come last in the function definition. This directory as your main program.
parameter is often named *args.
Passing a list as an argument Storing a function in a module
The ** operator allows a parameter to collect an arbitrary
File: pizza.py
def greet_users(names): number of keyword arguments. These are stored as a
"""Print a simple greeting to everyone.""" dictionary with the parameter names as keys, and the def make_pizza(size, *toppings):
for name in names: arguments as values. This is often named **kwargs. """Make a pizza."""
msg = f"Hello, {name}!" print(f"\nMaking a {size} pizza.")
print(msg) Collecting an arbitrary number of arguments print("Toppings:")
def make_pizza(size, *toppings): for topping in toppings:
usernames = ['hannah', 'ty', 'margot'] """Make a pizza.""" print(f"- {topping}")
greet_users(usernames) print(f"\nMaking a {size} pizza.")
Importing an entire module
Allowing a function to modify a list File: making_pizzas.py Every function in the module is available in
print("Toppings:")
The following example sends a list of models to a function for the program file.
printing. The first list is emptied, and the second list is filled.
for topping in toppings:
print(f"- {topping}") import pizza
def print_models(unprinted, printed):
"""3d print a set of models.""" # Make three pizzas with different toppings. pizza.make_pizza('medium', 'pepperoni')
while unprinted: make_pizza('small', 'pepperoni') pizza.make_pizza('small', 'bacon', 'pineapple')
current_model = unprinted.pop() make_pizza('large', 'bacon bits', 'pineapple')
print(f"Printing {current_model}") make_pizza('medium', 'mushrooms', 'peppers', Importing a specific function
printed.append(current_model) 'onions', 'extra cheese') Only the imported functions are available in the program file.
from pizza import make_pizza
# Store some unprinted designs, Collecting an arbitrary number of keyword arguments
# and print each of them. def build_profile(first, last, **user_info): make_pizza('medium', 'pepperoni')
unprinted = ['phone case', 'pendant', 'ring'] """Build a dictionary for a user.""" make_pizza('small', 'bacon', 'pineapple')
printed = [] user_info['first'] = first
print_models(unprinted, printed) user_info['last'] = last Giving a module an alias
import pizza as p
print(f"\nUnprinted: {unprinted}") return user_info
print(f"Printed: {printed}") p.make_pizza('medium', 'pepperoni')
Preventing a function from modifying a list # Create two users with different kinds p.make_pizza('small', 'bacon', 'pineapple')
# of information.
The following example is the same as the previous one, except the Giving a function an alias
original list is unchanged after calling print_models().
user_0 = build_profile('albert', 'einstein',
location='princeton') from pizza import make_pizza as mp
def print_models(unprinted, printed):
"""3d print a set of models.""" user_1 = build_profile('marie', 'curie', mp('medium', 'pepperoni')
while unprinted: location='paris', field='chemistry') mp('small', 'bacon', 'pineapple')
current_model = unprinted.pop()
print(f"Printing {current_model}") print(user_0) Importing all functions from a module
printed.append(current_model) print(user_1) Don't do this, but recognize it when you see it in others' code. It can
result in naming conflicts, which can cause errors.
# Store some unprinted designs,
# and print each of them.
What's the best way to structure a function? from pizza import *
original = ['phone case', 'pendant', 'ring'] There are many ways to write and call a function. When
printed = [] you're starting out, aim for something that simply works. As make_pizza('medium', 'pepperoni')
you gain experience you'll develop an understanding of the make_pizza('small', 'bacon', 'pineapple')
print_models(original[:], printed) subtle advantages of different structures such as positional
print(f"\nOriginal: {original}") and keyword arguments, and the various approaches to
print(f"Printed: {printed}") importing functions. For now if your functions do what you Weekly posts about all things Python
need them to, you're doing well. mostlypython.substack.com
Creating and using a class (cont.) Class inheritance
Beginner's Python Creating an instance from a class If the class you're writing is a specialized version of another
class, you can use inheritance. When one class inherits
my_car = Car('audi', 'a4', 2021)
from another, it automatically takes on all the attributes
Cheat Sheet - Classes Accessing attribute values and methods of the parent class. The child class is free
to introduce new attributes and methods, and override
print(my_car.make)
attributes and methods of the parent class.
print(my_car.model)
What are classes? print(my_car.year)
To inherit from another class include the name of the
parent class in parentheses when defining the new class.
Classes are the foundation of object-oriented
Calling methods The __init__() method for a child class
programming. Classes represent real-world things
you want to model in your programs such as dogs, my_car.fill_tank() class ElectricCar(Car):
cars, and robots. You use a class to make objects, my_car.drive() """A simple model of an electric car."""
which are specific instances of dogs, cars, and robots. Creating multiple instances
A class defines the general behavior that a whole def __init__(self, make, model, year):
my_car = Car('audi', 'a4', 2024) """Initialize an electric car."""
category of objects can have, and the information that my_old_car = Car('subaru', 'outback', 2018) super().__init__(make, model, year)
can be associated with those objects. my_truck = Car('toyota', 'tacoma', 2020)
Classes can inherit from each other—you can write my_old_truck = Car('ford', 'ranger', 1999) # Attributes specific to electric cars.
a class that extends the functionality of an existing # Battery capacity in kWh.
class. This allows you to code efficiently for a wide Modifying attributes self.battery_size = 40
variety of situations. Even if you don't write many You can modify an attribute's value directly, or you can
# Charge level in %.
of your own classes, you'll frequently find yourself write methods that manage updating values more carefully.
self.charge_level = 0
working with classes that others have written. Methods like these can help validate the kinds of changes
that are being made to an attribute. Adding new methods to the child class
Creating and using a class Modifying an attribute directly class ElectricCar(Car):
Consider how we might model a car. What information would --snip--
my_new_car = Car('audi', 'a4', 2024)
we associate with a car, and what behavior would it have?
my_new_car.fuel_level = 5
The information is assigned to variables called attributes, def charge(self):
and the behavior is represented by functions. Functions that Writing a method to update an attribute's value """Fully charge the vehicle."""
are part of a class are called methods. self.charge_level = 100
def update_fuel_level(self, new_level):
print("The vehicle is fully charged.")
The Car class """Update the fuel level."""
class Car:
if new_level <= self.fuel_capacity: Using child methods and parent methods
self.fuel_level = new_level
"""A simple attempt to model a car.""" my_ecar = ElectricCar('nissan', 'leaf', 2024)
else:
print("The tank can't hold that much!")
def __init__(self, make, model, year): my_ecar.charge()
"""Initialize car attributes.""" Writing a method to increment an attribute's value my_ecar.drive()
self.make = make
self.model = model def add_fuel(self, amount):
self.year = year """Add fuel to the tank.""" Finding your workflow
if (self.fuel_level + amount There are many ways to model real world objects and
# Fuel capacity and level in gallons. <= self.fuel_capacity): situations in code, and sometimes that variety can feel
self.fuel_capacity = 15 self.fuel_level += amount overwhelming. Pick an approach and try it; if your first
self.fuel_level = 0 print("Added fuel.") attempt doesn't work, try a different approach.
else:
def fill_tank(self): print("The tank won't hold that much.")
"""Fill gas tank to capacity."""
self.fuel_level = self.fuel_capacity Naming conventions Python Crash Course
print("Fuel tank is full.") In Python class names are usually written in CamelCase A Hands-on, Project-Based
and object names are written in lowercase with underscores. Introduction to Programming
def drive(self): Modules that contain classes should be named in lowercase
"""Simulate driving.""" with underscores. ehmatthes.github.io/pcc_3e
print("The car is moving.")
Class inheritance (cont.) Importing classes Storing objects in a list
Overriding parent methods Class files can get long as you add detailed information and A list can hold as many items as you want, so you can make
functionality. To help keep your program files uncluttered, a large number of objects from a class and store them in a
class ElectricCar(Car):
you can store your classes in modules and import the list.
--snip--
classes you need into your main program. Here's an example showing how to make a fleet of rental
cars, and make sure all the cars are ready to drive.
def fill_tank(self): Storing classes in a file
"""Display an error message.""" car.py A fleet of rental cars
print("This car has no fuel tank!")
"""Represent gas and electric cars.""" from car import Car, ElectricCar

Instances as attributes class Car: # Make lists to hold a fleet of cars.


A class can have objects as attributes. This allows classes to """A simple attempt to model a car.""" gas_fleet = []
work together to model more complex real-world things and --snip— electric_fleet = []
concepts.
class Battery: # Make 250 gas cars and 500 electric cars.
A Battery class """A battery for an electric car.""" for _ in range(250):
class Battery: --snip-- car = Car('ford', 'escape', 2024)
"""A battery for an electric car.""" gas_fleet.append(car)
class ElectricCar(Car): for _ in range(500):
def __init__(self, size=85): """A simple model of an electric car.""" ecar = ElectricCar('nissan', 'leaf', 2024)
"""Initialize battery attributes.""" --snip-- electric_fleet.append(ecar)
# Capacity in kWh, charge level in %.
Importing individual classes from a module # Fill the gas cars, and charge electric cars.
self.size = size
my_cars.py for car in gas_fleet:
self.charge_level = 0
from car import Car, ElectricCar car.fill_tank()
def get_range(self): for ecar in electric_fleet:
"""Return the battery's range.""" my_beetle = Car('volkswagen', 'beetle', 2021) ecar.charge()
if self.size == 40: my_beetle.fill_tank()
return 150 my_beetle.drive() print(f"Gas cars: {len(gas_fleet)}")
elif self.size == 65: print(f"Electric cars: {len(electric_fleet)}")
return 225 my_leaf = ElectricCar('nissan', 'leaf', 2024)
Using an instance as an attribute
my_leaf.charge() Understanding self
my_leaf.drive()
People often ask what the self variable represents. The
class ElectricCar(Car): self variable is a reference to an object that's been created
--snip--
Importing an entire module
from the class.
import car The self variable provides a way to make other variables
def __init__(self, make, model, year):
and objects available everywhere in a class. The self
"""Initialize an electric car.""" my_beetle = car.Car(
variable is automatically passed to each method that's
super().__init__(make, model, year) 'volkswagen', 'beetle', 2021)
my_beetle.fill_tank() called through an object, which is why you see it listed first
# Attribute specific to electric cars. my_beetle.drive() in most method definitions. Any variable attached to self is
self.battery = Battery() available everywhere in the class.
my_leaf = car.ElectricCar('nissan', 'leaf',
def charge(self): 2024) Understanding __init__()
"""Fully charge the vehicle.""" my_leaf.charge() The __init__() method is a function that's part of a class,
self.battery.charge_level = 100 my_leaf.drive() just like any other method. The only special thing about
print("The vehicle is fully charged.") __init__() is that it's called automatically every time
Importing all classes from a module
Using the instance (Don’t do this, but recognize it when you see it.) you make a new instance from a class. If you accidentally
misspell __init__(), the method won't be called and your
my_ecar = ElectricCar('nissan', 'leaf', 2024) from car import * object may not be created correctly.
my_ecar.charge() my_beetle = Car('volkswagen', 'beetle', 2021)
print(my_ecar.battery.get_range()) my_leaf = ElectricCar('nissan', 'leaf', 2024)
my_ecar.drive() Weekly posts about all things Python
mostlypython.substack.com

You might also like