[go: up one dir, main page]

0% found this document useful (0 votes)
8 views40 pages

Topic 9. LOOPS IN PYTHON

The document provides an overview of loops in Python, focusing on 'while' and 'for' loops, including their syntax and examples. It explains infinite loops, how to implement user input scenarios, and introduces break and continue statements. Additionally, it includes activities and assignments to reinforce understanding of loop concepts.

Uploaded by

ranseldulagan
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)
8 views40 pages

Topic 9. LOOPS IN PYTHON

The document provides an overview of loops in Python, focusing on 'while' and 'for' loops, including their syntax and examples. It explains infinite loops, how to implement user input scenarios, and introduces break and continue statements. Additionally, it includes activities and assignments to reinforce understanding of loop concepts.

Uploaded by

ranseldulagan
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/ 40

LOOPS IN PYTHON

Computer Programming
Ryan Floyd M. Sarne
LOOPS

• Loops are used in programming to execute a block of code


multiple times. Python provides two primary loop types: for loops
and while loops.
LOOPS
WHILE LOOP

while there is something to do


do it
WHILE LOOP

while
instruction
WHILE LOOP

SYNTAX:

while conditional_expression:
instruction_one
instruction_two
instruction_three LOOP’S BODY
:
instruction_n
WHILE LOOP – INFINITE LOOP

An infinite loop, also called an endless


loop, is a sequence of instructions in a
program which repeat indefinitely
(loop endlessly.)
WHILE LOOP – INFINITE LOOP

An infinite loop, also called an endless


loop, is a sequence of instructions in a
program which repeat indefinitely
(loop endlessly.)
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: "))

while number != -1:


if number > largest_number:
largest_number = number
number = int(input("Enter a number or type -1 to stop: "))
print("The largest number is:", largest_number)
WHILE LOOP – Example 2
odd_numbers = 0
even_numbers = 0
number = int(input("Enter a number or type 0 to stop: "))
while number != 0:
if number % 2 == 1:
odd_numbers += 1
else:
even_numbers += 1
number = int(input("Enter a number or type 0 to stop: "))
print("Odd numbers count:", odd_numbers)
print("Even numbers count:", even_numbers)
WHILE LOOP – Example 2
odd_numbers = 0
even_numbers = 0
number = int(input("Enter a number or type 0 to stop: "))
while number:
if number % 2:
odd_numbers += 1
else:
even_numbers += 1
number = int(input("Enter a number or type 0 to stop: "))
print("Odd numbers count:", odd_numbers)
print("Even numbers count:", even_numbers)
WHILE LOOP – Example 3

#Using a counter variable to exit a while loop

counter = 5
while counter != 0:
print("Inside the loop.", counter)
counter -= 1
print("Outside the loop.", counter)
ACTIVITY - Scenario

A junior magician has picked a secret number. He has hidden it in a


variable named secret_number. He wants everyone who runs his
program to play the Guess the secret number game, and guess what
number he has picked for them. Those who don't guess the number will
be stuck in an endless loop forever! Unfortunately, he does not know
how to complete the code.
Your task is to help the magician complete the code in the editor in such a way so that the code:
• will ask the user to enter an integer number;
• will use a while loop;
• will check whether the number entered by the user is the same as the number picked by the magician. If
the number chosen by the user is different than the magician's secret number, the user should see the
message "Ha ha! You're stuck in my loop!" and be prompted to enter a number again. If the number
entered by the user matches the number picked by the magician, the number should be printed to the
screen, and the magician should say the following words: "Well done, muggle! You are free now."
The magician is counting on you! Don't disappoint him.
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

•comes from the observation that


sometimes it's more important to count
the "turns" of the loop than to check the
conditions.
•It goes through a collection of items (like
a list, string, or range of numbers) and
does something for each item.
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(100): the in keyword introduces a


syntax element describing
#do something the range of possible values
being assigned to the
control variable;
pass the range() function is
responsible for generating all
the desired values of the
control variable;

the for keyword


opens the for loop
FOR LOOP

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

The range() function invocation


may be equipped with two
arguments, not just one:
FOR LOOP

for i in range(2, 8):


print("The value of i is currently", i)
FOR LOOP

for i in range(3, 10):


print("The value of i is currently", i)
FOR LOOP

Note:
the range() function accepts
only integers as its arguments,
and generates sequences of
integers.
FOR LOOP

for i in range(2, 8, 3):


print("The value of i is currently", i)
FOR LOOP

The third argument is


an increment – it's a value added
to control the variable at every
loop turn.
FOR LOOP

for i in range(1, 1):


print("The value of i is currently", i)
FOR LOOP

for i in range(2, 1):


print("The value of i is currently", i)
FOR LOOP

power = 1
for expo in range(16):
print("2 to the power of", expo, "is", power)
power *= 2
FOR LOOP

import time we've imported the time


module and used the sleep()
for i in range(1,6): method to suspend the
execution of each
print(i, "Mississippi") subsequent print() function
time.sleep(1) inside the for loop for one
second, so that the message
outputted to the console
resembles an actual
counting.
FOR LOOP

word = input("Enter a word: ").upper()

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

break – exits the loop immediately, and


unconditionally ends the loop's operation; the
program begins to execute the nearest instruction
after the loop's body;
BREAK AND CONTINUE STATEMENTS

continue – behaves as if the program has


suddenly reached the end of the body; the next
turn is started and the condition expression is
tested immediately.
BREAK AND CONTINUE STATEMENTS

print("The break instruction:")


for i in range(1, 6):
if i == 3:
break
print("Inside the loop.", i)
print("Outside the loop.")
BREAK AND CONTINUE STATEMENTS

print("\nThe continue instruction:")


for i in range(1, 6):
if i == 3:
continue
print("Inside the loop.", i)
print("Outside the loop.")
BREAK AND CONTINUE STATEMENTS
largest_number = -99999999
counter = 0

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:

ask the user to enter a word;


The entered word must be converted to upper case.
use conditional execution and the continue statement to "eat" the following vowels A, E, I,
O, U from the inputted word;
print the uneaten letters to the screen, each one of them on one line.
ASSIGNMENT ON FOR LOOP

SAMPLE OUTPUTS:

You might also like