HELLO WORLD
SIMPLE MESSAGES
print("Hello Python World!")
PERSONAL MESSAGE
# Store a message in a variable, and print that message.
# Then change the value of your variable to a new message, and print the new
# message.
message = "Hello Python world!"
print(message)
message = "Hello Python Crash Course world!"
print(message)
NAME CASES
# Store a person’s name in a variable, and print a message to that person.
# Your message should be simple, such as, “Hello Eric, would you like to
# learn some Python today?”
name = "Justin"
print("Hello " + name + ", would you like to learn some Python today?")
FAMOUS QUOTE
# Store a person’s name in a variable, and then print that person’s
# name in lowercase, uppercase, and titlecase.
name = "Isciuc Iustin - Constantin"
print(name.lower())
print(name.upper())
print(name.title())
STRIPPING NAMES
# Find a quote from a famous person you admire. Print the
# quote and the name of its author. Your output should look something like the
# following, including the quotation marks:
# Albert Einstein once said, “A person who never made a
# mistake never tried anything new.”
author = "Seneca"
quote = "To be everywhere is to be nowhere!"
print(author + " writted " + '"' + quote + '"')
NUMBER EIGHT
# Store a person’s name, and include some whitespace
# characters at the beginning and end of the name. Make sure you use each
# character combination, "\t" and "\n", at least once.
# Print the name once, so the whitespace around the name is displayed.
# Then print the name using each of the three stripping functions, lstrip(),
# rstrip(), and strip().
person_name = " Razvan\nCazacu\tConstantin "
print(person_name.lstrip())
print(person_name.rstrip())
print(person_name.strip())
FAVORITE NUMBER
# Write addition, subtraction, multiplication, and division
# operations that each result in the number 8. Be sure to enclose your operations
# in print statements to see the results. You should create four lines that look
# like this:
# print(5 + 3)
# Your output should simply be four lines with the number 8 appearing once
# on each line.
print(5 + 3)
print(10 - 2)
print(4 * 2)
print(24 // 3)
ADDING COMMENTS!
# Store your favorite number in a variable. Then, using
# that variable, create a message that reveals your favorite number. Print that
# message.
favorite_number = 6
message = "My favorite number is " + str(favorite_number)
print(message)
NAMES
# Choose two of the programs you’ve written, and
# add at least one comment to each. If you don’t have anything specific to write
# because your programs are too simple at this point, just add your name and
# the current date at the top of each program file. Then write one sentence
# describing what the program does.
# ISCIUC IUSTIN - CONSTANTIN 10.01.2024
# THIS PROGRAM PRINTS Hello Python World to the terminal
print("Hello Python World!")
GREETINGS
# Store the names of a few of your friends in a list called names. Print
# each person’s name by accessing each element in the list, one at a time.
names = ["Razvan", "Petronel", "Sebastian"]
print(names[0])
print(names[1])
print(names[2])
YOUR OWN LIST
# Start with the list you used in Exercise 3-1, but instead of just
# printing each person’s name, print a message to them. The text of each message should be the same, but each message should be personalized with the
# person’s name.
names = ["Razvan", "Petronel", "Sebastian"]
print("Hello my dear friend " + names[0])
print("Hello my dear friend " + names[1])
print("Hello my dear friend " + names[2])
GUEST LIST
# Think of your favorite mode of transportation, such as a
# motorcycle or a car, and make a list that stores several examples. Use your list
# to print a series of statements about these items, such as “I would like to own a
# Honda motorcycle.”
cars = ["Lamborghini Revuelto", "Maserati Mc20", "Range Rover Sport"]
print("I would like to own a " + cars[0])
print("The best Maserati is " + cars[1])
print("My favorite SUV is " + cars[2])
CHANGING GUEST LIST
# If you could invite anyone, living or deceased, to dinner, who
# would you invite? Make a list that includes at least three people you’d like to
# invite to dinner. Then use your list to print a message to each person, inviting
# them to dinner
guest_list = ["Jeff Beszos", "John White", "Jim Rohn"]
print("Hy Mr. " + guest_list[0] + " I would like to invite you to dinner!")
print("Hy Mr. " + guest_list[1] + " I would like to invite you to dinner!")
print("Hy Mr. " + guest_list[2] + " I would like to invite you to dinner!")
SEEING THE WORLD
# You just heard that one of your guests can’t make the
# dinner, so you need to send out a new set of invitations. You’ll have to think of
# someone else to invite.
# • Start with your program from Exercise 3-4. Add a print statement at the
# end of your program stating the name of the guest who can’t make it.
# • Modify your list, replacing the name of the guest who can’t make it with
# the name of the new person you are inviting.
# • Print a second set of invitation messages, one for each person who is still
# in your list.
guest_list = ["Jeff Beszos", "John White", "Jim Rohn"]
print("Hy Mr. " + guest_list[0] + " I would like to invite you to dinner!")
print("Hy Mr. " + guest_list[1] + " I would like to invite you to dinner!")
print("Hy Mr. " + guest_list[2] + " I would like to invite you to dinner!")
print("Hy Mr. " + guest_list[0] + " can't attend the dinner!")
guest_list.pop(0)
guest_list.insert(0, "George Washington")
print("Hy Mr. " + guest_list[0] + " I would like to invite you to dinner!")
print("Hy Mr. " + guest_list[1] + " I would like to invite you to dinner!")
print("Hy Mr. " + guest_list[2] + " I would like to invite you to dinner!")
guest_list.insert(0, "Dorian Popa")
guest_list.insert(2, "Allen Turing")
guest_list.append("Jesus Christ")
print("Hy Mr. " + guest_list[0] + " I would like to invite you to dinner!")
print("Hy Mr. " + guest_list[1] + " I would like to invite you to dinner!")
print("Hy Mr. " + guest_list[2] + " I would like to invite you to dinner!")
print("Hy Mr. " + guest_list[3] + " I would like to invite you to dinner!")
print("Hy Mr. " + guest_list[4] + " I would like to invite you to dinner!")
print("Hy Mr. " + guest_list[5] + " I would like to invite you to dinner!")
print("Hy unfortunately I found out that I can invite only 2 people to dinner")
print("Hy Mr. " + guest_list.pop() + " I can't invite you to the dinner!")
print("Hy Mr. " + guest_list.pop() + " I can't invite you to the dinner!")
print("Hy Mr. " + guest_list.pop() + " I can't invite you to the dinner!")
print("Hy Mr. " + guest_list.pop() + " I can't invite you to the dinner!")
print("Hy Mr. " + guest_list[0] + " you are still invited to dinner")
print("Hy Mr. " + guest_list[1] + " you are still invited to dinner")
del guest_list[0]
del guest_list[0]
print(guest_list)
DINNER GUESTS
# Think of at least five places in the world you’d like to
# visit.
# • Store the locations in a list. Make sure the list is not in alphabetical order.
# • Print your list in its original order. Don’t worry about printing the list neatly,
# just print it as a raw Python list.
# • Use sorted() to print your list in alphabetical order without modifying the
# actual list.
# • Show that your list is still in its original order by printing it.
# • Use sorted() to print your list in reverse alphabetical order without changing the order of the original list.
# • Show that your list is still in its original order by printing it again.
# • Use reverse() to change the order of your list. Print the list to show that its
# order has changed.
# • Use reverse() to change the order of your list again. Print the list to show
# it’s back to its original order.
# • Use sort() to change your list so it’s stored in alphabetical order. Print the
# list to show that its order has been changed.
# • Use sort() to change your list so it’s stored in reverse alphabetical order.
# Print the list to show that its order has changed.
locations = ["Apple Park Cupertino", "Brasv Romania", "White House", "Capitol", "Times Square NYC"]
print(locations)
print(sorted(locations))
print(locations)
print(sorted(locations, reverse=True))
print(locations)
locations.reverse()
print(locations)
locations.reverse()
print(locations)
locations.sort()
print(locations)
locations.sort(reverse=True)
print(locations)
PIZZAS
# Working with the following program use len() to print a message indicating the number
# of people you are inviting to dinner.
guest_list = ["Jeff Beszos", "John White", "Jim Rohn"]
print("Hy Mr. " + guest_list[0] + " I would like to invite you to dinner!")
print("Hy Mr. " + guest_list[1] + " I would like to invite you to dinner!")
print("Hy Mr. " + guest_list[2] + " I would like to invite you to dinner!")
print("I invite " + str(len(guest_list)) + " guests to dinner" )
print("Hy Mr. " + guest_list[0] + " can't attend the dinner!")
guest_list.pop(0)
guest_list.insert(0, "George Washington")
print("Hy Mr. " + guest_list[0] + " I would like to invite you to dinner!")
print("Hy Mr. " + guest_list[1] + " I would like to invite you to dinner!")
print("Hy Mr. " + guest_list[2] + " I would like to invite you to dinner!")
print("I invite " + str(len(guest_list)) + " guests to dinner" )
guest_list.insert(0, "Dorian Popa")
guest_list.insert(2, "Allen Turing")
guest_list.append("Jesus Christ")
print("Hy Mr. " + guest_list[0] + " I would like to invite you to dinner!")
print("Hy Mr. " + guest_list[1] + " I would like to invite you to dinner!")
print("Hy Mr. " + guest_list[2] + " I would like to invite you to dinner!")
print("Hy Mr. " + guest_list[3] + " I would like to invite you to dinner!")
print("Hy Mr. " + guest_list[4] + " I would like to invite you to dinner!")
print("Hy Mr. " + guest_list[5] + " I would like to invite you to dinner!")
print("I invite " + str(len(guest_list)) + " guests to dinner" )
print("Hy unfortunately I found out that I can invite only 2 people to dinner")
print("Hy Mr. " + guest_list.pop() + " I can't invite you to the dinner!")
print("Hy Mr. " + guest_list.pop() + " I can't invite you to the dinner!")
print("Hy Mr. " + guest_list.pop() + " I can't invite you to the dinner!")
print("Hy Mr. " + guest_list.pop() + " I can't invite you to the dinner!")
print("Hy Mr. " + guest_list[0] + " you are still invited to dinner")
print("Hy Mr. " + guest_list[1] + " you are still invited to dinner")
print("I invite " + str(len(guest_list)) + " guests to dinner" )
del guest_list[0]
del guest_list[0]
print(guest_list)
ANIMALS
# Think of at least three kinds of your favorite pizza. Store these
# pizza names in a list, and then use a for loop to print the name of each pizza.
# • Modify your for loop to print a sentence using the name of the pizza
# instead of printing just the name of the pizza. For each pizza you should
# have one line of output containing a simple statement like I like pepperoni
# pizza.
# • Add a line at the end of your program, outside the for loop, that states
# how much you like pizza. The output should consist of three or more lines
# about the kinds of pizza you like and then an additional sentence, such as
# I really love pizza!
pizza_names = ["Hatz", "Pepperoni", "Margherita"]
for pizza_name in pizza_names:
print("I like " + pizza_name + " pizza!")
print("I really love pizza!")
COUNTING TO TWENTY
# Think of at least three different animals that have a common characteristic. Store the names of these animals in a list, and then use a for loop to
# print out the name of each animal.
# • Modify your program to print a statement about each animal, such as
# A dog would make a great pet.
# • Add a line at the end of your program stating what these animals have in
# common. You could print a sentence such as Any of these animals would
# make a great pet!
animals = ["Cat", "Dog", "Hamster"]
for animal in animals:
print("A " + animal + " would make a great pet!")
print("Any of this animals would make a great pet!")
ONE MILLION
# Use a for loop to print the numbers from 1 to 20,
# inclusive.
for number in range(1, 11):
print(number)
SUMMING A MILLION
# Make a list of the numbers from one to one million, and then
# use a for loop to print the numbers. (If the output is taking too long, stop it by
# pressing ctrl-C or by closing the output window.
values = [value for value in range(1, 1000001)]
for value in values:
print(value)
ODD NUMBERS
# Make a list of the numbers from one to one million,
# and then use min() and max() to make sure your list actually starts at one and
# ends at one million. Also, use the sum() function to see how quickly Python can
# add a million numbers.
values = [value for value in range(1, 1000001)]
print(min(values))
print(max(values))
print(sum(values))
THREES
# Use the third argument of the range() function to make a list
# of the odd numbers from 1 to 20. Use a for loop to print each number.
odd_numbers = [value for value in range(1,20,2)]
for odd_number in odd_numbers:
print(odd_number)
CUBES
# Make a list of the multiples of 3 from 3 to 30. Use a for loop to
# print the numbers in your list.
threes = [value for value in range(3, 31, 3)]
for three in threes:
print(three)
SLICES
# A number raised to the third power is called a cube. For example,
# the cube of 2 is written as 2**3 in Python. Make a list of the first 10 cubes (that
# is, the cube of each integer from 1 through 10), and use a for loop to print out
# the value of each cube.
cubes = [value ** 3 for value in range(1, 11)]
for cube in cubes:
print(cube)
MY PIZZA, YOUR PIZZA
# Using one of the programs you wrote in this chapter, add several
# lines to the end of the program that do the following:
# • Print the message, The first three items in the list are:. Then use a slice to
# print the first three items from that program’s list.
# • Print the message, Three items from the middle of the list are:. Use a slice
# to print three items from the middle of the list.
# • Print the message, The last three items in the list are:. Use a slice to print
# the last three items in the list.
cubes = [value ** 3 for value in range(1, 11)]
for cube in cubes:
print(cube)
print("The first three items in the list are : " + str(cubes[:3]))
print("Three items from the middle of the list are : " + str(cubes[4:7]))
print("The last three items in the list are: " + str(cubes[-3:]))
BUFFET
# Start with your program from Exercise 4-1
# (page 60). Make a copy of the list of pizzas, and call it friend_pizzas.
# Then, do the following:
# • Add a new pizza to the original list.
# • Add a different pizza to the list friend_pizzas.
# • Prove that you have two separate lists. Print the message, My favorite
# pizzas are:, and then use a for loop to print the first list. Print the message,
# My friend’s favorite pizzas are:, and then use a for loop to print the second list. Make sure each new pizza is stored in the appropriate list.
pizza_names = ["Hatz", "Pepperoni", "Margherita"]
for pizza_name in pizza_names:
print("I like " + pizza_name + " pizza!")
print("I really love pizza!")
friend_pizzas = pizza_names[:]
pizza_names.append("Neapolitan")
friend_pizzas.append("Marinara")
print("My favorite pizzas are : ")
for favorite_pizza in pizza_names:
print(favorite_pizza)
print("My freind's favorite pizzas are : ")
for friend_pizza in friend_pizzas:
print(friend_pizza)
ALIEN COLORS #1
# A buffet-style restaurant offers only five basic foods. Think of five
# simple foods, and store them in a tuple.
# • Use a for loop to print each food the restaurant offers.
# • Try to modify one of the items, and make sure that Python rejects the
# change.
# • The restaurant changes its menu, replacing two of the items with different
# foods. Add a block of code that rewrites the tuple, and then use a for
# loop to print each of the items on the revised menu
foods = ("Hot Dog", "Hatz Pizza", "Hamburger", "Doughnut", "Cheeseburger")
for food in foods:
print(food)
# foods[1] = "Margherita Pizza" THIS PRODUCES AN ERROR
foods = ["Margherita Pizza", "Hatz Pizza", "Marinara Pizza", "Doughnut", "Cheeseburger"]
for food in foods:
print(food)
STAGES OF LIFE
# Imagine an alien was just shot down in a game. Create a
# variable called alien_color and assign it a value of 'green', 'yellow', or 'red'.
# • Write an if statement to test whether the alien’s color is green. If it is, print
# a message that the player just earned 5 points.
# • Write one version of this program that passes the if test and another that
# fails. (The version that fails will have no output.)
alien_color = "green"
if alien_color == "green":
print("You just earned 5 points!")
HELLO ADMIN
# Write an if-elif-else chain that determines a person’s
# stage of life. Set a value for the variable age, and then:
# • If the person is less than 2 years old, print a message that the person is
# a baby.
# • If the person is at least 2 years old but less than 4, print a message that
# the person is a toddler.
# • If the person is at least 4 years old but less than 13, print a message that
# the person is a kid.
# • If the person is at least 13 years old but less than 20, print a message that
# the person is a teenager.
# • If the person is at least 20 years old but less than 65, print a message that
# the person is an adult.
# • If the person is age 65 or older, print a message that the person is an
# elder.
age = 21
if age < 2:
print("You are a baby!")
elif age < 4:
print("You are a toddler!")
elif age < 13:
print("You are a kid!")
elif age < 21:
print("You are a teenager!")
elif age < 65:
print("You are an adult!")
else:
print("Ypu are an elder!")
NO USERS
# Make a list of five or more usernames, including the name
# 'admin'. Imagine you are writing code that will print a greeting to each user
# after they log in to a website. Loop through the list, and print a greeting to
# each user:
# • If the username is 'admin', print a special greeting, such as Hello admin,
# would you like to see a status report?
# • Otherwise, print a generic greeting, such as Hello Eric, thank you for logging in again.
usernames = ["Iustin", "razvan", "rares", "admin", "george"]
for username in usernames:
if username == "admin":
print("Hello admin,would you like to see a status report?")
else:
print("Hello " + username + ", thank you for log-ging in again.")
CHECKING USERNAMES
# Add an if test to hello_admin.py to make sure the list of users is
# not empty.
# • If the list is empty, print the message We need to find some users!
# • Remove all of the usernames from your list, and make sure the correct
# message is printed.
usernames = []
if usernames:
for username in usernames:
if username == "admin":
print("Hello admin,would you like to see a status report?")
else:
print("Hello " + username + ", thank you for log-ging in again.")
else:
print("We need to find some users!")
ORDINAL NUMBERS
# Do the following to create a program that simulates
# how websites ensure that everyone has a unique username.
# • Make a list of five or more usernames called current_users.
# • Make another list of five usernames called new_users. Make sure one or
# two of the new usernames are also in the current_users list.
# • Loop through the new_users list to see if each new username has already
# been used. If it has, print a message that the person will need to enter a
# new username. If a username has not been used, print a message saying
# that the username is available.
# • Make sure your comparison is case insensitive. If 'John' has been used,
# 'JOHN' should not be accepted
current_users = ["Iustin", "razvan", "rares", "admin", "george"]
new_users = ["iustin", "Alex", "Edi", "george", "Rambarn"]
for new_user in new_users:
available = True
for current_user in current_users:
if new_user.lower() == current_user.lower():
available = False
if available == False:
print("Sry, but the " + new_user + " username has already been used!")
else:
print("Hy! the " + new_user + " username is available!")
PERSON
# Ordinal numbers indicate their position in a list, such
# as 1st or 2nd. Most ordinal numbers end in th, except 1, 2, and 3.
# • Store the numbers 1 through 9 in a list.
# • Loop through the list.
# • Use an if-elif-else chain inside the loop to print the proper ordinal ending for each number. Your output should read "1st 2nd 3rd 4th 5th 6th
# 7th 8th 9th", and each result should be on a separate line
numbers = [value for value in range(1, 10)]
for number in numbers:
ordinal = str(number)
if number == 1:
ordinal += "st"
elif number == 2:
ordinal += "nd"
elif number == 3:
ordinal += "rd"
else:
ordinal += "th"
print(ordinal)
FAVORITE NUMBERS
# Use a dictionary to store information about a person you know.
# Store their first name, last name, age, and the city in which they live. You
# should have keys such as first_name, last_name, age, and city. Print each
# piece of information stored in your dictionary.
person = {
"first_name" : "Razvan",
"last_name" : "Cazacu",
"age" : 21,
"city" : "Nottingham"
}
print(person)
Rivers
# Use a dictionary to store people’s favorite numbers.
# Think of five names, and use them as keys in your dictionary. Think of a favorite
# number for each person, and store each as a value in your dictionary. Print
# each person’s name and their favorite number. For even more fun, poll a few
# friends and get some actual data for your program
favorite_numbers = {
"Razvan" : 1,
"Alex" : 5,
"Iustin" : 6,
"Noe" : 666,
"Petronel" : 7
}
print(favorite_numbers)
POLLING
# Make a dictionary containing three major rivers and the country
# each river runs through. One key-value pair might be 'nile': 'egypt'.
# • Use a loop to print a sentence about each river, such as The Nile runs
# through Egypt
rivers = {
"Amazon" : "Brazil",
"Nile" : "Egypt",
"Volga" : "Russian Federation"
}
for river, country in rivers.items():
print("The " + river + " runs through " + country)
PETS
# Make a list of people who should take the favorite languages poll. Include
# some names that are already in the dictionary and some that are not.
# • Loop through the list of people who should take the poll. If they have
# already taken the poll, print a message thanking them for responding.
# If they have not yet taken the poll, print a message inviting them to take
# the poll.
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
required_people = ["iustin", "razvan", "sarah", "edward"]
for required_person in required_people:
if required_person in favorite_languages.keys():
print("Thank you " + required_person + " for taking the poll!")
else:
print("Hy! " + required_person + " please take the poll!")
FAVORITE PLACES
# Make several dictionaries, where the name of each dictionary is the
# name of a pet. In each dictionary, include the kind of animal and the owner’s
# name. Store these dictionaries in a list called pets. Next, loop through your list
# and as you do print everything you know about each pet.
rex = {
"kind_of_animal" : "dog",
"owner_name" : "iustin"
}
garfield = {
"kind_of_animal" : "dog",
"owner_name" : "iustin"
}
pets = []
pets.append(rex)
pets.append(garfield)
for pet in pets:
print("Pet name : " + str(pet))
CITIES
# Make a dictionary called favorite_places. Think of three
# names to use as keys in the dictionary, and store one to three favorite places
# for each person. To make this exercise a bit more interesting, ask some friends
# to name a few of their favorite places. Loop through the dictionary, and print
# each person’s name and their favorite places.
favorite_places = {
"iustin" : ["Apple Park Cupertino", "NYC", "Hollywood Hills California"],
"razvan" : ["London", "Paris", "Chicago"],
"alex" : ["home", "school", "library"]
}
for name , favorite_places in favorite_places.items():
print(str(name) + " favorite places are " + str(favorite_places) )
RENTAL CAR
# Make a dictionary called cities. Use the names of three cities as
# keys in your dictionary. Create a dictionary of information about each city and
# include the country that the city is in, its approximate population, and one fact
# about that city. The keys for each city’s dictionary should be something like
# country, population, and fact. Print the name of each city and all of the information you have stored about it.
cities = {
'New York' : {
'country' : "USA",
'population': 19469232,
'fact' : "The New York Public Library houses over 50 million books"
},
'Oslo' : {
'country': "Norway",
'population': 1100868,
'fact': "The Nobel Peace Prize is awarded in Oslo"
},
'Cupertino' : {
'country': "USA",
'population': 56343,
'fact': "It is known for being the home of Apple Inc., currently headquartered at Apple Park."
}
}
for city, info in cities.items():
print("Info about " + city + " : ")
print("It is located in : " + info['country'])
print("Aprox. population : " + str(info['population']))
print("An interesting fact : " + info['fact'])
RESTAURANT SEATING
# Write a program that asks the user what kind of rental car they
# would like. Print a message about that car, such as “Let me see if I can find you
# a Subaru.
message = input("Tell me what kind of car you want : ")
part_of_message = 'an' if message[0].lower() == 'a' else 'a'
print("Let me see if I can find you " + part_of_message + " " + message )
MULTIPLES OF TEN
# Write a program that asks the user how many people
# are in their dinner group. If the answer is more than eight, print a message say-
# ing they’ll have to wait for a table. Otherwise, report that their table is ready.
nr_of_people = input("How many people are in your dinner group : ")
nr_of_people = int(nr_of_people)
if nr_of_people > 8:
print("Sry, but you have to wait for a table!")
else:
print("Hy! your table is ready!")
PIZZA TOPPINGS
# Ask the user for a number, and then report whether the
# number is a multiple of 10 or not.
number = input("Please tell me a number! ")
number = int(number)
if number % 10 == 0:
print("Your number is multiple of 10")
else:
print("Your number is not multiple of 10!")
MOVIE TICKETS
# Write a loop that prompts the user to enter a series of
# pizza toppings until they enter a 'quit' value. As they enter each topping,
# print a message saying you’ll add that topping to their pizza
message = "Please enter your favorite toppings for pizza!"
message += "\nEnter 'quit' to stop!\n"
topping = input(message)
while topping != "quit":
print("I added " + topping + " to your pizza!")
topping = input(message)
DELI
# A movie theater charges different ticket prices depending on
# a person’s age. If a person is under the age of 3, the ticket is free; if they are
# between 3 and 12, the ticket is $10; and if they are over age 12, the ticket is
# $15. Write a loop in which you ask users their age, and then tell them the cost
# of their movie ticket.
message = "Please enter your age!"
message += "\nEnter 'quit' to stop!\n"
age = input(message)
while age != "quit":
age = int(age)
if age <= 3:
print("You can enter for free!")
elif age <= 12:
print("You need to pay 10$!")
else:
print("You need to pay 15$!")
age = input(message)
NO PASTRAMI
# Make a list called sandwich_orders and fill it with the names of vari-
# ous sandwiches. Then make an empty list called finished_sandwiches. Loop
# through the list of sandwich orders and print a message for each order, such
# as I made your tuna sandwich. As each sandwich is made, move it to the list
# of finished sandwiches. After all the sandwiches have been made, print a
# message listing each sandwich that was made.
sandwich_orders = ["PASTRAMI SANDWICH", "AMERICAN CLUB SANDWICH",
"BEIRUT SANDWITCH"]
finished_sandwiches = []
while sandwich_orders:
current_sandwitch = sandwich_orders.pop()
print("I made your " + current_sandwitch)
finished_sandwiches.append(current_sandwitch)
for sandwitch in finished_sandwiches:
print(sandwitch + " is finished!")
DREAM VACATION
# Using the list sandwich_orders, make sure
# the sandwich 'pastrami' appears in the list at least three times. Add code
# near the beginning of your program to print a message saying the deli has
# run out of pastrami, and then use a while loop to remove all occurrences of
# 'pastrami' from sandwich_orders. Make sure no pastrami sandwiches end up
# in finished_sandwiches.
sandwich_orders = [ "PASTRAMI SANDWICH", "AMERICAN CLUB SANDWICH",
"PASTRAMI SANDWICH", "BEIRUT SANDWITCH",
"PASTRAMI SANDWICH"
]
print("Deli has run out of pastrami!")
while "PASTRAMI SANDWICH" in sandwich_orders:
sandwich_orders.remove("PASTRAMI SANDWICH")
finished_sandwiches = []
while sandwich_orders:
current_sandwitch = sandwich_orders.pop()
print("I made your " + current_sandwitch)
finished_sandwiches.append(current_sandwitch)
for sandwitch in finished_sandwiches:
print(sandwitch + " is finished!")
MESSAGE
# Write a program that polls users about their dream
# vacation. Write a prompt similar to If you could visit one place in the world,
# where would you go? Include a block of code that prints the results of the poll.
responses = {}
# Set a flag to indicate that the polling is active
polling_active = True
while polling_active:
# Prompt for the person's name and response
name = input("What is your name sir?\n")
response = input("If you could visit one place in the world, where would you go?\n")
# Store the response in the dictionary
responses[name] = response
# You want to let anyone else to take the poll?
repeat = input("Would you like to let anyone else to take the poll? (yes/no)\n")
if repeat == "no":
polling_active = False
# Polling is complete, show the results!
print("\n---Poll Results---")
for name, place in responses.items():
print(name + " would like to visit " + place)
FAVORITE BOOK
# Write a function called display_message() that prints one sentence
# telling everyone what you are learning about in this chapter.
# Call the function, and make sure the message displays correctly.
def display_message():
print("I am learning about functions!")
display_message()
T-SHIRT
# Write a function called favorite_book() that accepts one
# parameter, title.
# The function should print a message, such as One of my
# favorite books is Alice in Wonderland. Call the function, making sure to
# include a book title as an argument in the function call.
def favorite_book(title):
print("One of my favorite books is " + title)
favorite_book("Fram, The Polar Bear by Cezar Petrescu")
LARGE SHIRTS
# Write a function called make_shirt() that accepts a size and the
# text of a message that should be printed on the shirt.
# The function should print a sentence summarizing the size of the shirt
# and the message printed on it.
# Call the function once using positional arguments to make a shirt.
# Call the function a second time using keyword arguments.
def make_shirt(size, message):
print("Your shirt is of size " + size + " and the message " + message)
make_shirt('M', "RockStar")
make_shirt(size="XXL", message="Banana")
CITIES
# Modify the make_shirt() function so that shirts are large
# by default with a message that reads I love Python. Make a large shirt and a
# medium shirt with the default message, and a shirt of any size with a different
# message.
def make_shirt(size="L", message="I love Python"):
print("Your shirt is of size " + size + " and the message " + message)
make_shirt()
make_shirt("M")
make_shirt(size="XXL", message="Banana")
CITY NAMES
# Write a function called describe_city() that accepts the name of
# a city and its country. The function should print a simple sentence, such as
# Reykjavik is in Iceland. Give the parameter for the country a default value.
# Call your function for three different cities, at least one of which is not in the
# default country
def describe_city(city, country="USA"):
print(city.title() + " is in " + country.title())
describe_city("NYC")
describe_city("London", "UK")
describe_city("Brasov", "Romania")
ALBUM
# Write a function called city_country() that takes in the name
# of a city and its country. The function should return a string formatted like this:
# "Santiago, Chile"
# Call your function with at least three city-country pairs, and print the value
# that’s returned.
def city_country(city, country):
return city + ", " + country
print(city_country("NYC", "USA"))
print(city_country("Bangalore", "India"))
print(city_country("Rome", "Italy"))
USER ALBUMS
# Write a function called make_album() that builds a dictionary
# describing a music album. The function should take in an artist name and an
# album title, and it should return a dictionary containing these two pieces of
# information. Use the function to make three dictionaries representing different
# albums. Print each return value to show that the dictionaries are storing the
# album information correctly.
# Add an optional parameter to make_album() that allows you to store the
# number of tracks on an album. If the calling line includes a value for the number of tracks, add that value to the album’s dictionary. Make at least one new
# function call that includes the number of tracks on an album.
def make_album(artist_name, album_title, number_of_tracks=''):
if number_of_tracks:
return {"artist_name": artist_name, "album_title": album_title, "number_of_tracks" : number_of_tracks}
return {"artist_name": artist_name, "album_title": album_title}
print(make_album("Lil Pump", "Lil Pump", 9))
print(make_album("Lil Pump", "Harverd Dropout"))
print(make_album("Lil Pumo", "Lil Pump 2"))
MAGICIANS
# Start with your program from Exercise 8-7. Write a while
# loop that allows users to enter an album’s artist and title. Once you have that
# information, call make_album() with the user’s input and print the dictionary
# that’s created. Be sure to include a quit value in the while loop.
def make_album(artist_name, album_title, number_of_tracks=''):
if number_of_tracks:
return {"artist_name": artist_name, "album_title": album_title, "number_of_tracks" : number_of_tracks}
return {"artist_name": artist_name, "album_title": album_title}
print(make_album("Lil Pump", "Lil Pump", 9))
print(make_album("Lil Pump", "Harverd Dropout"))
print(make_album("Lil Pumo", "Lil Pump 2"))
while True:
artist_name = input("Please add an artist name!\n")
album_title = input("Please add the album title!\n")
print(make_album(artist_name=artist_name, album_title=album_title))
you_want_to_quit = input("Press 'quit' if you want to quit!\n")
if you_want_to_quit == 'quit':
break
GREAT MAGICIANS
# Make a list of magician’s names. Pass the list to a function
# called show_magicians(), which prints the name of each magician in the list.
magigians = ["David Blaine", "Harry Houdini", "Teller", "Penn Jillette"]
def show_magicians(magicians):
for magician in magicians:
print(magician)
show_magicians(magicians=magigians[:])
UNCHANGED MAGICIANS
# Start with a copy of your program from Exercise 8-9.
# Write a function called make_great() that modifies the list of magicians by
# adding the phrase the Great to each magician’s name. Call show_magicians() to
# see that the list has actually been modified.
magicians = ["David Blaine", "Harry Houdini", "Teller", "Penn Jillette"]
def show_magicians(magicians):
if magicians:
for magician in magicians:
print(magician)
show_magicians(magicians=magicians[:])
def make_great(magicians):
for i in range(0, len(magicians)):
magicians[i] = "the Great " + magicians[i]
make_great(magicians=magicians)
show_magicians(magicians=magicians)
SANDWITCHES
# Start with your work from Exercise 8-10. Call the
# function make_great() with a copy of the list of magicians’ names. Because the
# original list will be unchanged, return the new list and store it in a separate list.
# Call show_magicians() with each list to show that you have one list of the
# original names and one list with the Great added to each magician’s name.
magicians = ["David Blaine", "Harry Houdini", "Teller", "Penn Jillette"]
def show_magicians(magicians):
if magicians:
for magician in magicians:
print(magician)
show_magicians(magicians=magicians[:])
def make_great(magicians):
for i in range(0, len(magicians)):
magicians[i] = "Great " + magicians[i]
return magicians
great_magicians = make_great(magicians=magicians[:])
print("The original list: ")
show_magicians(magicians=magicians)
print("The modified list: ")
show_magicians(magicians=great_magicians)
USER PROFILE
# Write a function that accepts a list of items a person wants
# on a sandwich. The function should have one parameter that collects as many
# items as the function call provides, and it should print a summary of the
# sandwich that is being ordered. Call the function three times, using a different
# number of arguments each time.
def make_sandwitch(ingredients):
print("Your sandwitch will contain : ")
for ingredient in ingredients:
print(ingredient)
make_sandwitch(["sweet bread rolls", "cup mayonnaise", "cup prepared mustard",
"pound thinly sliced cooked ham", "pound thinly sliced fully cooked pork"])
make_sandwitch(["tablespoon butter, softened", "hot dog buns or kaiser rolls, split",
"lettuce leaves", "tablespoons mayonnaise","teaspoon fresh lime juice"])
CARS
# Start with a copy of user_profile.py from page 153. Build
# a profile of yourself by calling build_profile(), using your first and last names
# and three other key-value pairs that describe you.
def build_profile(first, last, **user_info):
"""Build a dictionary containing everything we know about a user."""
profile = {}
profile['first_name'] = first
profile['last_name'] = last
for key, value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile('IUSTIN', 'ISCIUC',
location='INTERNET',
field='INFORMATICS')
print(user_profile)
RESTAURANT
# Write a function that stores information about a car in a dictionary. The function should always receive a manufacturer and a model name. It
# should then accept an arbitrary number of keyword arguments. Call the function with the required information and two other name-value pairs, such as a
# color or an optional feature. Your function should work for a call like this one:
# car = make_car('subaru', 'outback', color='blue', tow_package=True)
# Print the dictionary that’s returned to make sure all the information was
# stored correctly
def make_car(manufacturer, model, **car_info):
"""Build a dictionary containing everything we know about a car."""
car = {}
car['manufacturer'] = manufacturer
car['model'] = model
for key, value in car_info.items():
car[key] = value
return car
car = make_car('AUDI', 'Q8',
color='WHITE',
tow_package=True)
print(car)
USERS
# Make a class called Restaurant. The __init__() method for
# Restaurant should store two attributes: a restaurant_name and a cuisine_type.
# Make a method called describe_restaurant() that prints these two pieces of
# information, and a method called open_restaurant() that prints a message indicating that the restaurant is open.
# Make an instance called restaurant from your class. Print the two attributes individually, and then call both methods.
class Restaurant():
"""A class to model a Restaurant"""
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
print("The restaurant is called : " + self.restaurant_name +
" and it offers " + self.cuisine_type)
def open_restaurant(self):
print("The restaurant is open!")
first_restaurant = Restaurant("Iustin's Pizza House", "Pizzeria")
print(first_restaurant.restaurant_name)
print(first_restaurant.cuisine_type)
first_restaurant.describe_restaurant()
first_restaurant.open_restaurant()
NUMBER SERVED
# Make a class called User. Create two attributes called first_name
# and last_name, and then create several other attributes that are typically stored
# in a user profile. Make a method called describe_user() that prints a summary
# of the user’s information. Make another method called greet_user() that prints
# a personalized greeting to the user.
# Create several instances representing different users, and call both methods
# for each user.
class User():
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
def describe_user(self):
print("The user is called " + self.first_name + " " + self.last_name)
def greet_user(self):
print("Hy! " + self.first_name + " " + self.last_name + " good to see you!")
first_user = User("Iustin", "Isciuc")
first_user.describe_user()
first_user.greet_user()
last_user = User("Razvan", "Cazacu")
last_user.describe_user()
last_user.greet_user()
LOGIN ATTEMPTS
# Start with your program from Exercise 9-1 (page 166).
# Add an attribute called number_served with a default value of 0. Create an
# instance called restaurant from this class. Print the number of customers the
# restaurant has served, and then change this value and print it again.
# Add a method called set_number_served() that lets you set the number
# of customers that have been served. Call this method with a new number and
# print the value again.
# Add a method called increment_number_served() that lets you increment
# the number of customers who’ve been served. Call this method with any number you like that could represent how many customers were served in, say, a
# day of business.
class Restaurant():
"""A class to model a Restaurant"""
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
print("The restaurant is called : " + self.restaurant_name +
" and it offers " + self.cuisine_type)
def open_restaurant(self):
print("The restaurant is open!")
def set_number_served(self, new_number):
self.number_served = new_number
def increment_number_served(self,increment_value):
self.set_number_served(self.number_served + increment_value)
first_restaurant = Restaurant("Iustin's Pizza House", "Pizzeria")
print(first_restaurant.restaurant_name)
print(first_restaurant.cuisine_type)
first_restaurant.describe_restaurant()
first_restaurant.open_restaurant()
print(first_restaurant.number_served)
first_restaurant.number_served = 10
print(first_restaurant.number_served)
first_restaurant.set_number_served(20)
print(first_restaurant.number_served)
first_restaurant.increment_number_served(10)
print(first_restaurant.number_served)
ICE CREAM STAND
# Add an attribute called login_attempts to your User
# class from Exercise 9-3 (page 166). Write a method called increment_
# login_attempts() that increments the value of login_attempts by 1. Write
# another method called reset_login_attempts() that resets the value of login_
# attempts to 0.
# Make an instance of the User class and call increment_login_attempts()
# several times. Print the value of login_attempts to make sure it was incremented
# properly, and then call reset_login_attempts(). Print login_attempts again to
# make sure it was reset to 0.
class User():
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
self.login_attempts = 0
def describe_user(self):
print("The user is called " + self.first_name + " " + self.last_name)
def greet_user(self):
print("Hy! " + self.first_name + " " + self.last_name + " good to see you!")
def increment_login_attempts(self):
self.login_attempts = self.login_attempts + 1
def reset_login_attempts(self):
self.login_attempts = 0
first_user = User("Iustin", "Isciuc")
first_user.describe_user()
first_user.greet_user()
last_user = User("Razvan", "Cazacu")
last_user.describe_user()
last_user.greet_user()
last_user.increment_login_attempts()
last_user.increment_login_attempts()
last_user.increment_login_attempts()
print(last_user.login_attempts)
last_user.reset_login_attempts()
print(last_user.login_attempts)
ADMIN
# An ice cream stand is a specific kind of restaurant. Write
# a class called IceCreamStand that inherits from the Restaurant class you wrote
# in Exercise 9-1 (page 166) or Exercise 9-4 (page 171). Either version of
# the class will work; just pick the one you like better. Add an attribute called
# flavors that stores a list of ice cream flavors. Write a method that displays
# these flavors. Create an instance of IceCreamStand, and call this method.
class Restaurant():
"""A class to model a Restaurant"""
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
print("The restaurant is called : " + self.restaurant_name +
" and it offers " + self.cuisine_type)
def open_restaurant(self):
print("The restaurant is open!")
def set_number_served(self, new_number):
self.number_served = new_number
def increment_number_served(self,increment_value):
self.set_number_served(self.number_served + increment_value)
first_restaurant = Restaurant("Iustin's Pizza House", "Pizzeria")
class IceCreamStand(Restaurant):
def __init__(self):
self.flavors = ["Neapolitan", "Cherry", "Rum Raisin", "Cookie Dough"]
def display_flavors(self):
print(self.flavors)
ice_cream_stand = IceCreamStand();
ice_cream_stand.display_flavors()
PRIVILEGES
# An administrator is a special kind of user. Write a class called
# Admin that inherits from the User class you wrote in Exercise 9-3 (page 166)
# or Exercise 9-5 (page 171). Add an attribute, privileges, that stores a list
# of strings like "can add post", "can delete post", "can ban user", and so on.
# Write a method called show_privileges() that lists the administrator’s set of
# privileges. Create an instance of Admin, and call your method.
class User():
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
self.login_attempts = 0
def describe_user(self):
print("The user is called " + self.first_name + " " + self.last_name)
def greet_user(self):
print("Hy! " + self.first_name + " " + self.last_name + " good to see you!")
def increment_login_attempts(self):
self.login_attempts = self.login_attempts + 1
def reset_login_attempts(self):
self.login_attempts = 0
first_user = User("Iustin", "Isciuc")
first_user.describe_user()
first_user.greet_user()
class Admin(User):
def __init__(self):
self.privileges = ["can add post", "can delete post", "can ban user"]
def show_privileges(self):
print(self.privileges)
admin = Admin()
admin.show_privileges()
BATTERY UPGRADE
# Write a separate Privileges class. The class should have one
# attribute, privileges, that stores a list of strings as described in Exercise 9-7.
# Move the show_privileges() method to this class. Make a Privileges instance
# as an attribute in the Admin class. Create a new instance of Admin and use your
# method to show its privileges.
class User():
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
self.login_attempts = 0
def describe_user(self):
print("The user is called " + self.first_name + " " + self.last_name)
def greet_user(self):
print("Hy! " + self.first_name + " " + self.last_name + " good to see you!")
def increment_login_attempts(self):
self.login_attempts = self.login_attempts + 1
def reset_login_attempts(self):
self.login_attempts = 0
first_user = User("Iustin", "Isciuc")
first_user.describe_user()
first_user.greet_user()
class Admin(User):
def __init__(self):
self.privilege = Privileges()
class Privileges(Admin):
def __init__(self):
self.privileges = ["can add post", "can delete post", "can ban user"]
def show_privileges(self):
print(self.privileges)
admin = Admin()
print(admin.privilege.show_privileges())
IMPORTED RESTAURANT
# Use the final version of electric_car.py from this section.
# Add a method to the Battery class called upgrade_battery(). This method
# should check the battery size and set the capacity to 85 if it isn’t already.
# Make an electric car with a default battery size, call get_range() once, and
# then call get_range() a second time after upgrading the battery. You should
# see an increase in the car’s range.
class Car():
"""A simple attempt to represent a car."""
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
self.odometer_reading += miles
class Battery():
"""A simple attempt to model a battery for an electric car."""
def __init__(self, battery_size=70):
"""Initialize the battery's attributes."""
self.battery_size = battery_size
def describe_battery(self):
"""Print a statement describing the battery size."""
print("This car has a " + str(self.battery_size) + "-kWh battery.")
def get_range(self):
"""Print a statement about the range this battery provides."""
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270
message = "This car can go approximately " + str(range)
message += " miles on a full charge."
print(message)
def upgrade_battery(self):
if self.battery_size != 85:
self.battery_size = 85
class ElectricCar(Car):
"""Represent aspects of a car, specific to electric vehicles."""
def __init__(self, make, model, year):
"""
Initialize attributes of the parent class.
Then initialize attributes specific to an electric car.
"""
super().__init__(make, model, year)
self.battery = Battery()
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.upgrade_battery()
my_tesla.battery.describe_battery()
restaurant.py
class Restaurant():
"""A class to model a Restaurant"""
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
print("The restaurant is called : " + self.restaurant_name +
" and it offers " + self.cuisine_type)
def open_restaurant(self):
print("The restaurant is open!")
def set_number_served(self, new_number):
self.number_served = new_number
def increment_number_served(self,increment_value):
self.set_number_served(self.number_served + increment_value)
test.py
# Using your latest Restaurant class, store it in a module. Make a separate
# file that imports Restaurant. Make a Restaurant instance,
# and call one of Restaurant’s methods to show that the import statement
# is working properly
import restaurant
new_restaurant = restaurant.Restaurant("Iustin's Pizzeria", "Pizza")
new_restaurant.describe_restaurant()
user.py
class User():
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
self.login_attempts = 0
def describe_user(self):
print("The user is called " + self.first_name + " " + self.last_name)
def greet_user(self):
print("Hy! " + self.first_name + " " + self.last_name + " good to see you!")
def increment_login_attempts(self):
self.login_attempts = self.login_attempts + 1
def reset_login_attempts(self):
self.login_attempts = 0
class Admin(User):
def __init__(self):
self.privilege = Privileges()
test.py
class Privileges(Admin):
def __init__(self):
self.privileges = ["can add post", "can delete post", "can ban user"]
def show_privileges(self):
print(self.privileges)
# Start with your work from Exercise 9-8 (page 178).
# Store the classes User, Privileges, and Admin in one module.
# Create a separate file, make an Admin instance, and call show_privileges()
# to show that everything is working correctly.
import user
admin = user.Admin()
print(admin.privilege.show_privileges())
DICE
user.py
class User():
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
self.login_attempts = 0
def describe_user(self):
print("The user is called " + self.first_name + " " + self.last_name)
def greet_user(self):
print("Hy! " + self.first_name + " " + self.last_name + " good to see you!")
def increment_login_attempts(self):
self.login_attempts = self.login_attempts + 1
def reset_login_attempts(self):
self.login_attempts = 0
admin.py
import user
class Admin(user.User):
def __init__(self):
self.privilege = Privileges()
class Privileges(Admin):
def __init__(self):
self.privileges = ["can add post", "can delete post", "can ban user"]
def show_privileges(self):
print(self.privileges)
test.py
# Store the User class in one module, and store the
# Privileges and Admin classes in a separate module. In a separate file, create
# an Admin instance and call show_privileges() to show that everything is still
# working correctly
import admin
admin = admin.Admin()
print(admin.privilege.show_privileges())
LEARNING PYTHON
# The module random contains functions that generate random numbers in a variety of ways.
# The function randint() returns an integer in the
# range you provide. The following code returns a number between 1 and 6:
# from random import randint
# x = randint(1, 6)
# Make a class Die with one attribute called sides, which has a default
# value of 6. Write a method called roll_die() that prints a random number
# between 1 and the number of sides the die has. Make a 6-sided die and roll
# it 10 times.
# Make a 10-sided die and a 20-sided die. Roll each die 10 times.
from random import randint
class Die:
def __init__(self, sides=6):
self.sides = sides
def roll_die(self):
print(randint(1, self.sides))
print("6 sides dice")
dice = Die()
dice.roll_die()
dice.roll_die()
dice.roll_die()
dice.roll_die()
dice.roll_die()
dice.roll_die()
dice.roll_die()
dice.roll_die()
dice.roll_die()
dice.roll_die()
print("10 sides dice")
dice = Die(10)
dice.roll_die()
dice.roll_die()
dice.roll_die()
dice.roll_die()
dice.roll_die()
dice.roll_die()
dice.roll_die()
dice.roll_die()
dice.roll_die()
dice.roll_die()
print("20 sides dice")
dice = Die(20)
dice.roll_die()
dice.roll_die()
dice.roll_die()
dice.roll_die()
dice.roll_die()
dice.roll_die()
dice.roll_die()
dice.roll_die()
dice.roll_die()
dice.roll_die()
LEARNING C
# Open a blank file in your text editor and write a few
# lines summarizing what you’ve learned about Python so far. Start each line
# with the phrase In Python you can.... Save the file as learning_python.txt in the
# same directory as your exercises from this chapter. Write a program that reads
# the file and prints what you wrote three times. Print the contents once by reading
# in the entire file, once by looping over the file object, and once by storing
# the lines in a list and then working with them outside the with block.
learning_python.txt
In Python you can store information in varables, lists, tuples
In Python you can create Classes
In Python you can create functions
test.py
filename = 'learning_python.txt'
print("Print the entire file!")
with open(filename) as file_object:
content = file_object.read()
print(content.rstrip())
print("Print by looping over the lines")
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
print("Print by storing the lines in a list!")
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
GUEST
# You can use the replace() method to replace any word in a
# string with a different word. Here’s a quick example showing how to replace
# 'dog' with 'cat' in a sentence:
# >>> message = "I really like dogs."
# >>> message.replace('dog', 'cat')
# 'I really like cats.'
# Read in each line from the file you just created, learning_python.txt, and
# replace the word Python with the name of another language, such as C. Print
# each modified line to the screen.
filename = 'learning_python.txt'
with open(filename) as file_object:
for line in file_object:
print(line.rstrip().replace("Python", "C"))
GUEST BOOK
# Write a program that prompts the user for their name. When they
# respond, write their name to a file called guest.txt.
name = input("Please tell me your name sir!\n")
with open('guest.txt', 'w') as file_object:
file_object.write(name)
PROGRAMMING POLL
# Write a while loop that prompts users for their name. When
# they enter their name, print a greeting to the screen and add a line recording
# their visit in a file called guest_book.txt. Make sure each entry appears on a
# new line in the file
while True :
name = input("Hy! tell me your name pls!\n")
print("Hello Mr. " + name)
with open("guest_book.txt", 'a') as file_object:
file_object.write("Mr. " + name + " has visited us!\n")
next_guest = input("There is somebody else? (yes/no)\n")
if next_guest == "no":
break;
ADDITION
# Write a while loop that asks people why they like
# programming. Each time someone enters a reason, add their reason to a file
# that stores all the responses.
while True :
reason = input("Hy! tell me why do you like programming!\n")
with open("reasons.txt", 'a') as file_object:
file_object.write(reason + "\n")
next_guest = input("You want to let somebody else to take the poll? (yes/no)\n")
if next_guest == "no":
break;
CATS AND DOGS:
# One common problem when prompting for numerical input
# occurs when people provide text instead of numbers. When you try to convert
# the input to an int, you’ll get a TypeError. Write a program that prompts for
# two numbers. Add them together and print the result. Catch the TypeError if
# either input value is not a number, and print a friendly error message. Test your
# program by entering two numbers and then by entering some text instead of a
# number.
print("Give me two numbers, and I'll add them.")
print("Enter 'q' to quit.")
while True:
first_number = input("\nFirst number: ")
if first_number == 'q':
break;
second_number = input("\nSecond number: ")
if second_number == 'q':
break;
try:
answer = int(first_number) + int(second_number)
except ValueError:
print("Please add only numbers, not text!")
else:
print(answer)
COMMON WORDS
# Make two files, cats.txt and dogs.txt. Store at least three
# names of cats in the first file and three names of dogs in the second file. Write
# a program that tries to read these files and print the contents of the file to the
# screen. Wrap your code in a try-except block to catch the FileNotFound error,
# and print a friendly message if a file is missing. Move one of the files to a different location on your system, and make sure the code in the except block
# executes properly.
filenames = ['/tre/cats.txt', 'dogs.txt']
for filename in filenames:
try:
with open(filename) as f_obj:
contents = f_obj.read()
print(contents)
except FileNotFoundError:
msg = "Sorry, the file " + filename + " does was not found."
print(msg)
FAVORITE NUMBER
# Visit Project Gutenberg (http://gutenberg.org/ )
# and find a few texts you’d like to analyze. Download the text files for these
# works, or copy the raw text from your browser into a text file on your
# computer.
# You can use the count() method to find out how many times a word or
# phrase appears in a string. For example, the following code counts the number
# of times 'row' appears in a string:
# >>> line = "Row, row, row your boat"
# >>> line.count('row')
# 2
# >>> line.lower().count('row')
# 3
# Notice that converting the string to lowercase using lower() catches
# all appearances of the word you’re looking for, regardless of how it’s
# formatted.
# Write a program that reads the files you found at Project Gutenberg and
# determines how many times the word 'the' appears in each text.
filename = './LETTERS-SENECA.html'
try:
with open(filename) as f_obj:
contents = f_obj.read()
print(contents.count('the'))
except FileNotFoundError:
msg = "Sorry, the file " + filename + " does was not found."
print(msg)
#I saved the Minor Dialogues, Together With the Dialogue on Clemency by Lucius Annaeus Seneca as ./LETTERS-SENECA.html
FAVORITE NUMBER REMEMBERED
# Write a program that prompts for the user’s favorite
# number. Use json.dump() to store this number in a file. Write a separate program that reads in this value and prints the message, “I know your favorite
# number! It’s _____.”
write_number.py
import json
favorite_number = input("What is your favorite number?\n")
filename = 'favorite_number.json'
with open(filename, 'w') as f_obj:
json.dump(favorite_number, f_obj)
print("I will remember that your favorite number is : " + favorite_number)
read_number.py
import json
filename = './favorite_number.json'
with open(filename) as f_obj:
favorite_number = json.load(f_obj)
print("Your favorite number is : " + favorite_number)
VERIFY USER
# Combine the two programs from
# Exercise 10-11 into one file. If the number is already stored, report the favorite
# number to the user. If not, prompt for the user’s favorite number and store it in a
# file. Run the program twice to see that it works.
import json
filename = 'favorite_number.json'
try:
with open(filename) as f_obj:
favorite_number = json.load(f_obj)
print("Your favorite number is : " + favorite_number)
except FileNotFoundError:
favorite_number = input("What is your favorite number\n");
with open(filename, 'w') as f_obj:
json.dump(favorite_number, f_obj)
print("We will remeber that your favorite number is : " + favorite_number)
CITY, COUNTRY
# The final listing for remember_me.py assumes either that the
# user has already entered their username or that the program is running for the
# first time. We should modify it in case the current user is not the person who
# last used the program.
# Before printing a welcome back message in greet_user(), ask the user if
# this is the correct username. If it’s not, call get_new_username() to get the correct
# username.
import json
def get_stored_username():
"""Get stored username if available."""
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
return None
else:
return username
def get_new_username():
"""Prompt for a new username."""
username = input("What is your name?\n")
filename = 'username.json'
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
return username
def greet_user():
"""Greet the user by name."""
username = get_stored_username()
if username:
last_username = input("Hy! the last username used is : " + username + " (yes/no)\n")
if last_username == 'no':
username = get_new_username()
print("We'll remember you when you come back, " + username + "!")
else:
print("Welcome back, " + username + "!")
else:
username = get_new_username()
print("We'll remember you when you come back, " + username + "!")
greet_user()
POPULATION
# Write a function that accepts two parameters: a city name
# and a country name. The function should return a single string of the form
# City, Country, such as Santiago, Chile. Store the function in a module called
# city_functions.py.
# Create a file called test_cities.py that tests the function you just wrote
# (remember that you need to import unittest and the function you want to test).
# Write a method called test_city_country() to verify that calling your function
# with values such as 'santiago' and 'chile' results in the correct string. Run
# test_cities.py, and make sure test_city_country() passes.
city_functions.py
def city_country(city, country):
return city + ", " + country
test_cities.py
import unittest
from city_functions import city_country
class NamesTestCase(unittest.TestCase):
"""Tests for 'city_functions.py'."""
def test_city_country(self):
city_country_var = city_country("Santiego", "Chile")
self.assertEqual(city_country_var, "Santiego, Chile")
unittest.main()
EMPLOYEE
# Modify your function so it requires a third parameter,
# population. It should now return a single string of the form City, Country –
# population xxx, such as Santiago, Chile – population 5000000. Run
# test_cities.py again. Make sure test_city_country() fails this time.
# Modify the function so the population parameter is optional. Run
# test_cities.py again, and make sure test_city_country() passes again.
# Write a second test called test_city_country_population() that verifies you can call your function with the values 'santiago', 'chile', and
# 'population=5000000'. Run test_cities.py again, and make sure this new test
# passes.
city_functions.py
def city_country(city, country, population=''):
if population:
return city + ", " + country + ' - ' + str(population)
return city + ", " + country
test_cities.py
import unittest
from city_functions import city_country
class NamesTestCase(unittest.TestCase):
"""Tests for 'city_functions.py'."""
def test_city_country(self):
city_country_var = city_country("Santiego", "Chile")
self.assertEqual(city_country_var, "Santiego, Chile")
def test_city_country_population(self):
city_country_population_var = city_country("Santiego", "Chile", 5000000)
self.assertEqual(city_country_population_var, "Santiego, Chile - 5000000")
unittest.main()
SORT DICTIONARIES
# Write a class called Employee. The __init__() method should
# take in a first name, a last name, and an annual salary, and store each of these
# as attributes. Write a method called give_raise() that adds $5000 to the
# annual salary by default but also accepts a different raise amount.
# Write a test case for Employee. Write two test methods, test_give_
# default_raise() and test_give_custom_raise(). Use the setUp() method so
# you don’t have to create a new employee instance in each test method. Run
# your test case, and make sure both tests pass.
employee.py
class Employee():
def __init__(self, first_name, last_name, annual_salary):
self.first_name = first_name
self.last_name = last_name
self.annual_salary = annual_salary
def give_raise(self, amount=''):
if amount:
self.annual_salary += amount
else:
self.annual_salary += 5000
test_employee.py
import unittest
from employee import Employee
class TestEmployee(unittest.TestCase):
def setUp(self):
self.myEmployee = Employee("Iustin","Isciuc", 120000)
def test_give_default_raise(self):
self.myEmployee.give_raise();
self.assertEqual(self.myEmployee.annual_salary, 125000)
def test_give_custom_raise(self):
self.myEmployee.give_raise(10000);
self.assertEqual( self.myEmployee.annual_salary, 130000)
unittest.main()
# How to sort a list based on values, but how to sort a list based on key lengths
programming_class = {'java':12, 'python':10, 'javascript': 7, 'C':11}
sorted_dict = {key: value for key, value in sorted(programming_class.items(), key=lambda item : item[1])}
print(sorted_dict)
sorted_dict = {key: value for key, value in sorted(programming_class.items(), key=lambda item : len(item[0]))}
print(sorted_dict)