Lab # 4
Lab # 4
Lab # 4
Lab-04
Loops in python
Objectives:
The purpose of this lab is to get you familiar with the loops (for, while) and loop
controlling statements in Python
Apparatus:
Hardware Requirement
Personal computer.
Software Requirement
Anaconda, Jupyter Notebook/ Spyder
Theory:
In general, statements are executed sequentially − the first statement in a function
is executed first, followed by the second, and so on. There may be a situation when you need to
execute a block of code several number of times. Programming languages provide various
control structures that allow more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple
times. The following diagram illustrates a loop statement −
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.
The for statement in Python has the ability to iterate over the items of any
sequence, such as a list or a string.
Syntax
The structure of a for loop is as follows:
for variable_name in sequence:
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.
If a sequence contains an expression list, it is evaluated first. Then, the first item in
the sequence is assigned to the iterating variable variable_name. Next, the statements block is
executed. Each item in the list is assigned to variable_name, and the statement(s) block is
executed until the entire sequence is exhausted.
Flow Diagram
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.
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:
Names There’s nothing too special about the name i for our variable. The programs below will
have the exact same result.
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.
Examples
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.
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.
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 loopworks 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:
Example 5 A program that counts down from 5 and then prints a message.
Example 6 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.
The rectangle produced by this code is shown below on the left. The code '*'*6 just
repeats the asterisk character six times.
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:
While loops
We have already learned about for loops, which allow us to repeat things a
specified number of times. Sometimes, though, we need to repeat something, but we don’t know
ahead of time exactly how many times it has to be repeated. For instance, a game of Tic-tac-toe
keeps going until someone wins or there are no more moves to be made, so the number of turns
will vary from game to game. This is a situation that would call for a while loop.
A while loop statement in Python programming language repeatedly executes a
target statement as long as a given condition is true.
Syntax
The syntax of a while loop in Python programming language is −
while expression:
statement(s)
Here, statement(s) may be a single statement or a block of statements with uniform
indent. The condition may be any expression, and true is any non-zero value. The loop iterates
while the condition is true. When the condition becomes false, program control passes to the line
immediately following the loop.
In Python, all the statements indented by the same number of character spaces after
a programming construct are considered to be part of a single block of code. Python uses
indentation as its method of grouping statements.
Flow Diagram
Here, a key point of the while loop is that the loop might not ever run. When the
condition is tested and the result is false, the loop body will be skipped and the first statement
after the while loop will be executed.
Examples
Example 7: To convert the temperature repeatedly until the temperature is -1000
Look at the while statement first. It says that we will keep looping, that is, keep
getting and converting temperatures, as long as the temperature entered is not -1000. As soon as
-1000 is entered, the while loop stops. Tracing through, the program first compares temp to
-1000. If temp is not -1000, then the program asks for a temperature and converts it. The
program then loops back up and again compares temp to -1000. If temp is not -1000, the
program will ask for another temperature, convert it, and then loop back up again and do another
comparison. It continues this process until the user enters -1000.
We need the line temp=0 at the start, as without it, we would get a name error. The
program would get to the while statement, try to see if temp is not equal to -1000 and run into a
problem because temp doesn’t yet exist. To take care of this, we just declare temp equal to 0.
There is nothing special about the value 0 here. We could set it to anything except -1000.
(Setting it to -1000 would cause the condition on the while loop to be false right from the start
and the loop would never run.)
Note that is natural to think of the while loop as continuing looping until the user
enters -1000. However, when we construct the condition, instead of thinking about when to stop
looping, we instead need to think in terms of what has to be true in order to keep going.
A while loop is a lot like an if statement. The difference is that the indented
statements in an if block will only be executed once, whereas the indented statements in a while
loop are repeatedly executed.
Example 8: One problem with the previous program is that when the user enters in -1000 to quit,
the program still converts the value -1000 and doesn’t give any message to indicate that the
program has ended. A nicer way to do the program is shown below
Infinite loops
When working with while loops, sooner or later you will accidentally send Python
into a never ending loop. Here is an example:
In this program, the value of i never changes and so the condition i<10 is always true. Python
will continuously print zeroes. To stop a program caught in a never-ending loop, use Restart
Shell under the Shell menu. You can use this to stop a Python program before it is finished
executing.
Sometimes a never-ending loop is what you want. A simple way to create one is
shown below:
while True:
# statements to be repeated go here
The value True is called a boolean value and
Syntax
The syntax for a break statement in Python is as follows −
break
Flow Diagram
Example 9 Here is a program that allows the user to enter up to 10 numbers. The user can stop
early by entering a negative number.
Either method is ok. In many cases the break statement can help make your code
easier to understand and less clumsy.
Syntax
Continue
Flow Diagram
Example 10
Example 11
pass Statement
It is used when a statement is required syntactically but you do not want any
command or code to execute.
The pass statement is a null operation; nothing happens when it executes.
The pass statement is also useful in places where your code will eventually go, but has not been
written yet i.e. in stubs.
Syntax
pass
Example 12
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. 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.
10. The code below prints the numbers from 1 to 50. Rewrite the code using a while loop to
accomplish the same thing.
for i in range(1,51):
print(i)
11. Write a program that uses a while loop (not a for loop) to read through a string and print
the characters of the string one-by-one on separate lines.
12. Modify the program above to print out every second character of the string.
13. A good program will make sure that the data its users enter is valid. Write a program that
asks the user for a weight and converts it from kilograms to pounds. Whenever the user
enters a weight below 0, the program should tell them that their entry is invalid and then
ask them again to enter a weight. [Hint: Use a while loop, not an if statement].