Lesson 2 and 3
Lesson 2 and 3
Probably the most powerful thing about computers is that they can repeat things over and over
very quickly. There are several ways to repeat things in Python, the most common of which is
the for loop.
2.1 Examples
Example 1 The following program will print Hello ten times:
for i in range(10):
print('Hello')
The structure of a for loop is as follows:
for variable name in range( number of times to repeat ):
statements to be repeated
The syntax is important here. The word for must be in lowercase, the first line must end with
a colon, and the statements to be repeated must be indented. Indentation is used to tell Python
which statements will be repeated.
Example 2 The program below asks the user for a number and prints its square, then asks for
another number and prints its square, etc. It does this three times and then prints that the loop
is done.
for i in range(3):
num = eval(input('Enter a number: '))
print ('The square of your number is', num*num)
print('The loop is now done.')
Enter a number: 3
The square of your number is 9
Enter a number: 5
The square of your number is 25
Enter a number: 23
The square of your number is 529
The loop is now done.
Since the second and third lines are indented, Python knows that these are the statements to be
repeated. The fourth line is not indented, so it is not part of the loop and only gets executed
once, after the loop has completed.
Looking at the above example, we see where the term for loop comes from: we can picture
the execution of the code as starting at the for statement, proceeding to the second and third
lines, then looping back up to the for statement.
Example 3 The program below will print A, then B, then it will alternate C’s and D’s five
times and then finish with the letter E once.
print('A')
print('B')
for i in range(5):
print('C')
print('D')
print('E')
The first two print statements get executed once, printing an A followed by a B. Next, the C’s
and D’s alternate five times. Note that we don’t get five C’s followed by five D’s. The way
the loop works is we print a C, then a D, then loop back to the start of the loop and print a C
and another D, etc. Once the program is done looping with the C’s and D’s, it prints one E.
Example 4 If we wanted the above program to print five C’s followed by five D’s, instead of
alternating C’s and D’s, we could do the following:
print('A')
print('B')
for i in range(5):
print('C')
for i in range(5):
print('D')
print('E')
If we want the list of values to start at a value other than 0, we can do that by specifying the
starting value. The statement range(1,5) will produce the list 1, 2, 3, 4. This brings up one
quirk of the range function—it stops one short of where we think it should. If we wanted the
list to contain the numbers 1 through 5 (including 5), then we would have to do range(1,6).
Another thing we can do is to get the list of values to go up by more than one at a time. To do
this, we can specify an optional step as the third argument. The statement range(1,10,2) will
step through the list by twos, producing 1, 3, 5, 7, 9.
To get the list of values to go backwards, we can use a step of -1. For instance, range(5,1,-1)
will produce the values 5, 4, 3, 2, in that order. (Note that the range function stops one short
of the ending value 1). Here are a few more examples:
Statement Values generated
range(10) 0,1,2,3,4,5,6,7,8,9
range(1,10) 1,2,3,4,5,6,7,8,9
range(3,7) 3,4,5,6
range(2,15,3) 2,5,8,11,14
range(9,2,-1) 9,8,7,6,5,4,3
Here is an example program that counts down from 5 and then prints a message.
for i in range(5,0,-1):
print(i, end=' ')
print('Blast off!!')
5 4 3 2 1 Blast off!!!
The end=' ' just keeps everything on the same line.
2.5. EXERCISES
Suppose we want to make a triangle instead. We can accomplish this with a very small change
to the rectangle program. Looking at the program, we can see that the for loop will repeat the
print statement four times, making the shape four rows tall. It’s the 6 that will need to
change. The key is to change the 6 to i+1. Each time through the loop the program will now
print i+1 stars instead of 6 stars. The loop counter variable i runs through the values 0, 1, 2,
and 3. Using it allows us to vary the number of stars. Here is triangle program:
for i in range(4):
print('*'*(i+1))
2.5 Exercises
_______________________________________________________________
1. Write a program that prints your name 100 times.
2. Write a program to fill the screen horizontally and vertically with your name. [Hint: add
the option end='' into the print function to fill the screen horizontally.]
3. Write a program that outputs 100 lines, numbered 1 to 100, each with your name on it. The
output should look like the output below.
1 Your name
2 Your name
3 Your name
4 Your name
...
100 Your name
4. Write a program that prints out a list of the integers from 1 to 20 and their squares. The
output should look like this:
1 --- 1
2 --- 4
3 --- 9
...
20 --- 400
5. Write a program that uses a for loop to print the numbers 8, 11, 14, 17, 20, . . . , 83, 86, 89.
6. Write a program that uses a for loop to print the numbers 100, 98, 96, . . . , 4, 2.
7. Write a program that uses exactly four for loops to print the sequence of letters below.
AAAAAAAAAABBBBBBBCDCDCDCDEFFFFFFG
8. Write a program that asks the user for their name and how many times to print it. The
program should print out the user’s name the specified number of times.
9. The Fibonacci numbers are the sequence below, where the first two numbers are 1, and
each number thereafter is the sum of the two preceding numbers. Write a program that asks
the user how many Fibonacci numbers to print and then prints that many.
1, 1,2, 3,5, 8,13,21, 34,55, 89. .. 10. Use a for loop to print a box like the one below. Allow the
user to specify how wide and how high the box should be. [Hint: print('*'*10) prints ten
asterisks.]
11. Use a for loop to print a box like the one below. Allow the user to specify how wide and
how high the box should be.
12. Use a for loop to print a triangle like the one below. Allow the user to specify how high
the
triangle should be.
13. Use a for loop to print an upside down triangle like the one below. Allow the user to
specify
how high the triangle should be.
14. Use for loops to print a diamond like the one below. Allow the user to specify how high
the
diamond should be.
15. Write a program that prints a giant letter A like the one below. Allow the user to specify how
large the letter should be.
Lesson 3: Numbers
This lesson focuses on numbers and simple mathematics in Python.
Pi is roughly 3.14159265359
sin(0) = 0.0
Built-in math functions: There are two built in math functions, abs (absolute value) and
round that are available without importing the math module. Here are some examples:
print(abs(-4.3))
print(round(3.336, 2))
print(round(345.2, -1))
4.3
3.37
350.0
The round function takes two arguments: the first is the number to be rounded and the second
is the number of decimal places to round to. The second argument can be negative.
The second example here sums the numbers 1 + 1=4 + 1=9 + · · · + 1=100002. The result is
stored in the variable s. To inspect the value of that variable, just type its name and press
enter. Inspecting variables is useful for debugging your programs. If a program is not working
properly, you can type your variable names into the shell after the program has finished to see
what their values are.
The statement from math import* imports every function from the math module, which can
make the shell a lot like a scientific calculator.
Note Under the Shell menu, select Restart shell if you want to clear the values of all the
variables.
________________________________________________________________
3.8 Exercises
1. Write a program that generates and prints 50 random integers, each between 3 and 6.
2. Write a program that generates a random number, x, between 1 and 50, a random number
y
between 2 and 5, and computes x y.
3. Write a program that generates a random number between 1 and 10 and prints your name
that many times.
4. Write a program that generates a random decimal number between 1 and 10 with two
decimal places of accuracy. Examples are 1.23, 3.45, 9.80, and 5.00.
5. Write a program that generates 50 random numbers such that the first number is between 1
and 2, the second is between 1 and 3, the third is between 1 and 4, . . . , and the last is
between
1 and 51.
6. Write a program that asks the user to enter two numbers, x and y, and computes
(|x-y|)/(x +y)
7. Write a program that asks the user to enter an angle between -180◦ and 180◦. Using an
expression with the modulo operator, convert the angle to its equivalent between 0◦ and
360◦.
8. Write a program that asks the user for a number of seconds and prints out how many
minutes and seconds that is. For instance, 200 seconds is 3 minutes and 20 seconds. [Hint:
Use the // operator to get minutes and the % operator to get seconds.]
9. Write a program that asks the user for an hour between 1 and 12 and for how many hours
in
the future they want to go. Print out what the hour will be that many hours into the future.
An example is shown below.
10. (a) One way to find out the last digit of a number is to mod the number by 10. Write a
program that asks the user to enter a power. Then find the last digit of 2 raised to that
power.
(b) One way to find out the last two digits of a number is to mod the number by 100. Write
a program that asks the user to enter a power. Then find the last two digits of 2 raised to
that power.
(c) Write a program that asks the user to enter a power and how many digits they want.
Find the last that many digits of 2 raised to the power the user entered.
11. Write a program that asks the user to enter a weight in kilograms. The program should
convert it to pounds, printing the answer rounded to the nearest tenth of a pound.
12. Write a program that asks the user for a number and prints out the factorial of that
number.
13. Write a program that asks the user for a number and then prints out the sine, cosine, and
tangent of that number.
14. Write a program that asks the user to enter an angle in degrees and prints out the sine of
that
angle.
15. Write a program that prints out the sine and cosine of the angles ranging from 0 to 345◦
in
15◦ increments. Each result should be rounded to 4 decimal places. Sample output is shown
below:
19. Write a program that draws “modular rectangles” like the ones below. The user specifies
the width and height of the rectangle, and the entries start at 0 and increase typewriter
fashion
from left to right and top to bottom, but are all done mod 10. Below are examples of a 3 × 5
rectangle and a 4 × 8.