Exercises for Lesson 1

Back to Lesson 1

Exercise 1: Hello, world!

For this exercise, predict the output and then execute each of the following commands in VS Code.

# 1a
print("Hello, world!")

# 1b
print("Hello", "world!")

# 1c
print("Hello")
print()
print("world!")

Exercise 2: Getting user input

In this exercise, you’ll practice using the input() function to ask the user for input.

Part a: getting multiple inputs

The prompt for input() is not necessary. For example, we can ask the user for multiple inputs.

print("Please type 4 numbers (ints or floats), hitting enter/return after each.")
num1 = input()
num2 = input()
num3 = input()
num4 = input()
print("Their product is:", float(num1) * float(num2) * float(num3) * float(num4))

What do you think will happen when this program runs? Predict the result and then type it up in VS Code to find out.

Part b: your first function

Type the following lines of code in VS Code and observe the output.

# 2a: Get user input
animal = input("What is your favorite type of animal? ")
print("Your favorite type of animal is:", animal)

# 2b: Write and use a function to congratulate the user
def congratulate(firstName):
    print("Congratulations,", firstName, ":)")

congratulate("Lulu")
congratulate("Hobbes")
congratulate(Milo) # what's different here?

Food for thought: How could you add punctuation after the name, without a space in between?

Back to Lesson 1

Exercise 3: Changing loop counts

For this exercise, you will modify a variant of the chaos program from Zelle chapter 1. Note that you should replace eval with float.

3a: Hard-coded count

Modify the chaos.py program so that it prints out 20 values instead of 10.

3b: User-inputted count

Modify the chaos.py program so that the number of values to print is determined by the user. You will have to add a line near the top of the program to get another value from the user:

n = int(input("How many numbers should I print? "))

Then you will need to change the loop to use n instead of a specific number.

Exercise 4: Representing numbers in computers

The calculation performed in the chaos.py program can be written in a number of ways that are algebraically equivalent. Write a version of the program that uses each of the following ways of doing the computation. Have your modified program print out 100 iterations of the calculation and compare the results when run on the same input.

a)   3.9 * x * (1-x)
b)   3.9 * (x - x * x)
c)   3.9 * x - 3.9 * x * x

Back to Lesson 1