0% found this document useful (0 votes)
22 views10 pages

Chapter 5

Uploaded by

www.tooo18
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)
22 views10 pages

Chapter 5

Uploaded by

www.tooo18
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/ 10

Kingdom of Saudi Arabia ‫المملكة العربية السعودية‬

Ministry of education ‫وزارة التعليم‬


Qassim University ‫جامعة القصيم‬
Applied College ‫الكلية التطبيقية‬

Chapter 5: Loops In Python

1
ITBS103

Looping your code with while

while conditional_expression:
instruction_one
instruction_two
instruction_three
:
:
instruction_n

2
ITBS103

1
An infinite loop
while True:
print("I'm stuck inside a loop.")

# Store the current largest number here.


largest_number = -999999999
# Input the first value.
number = int(input("Enter a number or type -1 to stop: "))
# If the number is not equal to -1, continue.
while number != -1:
# Is number larger than largest_number?
if number > largest_number:
# Yes, update largest_number.
largest_number = number
# Input the next number.
number = int(input("Enter a number or type -1 to stop: "))
# Print the largest number.
print("The largest number is:", largest_number)

3
ITBS103

# A program that reads a sequence of numbers and counts how many numbers are even
and how
# many are odd. The program terminates when zero is entered.
odd_numbers = 0
even_numbers = 0
# Read the first number.
number = int(input("Enter a number or type 0 to stop: "))
# 0 terminates execution.
while number != 0:
# Check if the number is odd.
if number % 2 == 1:
# Increase the odd_numbers counter.
odd_numbers += 1
else:
# Increase the even_numbers counter.
even_numbers += 1
# Read the next number.
number = int(input("Enter a number or type 0 to stop: "))
# Print results.
print("Odd numbers count:", odd_numbers)
print("Even numbers count:", even_numbers) 4
ITBS103

2
Using a counter variable to exit a loop

counter=int(input("How many operations you want")


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

counter = 0
while counter < 10:
print("Inside the loop.", counter)
counter += 1
print("Outside the loop.", counter)

5
ITBS103

Looping your code with for


for var in iterable:
# statements

# Python program to illustrate


# Iterating over a list
arr = ["geeks", "for", "geeks"]
for i in arr:
print(i)

Output:
Geeks
for
geeks

6
ITBS103

3
Looping your code with for
The value of i is currently 0
The value of i is currently 1
The value of i is currently 2
for i in range(10): The value of i is currently 3
print("The value of i is currently", i) Output
The value of i is currently 4
The value of i is currently 5
The value of i is currently 6
The value of i is currently 7
The value of i is currently 8
The value of i is currently 9

7
ITBS103

Looping Through a Set

$ python basicloop.py
print('Before')
Before
for thing in [9, 41, 12, 3, 74, 15] : 9
print(thing) 41
print('After')
12
3
74
15
After
8
ITBS103

4
More about the for loop and the range() function with three arguments
❑ The range() function may also accept three arguments – take a look at the code in the editor.

for i in range(2, 8, 3): The value of i is currently 2


Output
print("The value of i is currently", i) The value of i is currently 5

❑ The third argument is an increment – it's a value added to control the variable at every loop turn (as you may suspect, the default
value of the increment is 1).
2 to the power of 0 is 1
2 to the power of 1 is 2
2 to the power of 2 is 4
2 to the power of 3 is 8
2 to the power of 4 is 16
power = 1 2 to the power of 5 is 32
2 to the power of 6 is 64
for expo in range(16): 2 to the power of 7 is 128
print("2 to the power of", expo, "is", power) Output 2 to the power of 8 is 256
power *= 2 2 to the power of 9 is 512
2 to the power of 10 is 1024
2 to the power of 11 is 2048
2 to the power of 12 is 4096
2 to the power of 13 is 8192
2 to the power of 14 is 16384
2 to the power of 15 is 32768

9
ITBS103

The 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;

❑ 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 - example
print("The break instruction:")
for i in range(1, 6):
if i == 3: The break instruction:
break Inside the loop. 1
print("Inside the loop.", i) Inside the loop. 2
print("Outside the loop.") Outside the loop.

# continue - example Output The continue instruction:


