Exercises for Lesson 1
Exercise 1: Hello, world!
For this exercise, predict the output and then type each of the following commands in IDLE.
>>> print("Hello, world!")
>>> print("Hello", "world!")
Exercise 2: Getting user input
In this exercise, you’ll practice using the input()
function to ask the user for input. Type each of the following commands in IDLE and observe the output.
>>> animal = input("What is your favorite type of animal? ")
>>> print("Your favorite type of animal is:", animal)
>>> def congratulate(firstName):
print("Congratulations,", firstName, ":)")
>>> congratulate("Colin")
>>> congratulate("Therese")
>>> congratulate(Sadie)
Exercise 3: Changing loop counts
For this exercise, you will modify the chaos
program from Zelle chapter 1. Note that I’ve replaced eval
with float
.
# File: chaos.py
# A simple program illustrating chaotic behavior.
def main():
print("This program illustrates a chaotic function")
x = float(input("Enter a number between 0 and 1: "))
for i in range(10):
x = 3.9 * x * (1 - x)
print(x)
main()
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