Repetition Structures Python
Repetition Structures Python
Repetition Structures Python
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
previous
statement
Looping
statements
(body of the loop)
next
statement after
the loop
Structure of condition-controlled
loop
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.
var=input();
while(var!=sentinel:
statement
statement
etc.
:
:
:
Var=input()
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
Examples:
for num in range(5):
print(num) #display 0 to 4
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])
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 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.
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