




















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





















Variables are used to assign labels to values. A string is a series of characters, surrounded by single or double quotes. Python's f-strings allow you to use variables inside strings to build dynamic messages.
print("Hello world!")
msg = "Hello world!" print(msg)
first_name = 'albert' last_name = 'einstein' full_name = f"{first_name} {last_name}" print(full_name)
A list stores a series of items in a particular order. You access items using an index, or within a loop.
bikes = ['trek', 'redline', 'giant']
first_bike = bikes[0]
last_bike = bikes[-1]
for bike in bikes: print(bike)
bikes = [] bikes.append('trek') bikes.append('redline') bikes.append('giant')
squares = [] for x in range(1, 11): squares.append(x**2)
squares = [x**2 for x in range(1, 11)]
finishers = ['sam', 'bob', 'ada', 'bea'] first_two = finishers[:2]
copy_of_bikes = bikes[:]
Tuples are similar to lists, but the items in a tuple can't be modified.
dimensions = (1920, 1080) resolutions = ('720p', '1080p', '4K')
If statements are used to test for particular conditions and respond appropriately.
equal x == 42 not equal x != 42 greater than x > 42 or equal to x >= 42 less than x < 42 or equal to x <= 42
'trek' in bikes 'surly' not in bikes
game_active = True can_edit = False
if age >= 18: print("You can vote!")
if age < 4: ticket_price = 0 elif age < 18: ticket_price = 10 elif age < 65: ticket_price = 40 else: ticket_price = 15
Dictionaries store connections between pieces of information. Each item in a dictionary is a key-value pair.
alien = {'color': 'green', 'points': 5}
print(f"The alien's color is {alien['color']}.")
alien['x_position'] = 0
fav_numbers = {'eric': 7, 'ever': 4, 'erin': 47} for name, number in fav_numbers.items(): print(f"{name} loves {number}.")
fav_numbers = {'eric': 7, 'ever': 4, 'erin': 47} for name in fav_numbers.keys(): print(f"{name} loves a number.")
fav_numbers = {'eric': 7, 'ever': 4, 'erin': 47} for number in fav_numbers.values(): print(f"{number} is a favorite.")
Your programs can prompt the user for input. All input is stored as a string.
name = input("What's your name? ") print(f"Hello, {name}!")
age = input("How old are you? ") age = int(age) pi = input("What's the value of pi? ") pi = float(pi)
ehmatthes.github.io/pcc_3e
A while loop repeats a block of code as long as a certain condition is true. While loops are especially useful when you can't know ahead of time how many times a loop should run.
current_value = 1 while current_value <= 5: print(current_value) current_value += 1
msg = '' while msg != 'quit': msg = input("What's your message? ") if msg != 'quit': print(msg)
Functions are named blocks of code, designed to do one specific job. Information passed to a function is called an argument, and information received by a function is called a parameter.
def greet_user(): """Display a simple greeting.""" print("Hello!") greet_user()
def greet_user(username): """Display a personalized greeting.""" print(f"Hello, {username}!") greet_user('jesse')
def make_pizza(topping='pineapple'): """Make a single-topping pizza.""" print(f"Have a {topping} pizza!") make_pizza() make_pizza('mushroom')
def add_numbers(x, y): """Add two numbers and return the sum.""" return x + y sum = add_numbers(3, 5) print(sum)
A class defines the behavior of an object and the kind of information an object can store. The information in a class is stored in attributes, and functions that belong to a class are called methods. A child class inherits the attributes and methods from its parent class.
class Dog: """Represent a dog.""" def init (self, name): """Initialize dog object.""" self.name = name def sit(self): """Simulate sitting.""" print(f"{self.name} is sitting.") my_dog = Dog('Peso') print(f"{my_dog.name} is a great dog!") my_dog.sit()
class SARDog(Dog): """Represent a search dog.""" def init (self, name): """Initialize the sardog.""" super(). init (name) def search(self): """Simulate searching.""" print(f"{self.name} is searching.") my_dog = SARDog('Willie') print(f"{my_dog.name} is a search dog.") my_dog.sit() my_dog.search()
If you had infinite programming skills, what would you build?
Downloaded by Boffin Boffin ([email protected])
Your programs can read from files and write to files. The pathlib library makes it easier to work with files and directories. Once you have a path defined, you can work with the read_text() and write_text() methods.
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 each line as you need to. from pathlib import Path path = Path('siddhartha.txt') contents = path.read_text() lines = contents.splitlines() for line in lines: print(line)
path = Path('journal.txt') msg = "I love programming.") path.write_text(msg)
Exceptions help you respond appropriately to errors that are likely to occur. You place code that might cause an error in the try block. Code that should run in response to an error goes in the except block. Code that should run only if the try block was successful goes in the else block.
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
mostlypython.substack.com
You can use the range() function to work with a set of numbers efficiently. The range() function starts at 0 by default, and stops one number below the number passed to it. You can use the list() function to efficiently generate a large list of numbers.
for number in range(1001): print(number)
for number in range(1, 1001): print(number)
numbers = list(range(1, 1_000_001))
There are a number of simple statistical operations you can run on a list containing numerical data.
ages = [93, 99, 66, 17, 85, 1, 35, 82, 2, 77] youngest = min(ages)
ages = [93, 99, 66, 17, 85, 1, 35, 82, 2, 77] oldest = max(ages)
ages = [93, 99, 66, 17, 85, 1, 35, 82, 2, 77] total_years = sum(ages)
You can work with any subset of elements from a list. A portion of a list is called a slice. To slice a list start with the index of the first item you want, then add a colon and the index after the last item you want. Leave off the first index to start at the beginning of the list, and leave off the second index to slice through the end of the list.
finishers = ['kai', 'abe', 'ada', 'gus', 'zoe'] first_three = finishers[:3]
middle_three = finishers[1:4]
last_three = finishers[-3:]
To copy a list make a slice that starts at the first item and ends at the last item. If you try to copy a list without using this approach, whatever you do to the copied list will affect the original list as well.
finishers = ['kai', 'abe', 'ada', 'gus', 'zoe'] copy_of_finishers = finishers[:]
You can use a loop to generate a list based on a range of numbers or on another list. This is a common operation, so Python offers a more efficient way to do it. List comprehensions may look complicated at first; if so, use the for loop approach until you're ready to start using comprehensions. To write a comprehension, define an expression for the values you want to store in the list. Then write a for loop to generate input values needed to make the list.
squares = [] for x in range(1, 11): square = x** squares.append(square)
squares = [x**2 for x in range(1, 11)]
names = ['kai', 'abe', 'ada', 'gus', 'zoe'] upper_names = [] for name in names: upper_names.append(name.upper())
names = ['kai', 'abe', 'ada', 'gus', 'zoe'] upper_names = [name.upper() for name in names]
Readability counts
A tuple is like a list, except you can't change the values in a tuple once it's defined. Tuples are good for storing information that shouldn't be changed throughout the life of a program. Tuples are usually designated by parentheses. You can overwrite an entire tuple, but you can't change the values of individual elements.
dimensions = (800, 600)
for dimension in dimensions: print(dimension)
dimensions = (800, 600) print(dimensions) dimensions = (1200, 900) print(dimensions)
When you're first learning about data structures such as lists, it helps to visualize how Python is working with the information in your program. Python Tutor is a great tool for seeing how Python keeps track of the information in a list. Try running the following code on pythontutor.com, and then run your own code.
dogs = [] dogs.append('willie') dogs.append('hootz') dogs.append('peso') dogs.append('goblin') for dog in dogs: print(f"Hello {dog}!") print("I love these dogs!") print("\nThese were my first two dogs:") old_dogs = dogs[:2] for old_dog in old_dogs: print(old_dog) del dogs[0] dogs.remove('peso') print(dogs)
mostlypython.substack.com
Try running some of these examples on pythontutor.com, and then run one of your own programs that uses dictionaries.
You can store as many key-value pairs as you want in a dictionary, until your computer runs out of memory. To add a new key-value pair to an existing dictionary give the name of the dictionary and the new key in square brackets, and set it equal to the new value. This also allows you to start with an empty dictionary and add key-value pairs as they become relevant.
alien_0 = {'color': 'green', 'points': 5} alien_0['x'] = 0 alien_0['y'] = 25 alien_0['speed'] = 1.
alien_0 = {} alien_0['color'] = 'green' alien_0['points'] = 5
You can modify the value associated with any key in a dictionary. To do so give the name of the dictionary and the key in square brackets, then provide the new value for that key.
alien_0 = {'color': 'green', 'points': 5} print(alien_0)
alien_0['color'] = 'yellow' alien_0['points'] = 10 print(alien_0)
You can remove any key-value pair you want from a dictionary. To do this use the del keyword and the dictionary name, followed by the key in square brackets. This will delete the key and its associated value.
alien_0 = {'color': 'green', 'points': 5} print(alien_0) del alien_0['points'] print(alien_0)
You can loop through a dictionary in three ways: you can loop through all the key-value pairs, all the keys, or all the values. Dictionaries keep track of the order in which key-value pairs are added. If you want to process the information in a different order, you can sort the keys in your loop, using the sorted() function.
fav_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', }
for name, language in fav_languages.items(): print(f"{name}: {language}")
for name in fav_languages.keys(): print(name)
for language in fav_languages.values(): print(language)
for name in sorted(fav_languages.keys(), reverse=True): language = fav_languages[name] print(f"{name}: {language}")
You can find the number of key-value pairs in a dictionary using the len() function.
num_responses = len(fav_languages)
Use curly braces to define a dictionary. Use colons to connect keys and values, and use commas to separate individual key-value pairs.
alien_0 = {'color': 'green', 'points': 5}
To access the value associated with an individual key give 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 dictionary, an error will occur. You can also use the get() method, which returns None instead of an error if the key doesn't exist. You can also specify a default value to use if the key is not in the dictionary.
alien_0 = {'color': 'green', 'points': 5} print(alien_0['color']) print(alien_0['points'])
alien_0 = {'color': 'green'} alien_color = alien_0.get('color') alien_points = alien_0.get('points', 0) alien_speed = alien_0.get('speed') print(alien_color) print(alien_points) print(alien_speed)
ehmatthes.github.io/pcc_3e
A conditional test is an expression that can be evaluated as true or false. Python uses the values True and False to decide whether the code in an if statement should be executed.
A single equal sign assigns a value to a variable. A double equal sign checks whether two values are equal. If your conditional tests aren't doing what you expect them to, make sure you're not accidentally using a single equal sign. >>> car = 'bmw' >>> car == 'bmw' True >>> car = 'audi' >>> car == 'bmw' False
>>> car = 'Audi' >>> car.lower() == 'audi' True
>>> topping = 'mushrooms' >>> topping != 'anchovies' True
Testing numerical values is similar to testing string values.
>>> age = 18 >>> age == 18 True >>> age != 18 False
>>> age = 19 >>> age < 21 True >>> age <= 21 True >>> age > 21 False >>> age >= 21 False
You can check multiple conditions at the same time. The and operator returns True if all the conditions listed are true. The or operator returns True if any condition is true.
>>> age_0 = 22 >>> age_1 = 18 >>> age_0 >= 21 and age_1 >= 21 False >>> age_1 = 23 >>> age_0 >= 21 and age_1 >= 21 True
>>> age_0 = 22 >>> age_1 = 18 >>> age_0 >= 21 or age_1 >= 21 True >>> age_0 = 18 >>> age_0 >= 21 or age_1 >= 21 False
A boolean value is either True or False_. Variables with boolean values are often used to keep track of certain conditions within a program._
game_active = True is_valid = True can_edit = False
Several kinds of if statements exist. Your choice of which to use depends on the number of conditions you need to test. You can have as many elif blocks as you need, and the else block is always optional.
age = 19 if age >= 18: print("You're old enough to vote!")
age = 17 if age >= 18: print("You're old enough to vote!") else: print("You can't vote yet.")
age = 12 if age < 4: price = 0 elif age < 18: price = 25 else: price = 40 print(f"Your cost is ${price}.")
You can easily test whether a certain value is in a list. You can also test whether a list is empty before trying to loop through the list.
>>> players = ['al', 'bea', 'cyn', 'dale'] >>> 'al' in players True >>> 'eric' in players False
>>> 'al' in players and 'cyn' in players
ehmatthes.github.io/pcc_3e
banned_users = ['ann', 'chad', 'dee'] user = 'erin' if user not in banned_users: print("You can play!")
An empty list evaluates as False in an if statement. players = [] if players: for player in players: print(f"Player: {player.title()}") else: print("We have no players yet!")
You can allow your users to enter input using the input() function. All input is initially stored as a string. If you want to accept numerical input, you'll need to convert the input string value to a numerical type.
name = input("What's your name? ") print(f"Hello, {name}.")
age = input("How old are you? ") age = int(age) if age >= 18: print("\nYou can vote!") else: print("\nSorry, you can't vote yet.")
tip = input("How much do you want to tip? ") tip = float(tip) print(f"Tipped ${tip}.")
A while loop repeats a block of code as long as a condition is true.
current_number = 1 while current_number <= 5: print(current_number) current_number += 1
prompt = "\nTell me something, and I'll " prompt += "repeat it back to you." prompt += "\nEnter 'quit' to end the program. " message = "" while message != 'quit': message = input(prompt) if message != 'quit': print(message)
Flags are most useful in long-running programs where code from other parts of the program might need to end the loop. prompt = "\nTell me something, and I'll " prompt += "repeat it back to you." prompt += "\nEnter 'quit' to end the program. " active = True while active: message = input(prompt) if message == 'quit': active = False else: print(message)
prompt = "\nWhat cities have you visited?" prompt += "\nEnter 'quit' when you're done. " while True: city = input(prompt) if city == 'quit': break else: print(f"I've been to {city}!")
Sublime Text, and a number of other text editors can't run programs that prompt the user for input. You can use these editors to write programs that prompt for input, but you'll need to run them from a terminal.
You can use the break statement and the continue statement with any of Python's loops. For example you can use break to quit a for loop that's working through a list or a dictionary. You can use continue to skip over certain items when looping through a list or dictionary as well.
banned_users = ['eve', 'fred', 'gary', 'helen'] prompt = "\nAdd a player to your team." prompt += "\nEnter 'quit' when you're done. " players = [] while True: player = input(prompt) if player == 'quit': break elif player in banned_users: print(f"{player} is banned!") continue else: players.append(player) print("\nYour team:") for player in players: print(player)
Every while loop needs a way to stop running so it won't continue to run forever. If there's no way for the condition to become false, the loop will never stop running. You can usually press Ctrl-C to stop an infinite loop.
while True: name = input("\nWho are you? ") print(f"Nice to meet you, {name}!")
The remove() method removes a specific value from a list, but it only removes the first instance of the value you provide. You can use a while loop to remove all instances of a particular value.
pets = ['dog', 'cat', 'dog', 'fish', 'cat', 'rabbit', 'cat'] print(pets) while 'cat' in pets: pets.remove('cat') print(pets)
mostlypython.substack.com
There are many ways to write and call a function. When you're starting out, aim for something that simply works. As you gain experience you'll develop an understanding of the subtle advantages of different structures such as positional and keyword arguments, and the various approaches to importing functions. For now if your functions do what you need them to, you're doing well.
You can pass a list as an argument to a function, and the function can work with the values in the list. Any changes the function makes to the list will affect the original list. You can prevent a function from modifying a list by passing a copy of the list as an argument.
def greet_users(names): """Print a simple greeting to everyone.""" for name in names: msg = f"Hello, {name}!" print(msg) usernames = ['hannah', 'ty', 'margot'] greet_users(usernames)
The following example sends a list of models to a function for printing. The first list is emptied, and the second list is filled. def print_models(unprinted, printed): """3d print a set of models.""" while unprinted: current_model = unprinted.pop() print(f"Printing {current_model}") printed.append(current_model)
unprinted = ['phone case', 'pendant', 'ring'] printed = [] print_models(unprinted, printed) print(f"\nUnprinted: {unprinted}") print(f"Printed: {printed}")
The following example is the same as the previous one, except the original list is unchanged after calling print_models(). def print_models(unprinted, printed): """3d print a set of models.""" while unprinted: current_model = unprinted.pop() print(f"Printing {current_model}") printed.append(current_model)
original = ['phone case', 'pendant', 'ring'] printed = [] print_models(original[:], printed) print(f"\nOriginal: {original}") print(f"Printed: {printed}")
Sometimes you won't know how many arguments a function will need to accept. Python allows you to collect an arbitrary number of arguments into one parameter using the * operator. A parameter that accepts an arbitrary number of arguments must come last in the function definition. This parameter is often named *args_. The_ ** operator allows a parameter to collect an arbitrary number of keyword arguments. These are stored as a dictionary with the parameter names as keys, and the arguments as values. This is often named **kwargs_._
def make_pizza(size, *toppings): """Make a pizza.""" print(f"\nMaking a {size} pizza.") print("Toppings:") for topping in toppings: print(f"- {topping}")
make_pizza('small', 'pepperoni') make_pizza('large', 'bacon bits', 'pineapple') make_pizza('medium', 'mushrooms', 'peppers', 'onions', 'extra cheese')
def build_profile(first, last, **user_info): """Build a dictionary for a user.""" user_info['first'] = first user_info['last'] = last return user_info
user_0 = build_profile('albert', 'einstein', location='princeton') user_1 = build_profile('marie', 'curie', location='paris', field='chemistry') print(user_0) print(user_1)
You can store your functions in a separate file called a module, and then import the functions you need into the file containing your main program. This allows for cleaner program files. Make sure your module is stored in the same directory as your main program.
File: pizza.py def make_pizza(size, *toppings): """Make a pizza.""" print(f"\nMaking a {size} pizza.") print("Toppings:") for topping in toppings: print(f"- {topping}")
File: making_pizzas.py Every function in the module is available in the program file. import pizza pizza.make_pizza('medium', 'pepperoni') pizza.make_pizza('small', 'bacon', 'pineapple')
Only the imported functions are available in the program file. from pizza import make_pizza make_pizza('medium', 'pepperoni') make_pizza('small', 'bacon', 'pineapple')
import pizza as p p.make_pizza('medium', 'pepperoni') p.make_pizza('small', 'bacon', 'pineapple')
from pizza import make_pizza as mp mp('medium', 'pepperoni') mp('small', 'bacon', 'pineapple')
Don't do this, but recognize it when you see it in others' code. It can result in naming conflicts, which can cause errors. from pizza import * make_pizza('medium', 'pepperoni') make_pizza('small', 'bacon', 'pineapple')
mostlypython.substack.com
In Python class names are usually written in CamelCase and object names are written in lowercase with underscores. Modules that contain classes should be named in lowercase with underscores.
my_car = Car('audi', 'a4', 2021)
print(my_car.make) print(my_car.model) print(my_car.year)
my_car.fill_tank() my_car.drive()
my_car = Car('audi', 'a4', 2024) my_old_car = Car('subaru', 'outback', 2018) my_truck = Car('toyota', 'tacoma', 2020) my_old_truck = Car('ford', 'ranger', 1999)
You can modify an attribute's value directly, or you can write methods that manage updating values more carefully. Methods like these can help validate the kinds of changes that are being made to an attribute.
my_new_car = Car('audi', 'a4', 2024) my_new_car.fuel_level = 5
def update_fuel_level(self, new_level): """Update the fuel level.""" if new_level <= self.fuel_capacity: self.fuel_level = new_level else: print("The tank can't hold that much!")
def add_fuel(self, amount): """Add fuel to the tank.""" if (self.fuel_level + amount <= self.fuel_capacity): self.fuel_level += amount print("Added fuel.") else: print("The tank won't hold that much.")
ehmatthes.github.io/pcc_3e
Consider how we might model a car. What information would we associate with a car, and what behavior would it have? The information is assigned to variables called attributes, and the behavior is represented by functions. Functions that are part of a class are called methods.
class Car: """A simple attempt to model a car.""" def init (self, make, model, year): """Initialize car attributes.""" self.make = make self.model = model self.year = year
self.fuel_capacity = 15 self.fuel_level = 0 def fill_tank(self): """Fill gas tank to capacity.""" self.fuel_level = self.fuel_capacity print("Fuel tank is full.") def drive(self): """Simulate driving.""" print("The car is moving.")
If the class you're writing is a specialized version of another class, you can use inheritance. When one class inherits from another, it automatically takes on all the attributes and methods of the parent class. The child class is free to introduce new attributes and methods, and override attributes and methods of the parent class. To inherit from another class include the name of the parent class in parentheses when defining the new class.
class ElectricCar(Car): """A simple model of an electric car.""" def init (self, make, model, year): """Initialize an electric car.""" super(). init (make, model, year)
self.battery_size = 40
self.charge_level = 0
class ElectricCar(Car): --snip-- def charge(self): """Fully charge the vehicle.""" self.charge_level = 100 print("The vehicle is fully charged.")
my_ecar = ElectricCar('nissan', 'leaf', 2024) my_ecar.charge() my_ecar.drive()
There are many ways to model real world objects and situations in code, and sometimes that variety can feel overwhelming. Pick an approach and try it; if your first attempt doesn't work, try a different approach.
To read from a file your program needs to specify the path to the file, and then read the contents of the file. The read_text() method returns a string containing the entire contents of the file.
from pathlib import Path path = Path('siddhartha.txt') contents = path.read_text() print(contents)
It's often useful to work with individual lines from a file. Once the contents of a file have been read, you can get the lines using the splitlines() method. from pathlib import Path path = Path('siddhartha.txt') contents = path.read_text() lines = contents.splitlines() for line in lines: print(line)
The write_text() method can be used to write text to a file. Be careful, this will write over the current file if it already exists. To append to a file, read the contents first and then rewrite the entire file.
from pathlib import Path path = Path("programming.txt") msg = "I love programming!" path.write_text(msg)
from pathlib import Path path = Path("programming.txt") msg = "I love programming!" msg += "\nI love making games." path.write_text(msg)
from pathlib import Path path = Path("programming.txt") contents = path.read_text() contents += "\nI love programming!" contents += "\nI love making games." path.write_text(contents)
The pathlib module makes it easier to work with files in Python. A Path object represents a file or directory, and lets you carry out common directory and file operations. With a relative path, Python usually looks for a location relative to the .py file that's running. Absolute paths are relative to your system's root folder ( "/" ). Windows uses backslashes when displaying file paths, but you should use forward slashes in your Python code.
path = Path("text_files/alice.txt")
path = Path("/Users/eric/text_files/alice.txt")
>>> path = Path("text_files/alice.txt") >>> path.name 'alice.txt'
base_path = Path("/Users/eric/text_files") file_path = base_path / "alice.txt"
>>> path = Path("text_files/alice.txt") >>> path.exists() True
>>> path.suffix '.txt'
When you think an error may occur, you can write a try- except block to handle the exception that might be raised. The try block tells Python to try running some code, and the except block tells Python what to do if the code results in a particular kind of error.
try: print(5/0) except ZeroDivisionError: print("You can't divide by zero!")
from pathlib import Path path = Path("siddhartha.txt") try: contents = path.read_text() except FileNotFoundError: msg = f"Can’t find file: {path.name}." print(msg)
It can be hard to know what kind of exception to handle when writing code. Try writing your code without a try block, and make it generate an error. The traceback will tell you what kind of exception your program needs to handle. It's a good idea to skim through the exceptions listed at docs.python.org/3/library/exceptions.html.
ehmatthes.github.io/pcc_3e
The try block should only contain code that may cause an error. Any code that depends on the try block running successfully should be placed in the else block.
print("Enter two numbers. I'll divide them.") x = input("First number: ") y = input("Second number: ") try: result = int(x) / int(y) except ZeroDivisionError: print("You can't divide by zero!") else: print(result)
Without the except block in the following example, the program would crash if the user tries to divide by zero. As written, it will handle the error gracefully and keep running. """A simple calculator for division only.""" print("Enter two numbers. I'll divide them.") print("Enter 'q' to quit.") while True: x = input("\nFirst number: ") if x == 'q': break y = input("Second number: ") if y == 'q': break try: result = int(x) / int(y) except ZeroDivisionError: print("You can't divide by zero!") else: print(result)
Well-written, properly tested code is not very prone to internal errors such as syntax or logical errors. But every time your program depends on something external such as user input or the existence of a file, there's a possibility of an exception being raised. It's up to you how to communicate errors to your users. Sometimes users need to know if a file is missing; sometimes it's better to handle the error silently. A little experience will help you know how much to report.
Sometimes you want your program to just continue running when it encounters an error, without reporting the error to the user. Using the pass statement in an except block allows you to do this.
from pathlib import Path f_names = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt'] for f_name in f_names:
path = Path(f_name) try: contents = path.read_text() except FileNotFoundError: pass else: lines = contents.splitlines() msg = f"{f_name} has {len(lines)}" msg += " lines." print(msg)
Exception handling code should catch specific exceptions that you expect to happen during your program's execution. A bare except block will catch all exceptions, including keyboard interrupts and system exits you might need when forcing a program to close. If you want to use a try block and you're not sure which exception to catch, use Exception_. It will catch most exceptions, but still allow you to interrupt programs intentionally._
try:
except: pass
try:
except Exception: pass
try:
except Exception as e: print(e, type(e))
The json module allows you to dump simple Python data structures into a file, and load the data from that file the next time the program runs. The JSON data format is not specific to Python, so you can share this kind of data with people who work in other languages as well. Knowing how to manage exceptions is important when working with stored data. You'll usually want to make sure the data you're trying to load exists before working with it.
from pathlib import Path import json numbers = [2, 3, 5, 7, 11, 13] path = Path("numbers.json") contents = json.dumps(numbers) path.write_text(contents)
from pathlib import Path import json path = Path("numbers.json") contents = path.read_text() numbers = json.loads(contents) print(numbers)
from pathlib import Path import json path = Path("numbers.json") try: contents = path.read_text() except FileNotFoundError: msg = f"Can't find file: {path}" print(msg) else: numbers = json.loads(contents) print(numbers)
Take a program you've already written that prompts for user input, and add some error-handling code to the program. Run your program with appropriate and inappropriate data, and make sure it handles each situation correctly.
mostlypython.substack.com
You can add as many unit tests to a test case as you need. To write a new test, add a new function to your test file. If the file grows too long, you can add as many files as you need.
We’ve shown that get_full_name() works for first and last names. Let’s test that it works for middle names as well. from full_names import get_full_name def test_first_last(): """Test names like Janis Joplin.""" full_name = get_full_name('janis', 'joplin') assert full_name == 'Janis Joplin' def test_middle(): """Test names like David Lee Roth.""" full_name = get_full_name('david', 'roth', 'lee') assert full_name == 'David Lee Roth'
The two dots after test_full_names.py represent two passing tests. $ pytest ============= test session starts ============= collected 2 items test_full_names.py .. [100%] ============== 2 passed in 0.01s ==============
You can use assert statements in a variety of ways, to check for the exact conditions you want to verify.
assert a == b assert a != b
assert x assert not x
assert my_item in my_list assert my_item not in my_list
In a growing test suite, you can have multiple test files. Sometimes you'll only want to run the tests from one file. You can pass the name of a file, and pytest will only run the tests in that file: $ pytest test_names_function.py
Testing a class is similar to testing a function, since you’ll mostly be testing its methods.
Save as account.py class Account(): """Manage a bank account.""" def init (self, balance=0): """Set the initial balance.""" self.balance = balance def deposit(self, amount): """Add to the balance.""" self.balance += amount def withdraw(self, amount): """Subtract from the balance.""" self.balance - = amount
For the first test, we’ll make sure we can start out with different initial balances. Save this as test_accountant.py. from account import Account def test_initial_balance(): """Default balance should be 0.""" account = Account() assert account.balance == 0 def test_deposit(): """Test a single deposit.""" account = Account() account.deposit(100) assert account.balance == 100
$ pytest ============= test session starts ============= collected 2 items test_account.py .. [100%] ============== 2 passed in 0.01s ==============
In general you shouldn’t modify a test once it’s written. When a test fails it usually means new code you’ve written has broken existing functionality, and you need to modify the new code until all existing tests pass. If your original requirements have changed, it may be appropriate to modify some tests. This usually happens in the early stages of a project when desired behavior is still being sorted out, and no one is using your code yet.
A fixture is a resource that's used in multiple tests. When the name of a fixture function is used as an argument to a test function, the return value of the fixture is passed to the test function. When testing a class, you often have to make an instance of the class. Fixtures let you work with just one instance.
The instance acc can be used in each new test. import pytest from account import Account @pytest.fixture def account(): account = Account() return account def test_initial_balance(account): """Default balance should be 0.""" assert account.balance == 0 def test_deposit(account): """Test a single deposit.""" account.deposit(100) assert account.balance == 100 def test_withdrawal(account): """Test a deposit followed by withdrawal.""" account.deposit(1_000) account.withdraw(100) assert account.balance == 900
$ pytest ============= test session starts ============= collected 3 items test_account.py ... [100%] ============== 3 passed in 0.01s ==============
pytest has some flags that can help you run your tests efficiently, even as the number of tests in your project grows.
$ pytest - x
$ pytest --last-failed
mostlypython.substack.com
The display.set_mode() function accepts a tuple that defines the screen size. screen_dim = (1500, 1000) self.screen = pygame.display.set_mode( screen_dim)
Colors are defined as a tuple of red, green, and blue values. Each value ranges from 0 - 255. The fill() method fills the screen with the color you specify, and should be called before you add any other elements to the screen. def init (self): --snip-- self.bg_color = (225, 225, 225) def run_game(self): while True: for event in pygame.event.get(): --snip-- self.screen.fill(self.bg_color) pygame.display.flip()
Many objects in a game can be treated as simple rectangles, rather than their actual shape. This simplifies code without noticeably affecting game play. Pygame has a rect object that makes it easy to work with game objects.
We already have a screen object; we can easily access the rect object associated with the screen. self.screen_rect = self.screen.get_rect()
Rect objects have a center attribute which stores the center point. screen_center = self.screen_rect.center
Once you have a rect object, there are a number of attributes that are useful when positioning objects and detecting relative positions of objects. (You can find more attributes in the Pygame documentation. The self variable has been left off for clarity.)
screen_rect.left, screen_rect.right screen_rect.top, screen_rect.bottom screen_rect.centerx, screen_rect.centery screen_rect.width, screen_rect.height
screen_rect.center screen_rect.size Python Crash Course
ehmatthes.github.io/pcc_3e Beginner's Python Cheat Sheet - Pygame
$ python - m pip install --user pygame
The following code sets up an empty game window, and starts an event loop and a loop that continually refreshes the screen.
import sys import pygame class AlienInvasion: """Overall class to manage the game.""" def init (self): pygame.init() self.clock = pygame.time.Clock() self.screen = pygame.display.set_mode( (1200, 800)) pygame.display.set_caption( "Alien Invasion") def run_game(self): while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() pygame.display.flip() self.clock.tick(60) if name == ' main ':
ai = AlienInvasion() ai.run_game()
You can create a rect object from scratch. For example a small rect object that’s filled in can represent a bullet in a game. The Rect() class takes the coordinates of the upper left corner, and the width and height of the rect. The draw.rect() function takes a screen object, a color, and a rect. This function fills the given rect with the given color. bullet_rect = pygame.Rect(100, 100, 3, 15) color = (100, 100, 100) pygame.draw.rect(screen, color, bullet_rect)
Many objects in a game are images that are moved around the screen. It’s easiest to use bitmap (.bmp) image files, but you can also configure your system to work with jpg, png, and gif files as well.
ship = pygame.image.load('images/ship.bmp')
ship_rect = ship.get_rect()
With rects, it’s easy to position an image wherever you want on the screen, or in relation to another object. The following code positions a ship at the bottom center of the screen, by matching the midbottom of the ship with the midbottom of the screen. ship_rect.midbottom = screen_rect.midbottom
Once an image is loaded and positioned, you can draw it to the screen with the blit() method. The blit() method acts on the screen object, and takes the image object and image rect as arguments.
screen.blit(ship, ship_rect)
The transform module allows you to make changes to an image such as rotation and scaling. rotated_image = pygame.transform.rotate( ship.image, 45)
$ python - m pip install --user matplotlib
The fig object represents the entire figure, or collection of plots; ax represents a single plot in the figure. This convention is used even when there's only one plot in the figure. import matplotlib.pyplot as plt x_values = [0, 1, 2, 3, 4, 5] squares = [0, 1, 4, 9, 16, 25] fig, ax = plt.subplots() ax.plot(x_values, squares) plt.show()
scatter() takes a list of x and y values; the s=10 argument controls the size of each point. import matplotlib.pyplot as plt x_values = list(range(1000)) squares = [x**2 for x in x_values] fig, ax = plt.subplots() ax.scatter(x_values, squares, s=10) plt.show()
Plots can be customized in a wide variety of ways. Just about any element of a plot can be modified.
Matplotlib comes with a number of built-in styles, which you can use with one additional line of code. The style must be specified before you create the figure. import matplotlib.pyplot as plt x_values = list(range(1000)) squares = [x**2 for x in x_values] plt.style.use('seaborn-v0_8') fig, ax = plt.subplots() ax.scatter(x_values, squares, s=10) plt.show()
You can see all available styles on your system. This can be done in a terminal session. >>> import matplotlib.pyplot as plt >>> plt.style.available ['Solarize_Light2', '_classic_test_patch', ...
import matplotlib.pyplot as plt x_values = list(range(1000)) squares = [x**2 for x in x_values]
plt.style.use('seaborn-v0_8') fig, ax = plt.subplots() ax.scatter(x_values, squares, s=10)
ax.set_title('Square Numbers', fontsize=24) ax.set_xlabel('Value', fontsize=14) ax.set_ylabel('Square of Value', fontsize=14)
ax.axis([0, 1100, 0, 1_100_000]) ax.tick_params(axis='both', labelsize=14) plt.show()
A colormap varies the point colors from one shade to another, based on a certain value for each point. The value used to determine the color of each point is passed to the c argument, and the cmap argument specifies which colormap to use. ax.scatter(x_values, squares, c=squares, cmap=plt.cm.Blues, s=10)
You can plot as much data as you want on one plot. Here we replot the first and last points larger to emphasize them. import matplotlib.pyplot as plt x_values = list(range(1000)) squares = [x**2 for x in x_values] fig, ax = plt.subplots() ax.scatter(x_values, squares, c=squares, cmap=plt.cm.Blues, s=10) ax.scatter(x_values[0], squares[0], c='green', s=100) ax.scatter(x_values[-1], squares[-1], c='red', s=100) ax.set_title('Square Numbers', fontsize=24) --snip--
You can customize or remove axes entirely. Here’s how to access each axis, and hide it. ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False)
You can make your plot as big or small as you want by using the figsize argument. The dpi argument is optional; if you don’t know your system’s resolution you can omit the argument and adjust the figsize argument accordingly. fig, ax = plt.subplots(figsize=(10, 6), dpi=128)
The Matplotlib viewer has a save button, but you can also save your visualizations programmatically by replacing plt.show() with plt.savefig(). The bbox_inches argument reduces the amount of whitespace around the figure. plt.savefig('squares.png', bbox_inches='tight')
The matplotlib gallery and documentation are at matplotlib.org/. Be sure to visit the Examples, Tutorials, and User guide sections.
ehmatthes.github.io/pcc_3e
The strptime() function generates a datetime object from a string, and the strftime() method generates a formatted string from a datetime object. The following codes let you work with dates exactly as you need to. %A Weekday name, such as Monday %B Month name, such as January %m Month, as a number (01 to 12) %d Day of the month, as a number (01 to 31) %Y Four-digit year, such as 2021 %y Two-digit year, such as 21 %H Hour, in 24-hour format (00 to 23) %I Hour, in 12-hour format (01 to 12) %p AM or PM %M Minutes (00 to 59) %S Seconds (00 to 61)
new_years = dt.strptime('1/1/2023', '%m/%d/%Y')
ny_string = new_years.strftime('%B %d, %Y') print(ny_string)
The following code creates a list of dates and a corresponding list of high temperatures. It then plots the high temperatures, with the date labels displayed in a specific format. from datetime import datetime as dt import matplotlib.pyplot as plt from matplotlib import dates as mdates dates = [ dt(2023, 6, 21), dt(2023, 6, 22), dt(2023, 6, 23), dt(2023, 6, 24), ] highs = [56, 57, 57, 64] plt.style.use('seaborn-v0_8') fig, ax = plt.subplots() ax.plot(dates, highs, c='red') ax.set_title("Daily High Temps", fontsize=24) ax.set_ylabel("Temp (F)", fontsize=16) x_axis = ax.get_xaxis() x_axis.set_major_formatter( mdates.DateFormatter('%B %d %Y') ) fig.autofmt_xdate() plt.show()
You can include as many individual graphs in one figure as you want.
The following code plots a set of squares and a set of cubes on two separate graphs that share a common x-axis. The plt. subplots() function returns a figure object and a tuple of axes. Each set of axes corresponds to a separate plot in the figure. The first two arguments control the number of rows and columns generated in the figure. import matplotlib.pyplot as plt x_values = list(range(11)) squares = [x2 for x in x_values] cubes = [x3 for x in x_values] fig, axs = plt.subplots(2, 1, sharex=True) axs[0].scatter(x_values, squares) axs[0].set_title('Squares') axs[1].scatter(x_values, cubes, c='red') axs[1].set_title('Cubes') plt.show()
To share a y-axis, use the sharey=True argument. import matplotlib.pyplot as plt x_values = list(range(11)) squares = [x2 for x in x_values] cubes = [x3 for x in x_values] plt.style.use('seaborn-v0_8') fig, axs = plt.subplots(1, 2, sharey=True) axs[0].scatter(x_values, squares) axs[0].set_title('Squares') axs[1].scatter(x_values, cubes, c='red') axs[1].set_title('Cubes') plt.show()
mostlypython.substack.com
You can make as many plots as you want on one figure. When you make multiple plots, you can emphasize relationships in the data. For example you can fill the space between two sets of data.
Here we use ax.scatter() twice to plot square numbers and cubes on the same figure. import matplotlib.pyplot as plt x_values = list(range(11)) squares = [x2 for x in x_values] cubes = [x3 for x in x_values] plt.style.use('seaborn-v0_8') fig, ax = plt.subplots() ax.scatter(x_values, squares, c='blue', s=10) ax.scatter(x_values, cubes, c='red', s=10) plt.show()
The fill_between() method fills the space between two data sets. It takes a series of x-values and two series of y-values. It also takes a facecolor to use for the fill, and an optional alpha argument that controls the color’s transparency. ax.fill_between(x_values, cubes, squares, facecolor='blue', alpha=0.25)
Many interesting data sets have a date or time as the x value. Python’s datetime module helps you work with this kind of data.
The datetime.now() function returns a datetime object representing the current date and time. from datetime import datetime as dt today = dt.now() date_string = today.strftime('%m/%d/%Y') print(date_string)
You can also generate a datetime object for any date and time you want. The positional order of arguments is year, month, and day. The hour, minute, second, and microsecond arguments are optional. from datetime import datetime as dt new_years = dt(2023, 1, 1) fall_equinox = dt(year=2023, month=9, day=22)