0% found this document useful (0 votes)
137 views12 pages

Repetition Structures Python

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 12

Please visit the following sites for additional discussion on

loops
https://www.w3schools.com/python/python_while_loops.asp
https://www.learnpython.org/en/Loops
https://www.tutorialspoint.com/python/python_for_loop.htm

LOOPING STATEMENTS
Loop – a part of a program that repeats
Loop body – contains the statements to be repeated

In writing a program it is always important to develop its algorithm first. Once


you have your algorithm, ask yourself these questions to determine if a loop is
required in your program.
a. Were there any steps repeated as I solved the problem? If so, which ones?
b. If the answer to number 1 is yes, did I know in advance how many times to
repeat the steps?
c. If the answer is no in question number 2, how did I know how long to keep
repeating the steps?

2 Broad Categories of Loops


1. Conditioned-controlled loop – uses a true/false condition to control the
number of times that it repeats(while statement)
2. Counter-controlled loop- repeats a specific number of times(for statement)
The logic of a pre-test loop

previous
statement

Looping
statements
(body of the loop)

next
statement after
the loop

In Python, there is a short, specific list


of false values:
• An empty string, “ “, is false
• The number 0 is false.
• An empty list, (), is false.
• The singleton None (i.e. no value) is
false.
Everything else is true.
4 ELEMENTS OF A CONDITIONED-CONTROLLED LOOP
The following elements should be present
in your looping statement:
a. looping statement – while, for, and do
while
b. the condition
c. initializing statement – placed before
the condition to ensure correct loop
execution the first time the condition is
evaluated
d. statement that allows the condition to
become false (ex. counter++, counter)

Structure of condition-controlled
loop

Initialize loop control variable


while condition
statements to be repeated here
:
:
Update the loop control variable
The while statement:
General format:
while condition:
statement
statement
etc.
else: //optional
statement

Using else Statement with Loops Python


supports having an else statement associated
with a loop statement.
If the else statement is used with a for
loop, the else statement is executed when
the loop has exhausted iterating the list.

If the else statement is used with a while


loop, the else statement is executed when
the condition becomes false.

1.A program that computes the average of a set of


quizzes. It lets the user decide how many
quizzes.

2.write a while statement to compute the product


of all numbers divisible by 3 between a and b
where a > b (a and b are inputs)Display also all
numbers divisible by 3

SENTINELS
Data values used to signal either the
start or end of a data series. The sentinel
value must be selected so as not to conflict
with legitimate data values. The sentinel is
not part of the data series.

Format of a sentinel-controlled loop:

var=input();
while(var!=sentinel:
statement
statement
etc.
:
:
:
Var=input()

Problem : A program that ask the user to enter a


series of numbers (use 0 to stop the series)
After all the numbers have been entered, the
program should display the smallest and the
greatest number of the series.

for Loop
-for statement in Python has the ability to iterate over the items
of any sequence, such as a list or a string.

General Format:
for variable in [value1, value2,etc]:
statement
statement
etc.
else: # optional
statement

The range() function


-the built-in function range() is the right function to iterate over a
sequence of numbers.
- It generates an iterator of arithmetic progressions
- generates integers starting with 0 up to n-1

Examples:
for num in range(5):
print(num) #display 0 to 4

for num in range(1,5): #display 1 to 5


print(num)

for num in range(5): #display UST 5 times(vertically)


print("UST")

for num in range(5): #display UST 5 times(horizontally


print("UST", end=' ')

for x in range(1,9,2): #display 1 3 5 7


print(x,end=' ')
for x in [2,7,8,9]: #display 2 7 8 9
print(x, end=' ')

for x in ["jose","abad","santos"]:
print(x, end=' ')

for x in "hello":
print(x, end='')

str="hello"
for x in range(len(str)):
print("Current letter : ", str[x])

fruits = ['banana', 'apple', 'mango']


for index in range(len(fruits)):
print ('Current fruit :', fruits[index])

Exercise :
1. Write a for loop that will display a table showing the numbers 1
through 10 and their squares

2. Write a Python program to convert Celsius degrees to Fahrenheit.


The program should request the starting Celsius value, the number
of conversions to be made, and the increment between Celsius
values. The display should have appropriate heading and list the
Celsius value and the corresponding Fahrenheit value. Use the
relationship F = (9/5)*C + 32. Use for loop. Round-off results to 2
decimal places.
Break and Continue Statements in a loop
break – forces an immediate break or exit
from while, for, and do
while statements
continue – when continue is encountered in a
loop, the next iteration of the loop will
immediately begin
Practice Problems:
1. Write a Python program to process a data file containing a collection of daily
high temperatures. Your program should count and print the number of hot days
(temperature 85 or higher), the number of pleasant days (temperature 60-84), and
the number of cold days (temperatures less than 60). The program should also
display the category of each temperature. (let 0 be the sentinel value).

2.Write a Python program that determines the number of digits in a given integer
by repeatedly removing the least significant digit until the number becomes 0.
(hint: use division and modulo division)

3.Write a Python program that asks the user to enter an integer n. The program
determines and displays the greatest power of 2 that is less than or equal to n.
4. Write a Python program to compute the sum of all integers both divisible by 3
and 4 from x to y where x and y are user inputs. Your code prompts the user to
enter new values for x and y if x >y.

5. The x and y coordinates, as a function of time, t, of a projectile fired with an


initial velocity, v, at an angle of theta, Ѳ, with respect to the ground, are given by
these formulas:
x = vt cos Ѳ y = vt sin Ѳ
using this formula, write a Python program that displays a table of x and y values
for a projectile fired with an initial velocity v (ft/sec) at an angle Ѳ. The table
should contain values corresponding to the time interval 0 to 5 seconds in
increment of 0.5 second
*input validation: v > 0, Ѳ is from 0 to 90 degrees
*your program should execute for as long as the user wants to continue
*round-off results to 2 decimal places
Filename: projectile

6. Write a program that will produce a table of x and y values for the given
function
y = 3x5 – 2x3 + x; x is from a to b in increments of 0.2
*input validation: a < b
*your program should execute for as long as the user wants to continue
*round-off results to 2 decimal places

7. There are 9870 people in a town whose population increases by ten percent
each year. Write a loop that prints the annual population and determines how
many years it will take for the population to go over 30,000.
Filename: population

You might also like