0% found this document useful (0 votes)
100 views10 pages

Lesson 2 and 3

For loops allow programmers to repeat blocks of code. The document provides examples of using for loops to print strings multiple times, ask users for input and print output within loops, and control the number of loop iterations using the range function. Key aspects of for loops covered include the loop variable, range function syntax, and using indentation to identify the block of code to repeat. Exercises are provided to have readers practice different for loop applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
100 views10 pages

Lesson 2 and 3

For loops allow programmers to repeat blocks of code. The document provides examples of using for loops to print strings multiple times, ask users for input and print output within loops, and control the number of loop iterations using the range function. Key aspects of for loops covered include the loop variable, range function syntax, and using indentation to identify the block of code to repeat. Exercises are provided to have readers practice different for loop applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Lesson 2: For loops

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')

2.2. THE LOOP VARIABLE


There is one part of a for loop that is a little tricky, and that is the loop variable. In the
example below, the loop variable is the variable i. The output of this program will be the
numbers 0, 1, . . . , 99, each printed on its own line.
for i in range(100):
print(i)
When the loop first starts, Python sets the variable i to 0. Each time we loop back up, Python
increases the value of i by 1. The program loops 100 times, each time increasing the value of i
by 1, until we have looped 100 times. At this point the value of i is 99.
You may be wondering why i starts with 0 instead of 1. Well, there doesn’t seem to be any
really good reason why other than that starting at 0 was useful in the early days of computing
and it has stuck with us. In fact most things in computer programming start at 0 instead of 1.
This does take some getting used to. Since the loop variable, i, gets increased by 1 each time
through the loop, it can be used to keep track of where we are in the looping process.
Consider the example below:
for i in range(3):
print(i+1, '-- Hello')
1 -- Hello
2 -- Hello
3 -- Hello
Names There’s nothing too special about the name i for our variable. The programs below
will have the exact same result.
for i in range(100): for wacky_name in range(100):
print(i) print(wacky_name)
It’s a convention in programming to use the letters i, j, and k for loop variables, unless there’s
a good reason to give the variable a more descriptive name.

2.3 The range function


The value we put in the range function determines how many times we will loop. The way
range works is it produces a list of numbers from zero to the value minus one. For instance,
range(5) produces five values: 0, 1, 2, 3, and 4.

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.4 A Trickier Example


Let’s look at a problem where we will make use of the loop variable. The program below
prints a rectangle of stars that is 4 rows tall and 6 rows wide.
for i in range(4):
print('*'*6)
The rectangle produced by this code is shown below on the left. The code '*'*6 is something
we’ll cover in Section 6.2; it just repeats the asterisk character six times.
****** *
****** **
****** ***
****** ****

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.

3.1 Integers and Decimal Numbers


Because of the way computer chips are designed, integers and decimal numbers are
represented differently on computers. Decimal numbers are represented by what are called
floating point numbers. The important thing to remember about them is you typically only
get about 15 or so digits of precision. It would be nice if there were no limit to the precision,
but calculations run a lot more quickly if you cut off the numbers at some point.
On the other hand, integers in Python have no restrictions. They can be arbitrarily large.
For decimal numbers, the last digit is sometimes slightly off due to the fact that computers
work in binary (base 2) whereas our human number system is base 10. As an example,
mathematically, we know that the decimal expansion of 7/3 is 2.333 · · ·, with the threes
repeating forever. But when we type 7/3 into the Python shell, we get 2.3333333333333335.
This is called roundoff error. For most practical purposes this is not too big of a deal, but it
actually can cause problems for some mathematical and scientific calculations. If you really
need more precision, there are ways as we will see later

3.2 Math Operators


Here is a list of the common operators in Python:
Exponentiation Python uses ** for exponentiation. The caret, ^, is used for something else.
Integer division The integer division operator, //, requires some explanation. Basically, for
positive numbers it behaves like ordinary division except that it throws away the decimal part
of the result. For instance, while 8/5 is 1.6, we have 8//5 equal to 1. We will see uses for this
operator later. Note that in many other programming languages and in older versions of
Python, the usual division operator / actually does integer division on integers.
Modulo The modulo operator, %, returns the remainder from a division. For instance, the
result of 18%7 is 4 because 4 is the remainder when 18 is divided by 7. This operation is
surprisingly useful. For instance, a number is divisible by n precisely when it leaves a
remainder of 0 when divided by n. Thus to check if a number, n, is even, see if n%2 is equal
to 0. To check if n is divisible by 3, see if n%3 is 0.
One use of this is if you want to schedule something in a loop to happen only every other time
through the loop, you could check to see if the loop variable modulo 2 is equal to 0, and if it
is, then do that something. The modulo operator shows up surprisingly often in formulas. If
you need to “wrap around” and come back to the start, the modulo is useful. For example,
think of a clock. If you go six hours past 8 o’clock, the result is 2 o’clock. Mathematically,
this can be accomplished by doing a modulo by 12. That is, (8+6)%12 is equal to 2. As
another example, take a game with players 1 through 5. Say you have a variable player that
keeps track of the current player. After player 5 goes, it’s player 1’s turn again. The modulo
operator can be used to take care of this: player = player%5+1
When player is 5, player%5 will be 0 and expression will set player to 1.
3.3. ORDER OF OPERATIONS 21

3.3 Order of operations


Exponentiation gets done first, followed by multiplication and division (including // and %),
and addition and subtraction come last. The classic math class mnemonic, PEMDAS (Please
Excuse My Dear Aunt Sally), might be helpful.
This comes into play in calculating an average. Say you have three variables x, y, and z, and
you want to calculate the average of their values. The expression x+y+z/3 would not work.
Because division comes before addition, you would actually be calculating x + y + 3z instead
of x+3y+z. This is easily fixed by using parentheses: (x+y+z)/3. In general, if you’re not sure
about something, adding parentheses might help and usually doesn’t do any harm.

3.4 Random numbers


To make an interesting computer game, it’s good to introduce some randomness into it.
Python comes with a module, called random, that allows us to use random numbers in our
programs. Before we get to random numbers, we should first explain what a module is. The
core part of the Python language consists of things like for loops, if statements, math
operators, and some functions, like print and input. Everything else is contained in modules,
and if we want to use something from a module we have to first import it—that is, tell Python
that we want to use it. At this point, there is only one function, called randint, that we will
need from the random module. To load this function, we use the following statement: from
random import randint. Using randint is simple:
randint(a,b) will return a random integer between a and b including both a and b. (Note that
randint includes the right endpoint b unlike the range function). Here is a short example:
from random import randint
x = randint(1,10)
print('A random number between 1 and 10: ', x)
A random number between 1 and 10: 7
The random number will be different every time we run the program.

3.5 Math functions


The math module Python has a module called math that contains familiar math functions,
including sin, cos, tan, exp, log, log10, factorial, sqrt, floor, and ceil. There are also the
inverse trig functions, hyperbolic functions, and the constants pi and e. Here is a short
example:
from math import sin, pi
print('Pi is roughly', pi)
print('sin(0) =', sin(0))

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.

3.6 Getting help from Python


There is documentation built into Python. To get help on the math module, for example, go to
the Python shell and type the following two lines:
This gives a list of all the functions and variables in the math module. You can ignore all of
the ones that start with underscores. To get help on a specific function, say the floor function,
you can type help(math.floor). Typing help(math) will give you help for everything in the
math module.

3.7 Using the Shell as a Calculator


The Python shell can be used as a very handy and powerful calculator. Here is an example
session:

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.

You might also like