Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Exercise Solutions

All of the exercise solutions are below.

Chapter 1

Exercise: Print Values

Task 1

name = "John"
age = 20
is_student = True

Task 2

print("Name:", name)
print("Age:", age)
print("Is Student:", is_student)

Exercise: Input User Information


name = input("Enter your name: ")
age = input("Enter your age: ")

print("Hello", name)
print("I see that you are", age, "years old!")

Exercise: Using Operators


num1 = input("Enter your first number: ")
num1 = int(num1)
num2 = input("Enter your second number: ")
num2 = int(num2)
print(num1, "+", num2, "=", num1+num2)
print(num1, "-", num2, "=", num1-num2)
print(num1, "*", num2, "=", num1*num2)
print(num1, "/", num2, "=", num1/num2)
print(num1, "//", num2, "=", num1//num2)
print(num1, "**", num2, "=", num1**num2)
print(num1, "%", num2, "=", num1%num2)

Project 1 Code

Initial inputs

name = input("Enter a name: ")
place = input("Enter a place: ")
time = input("Enter a time: ")

Initial story

story = f"{name} went to {place} at {time}"

Secondary inputs

duration = input("Enter a duration: ")
food = input("Enter some food: ")
pronoun = input("Enter the pronoun of the person: ")
second_name = input("Enter the name of a second person: ")

Updated Story

story = f"{name} went to {place} at {time}. It took {name} {duration} to get there. {pronoun} went to {place} since {second_name}'s birthday was coming up. They wanted to eat some {food} together."

Seeing the state of our story

print(story)

Final code

name = input("Enter a name: ")
place = input("Enter a place: ")
time = input("Enter a time: ")
duration = input("Enter a duration: ")
food = input("Enter some food: ")
pronoun = input("Enter the pronoun of the person: ")
second_name = input("Enter the name of a second person: ")
age = int(input("Enter the age of the second person: "))
quantity = int(input("Enter how much of the previously mentioned food was bought: "))
cost = float(input("Cost of previous food: "))
budget = float(input("Enter their original budget: "))

story = f"{name} went to {place} at {time}. It took {name} {duration} to get there. {pronoun} went to {place} since {second_name}'s birthday was coming up. They wanted to eat some {food} together. {second_name} is turning {age+1} years old! They bought {quantity} of {food}, which cost them ${cost}. They had a collective budget of ${budget}, which left them with ${budget-cost} afterwards."

print(story)