Inside the loop. 1
print("\nThe continue instruction:") Inside the loop. 2
for i in range(1, 6): Inside the loop. 4
Inside the loop. 5
if i == 3:
Outside the loop.
continue
print("Inside the loop.", i) 10
print("Outside the loop.") ITBS103

10

5
The 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 Enter a number or type -1 to end the program: 3
counter += 1 Enter a number or type -1 to end the program: 5
if number > largest_number:
Output Enter a number or type -1 to end the program: 1
largest_number = number Enter a number or type -1 to end the program: -1
The largest number is 5
if counter != 0:
print("The largest number is", largest_number)
else:
print("You haven't entered any number.")

11
ITBS103

11

The break and continue statements

largest_number = -99999999
counter = 0

number = int(input("Enter a number or type -1 to end program:


"))

while number != -1:


if number == -1: Enter a number or type -1 to end program: 2
continue Enter a number or type -1 to end the program: 6
counter += 1
Output Enter a number or type -1 to end the program: -1
The largest number is 6
if number > largest_number:
largest_number = number
number = int(input("Enter a number or type -1 to end the
program: "))

if counter:
print("The largest number is", largest_number)
else:
print("You haven't entered any number.")
12
ITBS103

12

6
Making use of lists

my_list = [10, 1, 8, 3, 5]
total = 0

for i in range(len(my_list)): Output 27


total += my_list[i]

print(total)

13
ITBS103

13

Quiz

14
ITBS103

14

7
❑ Question 1: Create a for loop that counts from 0 to 10, and prints odd
numbers to the screen. Use the skeleton below:
for i in range(1, 11): for i in range(0, 11):
# Line of code. solution if i % 2 != 0:
# Line of code. print(i)

❑ Question 2: Create a while loop that counts from 0 to 10, and prints
odd numbers to the screen. Use the skeleton below:

x=1 x=1
while x < 11: while x < 11:
# Line of code. solution if x % 2 != 0:
# Line of code. print(x)
# Line of code. x += 1

15
ITBS103

15

❑ Question 3: Create a program with a for loop and a break statement. The program should
iterate over characters in an email address, exit the loop when it reaches the @ symbol, and
print the part before @ on one line. Use the skeleton below:

for ch in for ch in
"[email protected] "john.smith@pythonin
rg": stitute.org":
if ch == "@": solution if ch == "@":
# Line of code. break
# Line of code. print(ch, end="")

16
ITBS103

16

8
❑ Question 4: Create a program with a for loop and a continue statement. The program
should iterate over a string of digits, replace each 0 with x, and print the modified string to
the screen. Use the skeleton below:
for digit in "0165031806510":
if digit == "0": for digit in "0165031806510":
# Line of code. if digit == "0":
# Line of code. solution print("x", end="")
# Line of code. continue
print(digit, end="")

❑ Question 5: What is the output of the following code?

n = 3

while n > 0: 4
print(n + 1) 3
n -= 1 solution
2
else: 0
print(n)
17
ITBS103

17

❑ Question 6: What is the output of the following code?

n = range(4)
-1
for num in n: 0
print(num - 1) solution 1
else: 2
print(num) 3

❑ Question 7: What is the output of the following code?

for i in range(0, 6, 3): 0


solution
print(i) 3

18
ITBS103

18

9
❑ Question 8: What is the output of the following snippet?

lst = [1, 2, 3, 4, 5]
lst.insert(1, 6)
del lst[0]
lst.append(1) solution [6, 2, 3, 4, 5, 1]
print(lst)

❑ Question 9: What is the output of the following snippet?


lst = [1, 2, 3, 4, 5]
lst_2 = []
add = 0

for number in lst:


solution [1, 3, 6, 10, 15]
add += number
lst_2.append(add)

print(lst_2) 19
ITBS103

19

❑ Question 10: What is the output of the following snippet?

lst = []
del lst solution NameError: name 'lst' is not defined
print(lst)

❑ Question 11: What is the output of the following snippet?

lst = [1, [2, 3], 4]


[2, 3]
print(lst[1]) solution
3
print(len(lst))

20
ITBS103

20

10

You might also like