Topic 9. LOOPS IN PYTHON
Topic 9. LOOPS IN PYTHON
Computer Programming
Ryan Floyd M. Sarne
LOOPS
while
instruction
WHILE LOOP
SYNTAX:
while conditional_expression:
instruction_one
instruction_two
instruction_three LOOP’S BODY
:
instruction_n
WHILE LOOP – INFINITE LOOP
while True:
print("I'm stuck inside a loop.")
WHILE LOOP – Example 1
largest_number = -999999999
number = int(input("Enter a number or type -1 to stop: "))
counter = 5
while counter != 0:
print("Inside the loop.", counter)
counter -= 1
print("Outside the loop.", counter)
ACTIVITY - Scenario
secret_number = 777
print(
"""
+================================+
| Welcome to my game, muggle! |
| Enter an integer number |
| and guess what number I've |
| picked for you. |
| So, what is the secret number? |
+================================+
""")
LAB ACTIVITY on WHILE LOOP
1. Define the initial balance. Set an initial account balance (e.g., ₱5,000).
2. Run a while loop until the balance is depleted. As long as the balance is
greater than zero, allow withdrawals.
3. Prompt the user for a withdrawal amount. Ask the user how much they
want to withdraw.
4. Check if the withdrawal amount is valid. If the withdrawal amount is
greater than the balance → Show an “Insufficient funds” message.
Otherwise, deduct the amount from the balance.
5. Display the updated balance. After each successful withdrawal, print the
remaining balance.
6. End the program when balance reaches zero. Once the balance is ₱0,
print “No more funds available.” and exit the loop.
FOR LOOP
i=100
while i<100:
#do something
i+=1
FOR LOOP
i=0
while i<100:
#do something
i+=1
FOR LOOP any variable after the for keyword is
the control variable of the loop; it
counts the loop's turns, and does it
automatically;
for i in range(10):
print("The value of i is currently", i)
FOR LOOP
for i in range(10):
if i % 2:
print(“My Turn”)
FOR LOOP
Note:
the range() function accepts
only integers as its arguments,
and generates sequences of
integers.
FOR LOOP
power = 1
for expo in range(16):
print("2 to the power of", expo, "is", power)
power *= 2
FOR LOOP
for x in word:
use string.upper() to convert
print(x)
the word entered by the user to
upper case; we'll talk about
for i in word: string methods and the upper()
print(i, end="") method very soon
BREAK AND CONTINUE STATEMENTS
while True:
number = int(input("Enter a number or type -1 to end the program: "))
if number == -1:
break
counter += 1
if number > largest_number:
largest_number = number
if counter != 0:
print("The largest number is", largest_number)
else:
print("You haven't entered any number.")
ASSIGNMENT ON FOR LOOP
Write it on ¼ sheet of paper.
Your task here is very special: you must design a vowel eater! Write a program that uses:
1. a for loop;
2. the concept of conditional execution (if-elif-else)
3. the continue statement.
Your program must:
SAMPLE OUTPUTS: