[go: up one dir, main page]

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

Loops and Fnction

The document provides a comprehensive overview of loops in Python, detailing both for and while loops, including their syntax and use cases. It explains how to utilize break and continue statements, as well as the range function for generating sequences. Additionally, the document covers nested loops, functions, and includes various examples and lab work exercises for practical application.

Uploaded by

marubakulwa
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)
13 views12 pages

Loops and Fnction

The document provides a comprehensive overview of loops in Python, detailing both for and while loops, including their syntax and use cases. It explains how to utilize break and continue statements, as well as the range function for generating sequences. Additionally, the document covers nested loops, functions, and includes various examples and lab work exercises for practical application.

Uploaded by

marubakulwa
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/ 12

Loops in Python

A for loop is used to iterate over a sequence (such as a list,


tuple, or string)
Use for loop when you know exactly how many times you
want to execute the loop.
for loops = execute a block of code a fixed number of
times. You can iterate over a range , string or sequence.
Break : used to terminate the loop when encountered
Continue : terminates execution in the current iteration &
continues execution of the loop with the next iteration.
Range
Range functions returns a sequence of numbers, starting from 0 by default, and increments by 1
(by default), and stops before a specified number.

range( start?, stop, step?)

for el in range (5):


print(el)

0
1
2
3
4

for el in range (1, 5):


print(el)

1
2
3
4

for el in range (1, 5, 2):


print(el)
1
3

Example
list = [1, 2, 3, 4, 5]
for el in list:
print(el)

1
2
3
4
5

list = [1, 2, 3, 4, 5]
for el in list:
print(el)
else:
print("END")

1
2
3
4
5
END

colors = ["blue", "black", "green", "red", "grey"]


for i in colors:
print(i)

blue
black
green
red
grey

for i in range (1, 10):


print(i)

1
2
3
4
5
6
7
8
9
for x in reversed(range(1,11)):
print(x)

print ("Hello Class")

10
9
8
7
6
5
4
3
2
1
Hello Class

for x in range(1, 11, 2):


print(x)

1
3
5
7
9

for x in range(1, 11, 3):


print(x)

1
4
7
10

credit_Card = "1234-5678-9012-3456"

for x in credit_Card:
print(x)

1
2
3
4
-
5
6
7
8
-
9
0
1
2
-
3
4
5
6

for x in range(1, 21):


if x == 13:
continue
else:
print(x)

1
2
3
4
5
6
7
8
9
10
11
12
14
15
16
17
18
19
20

for x in range(1, 21):


if x == 13:
break
else:
print(x)

1
2
3
4
5
6
7
8
9
10
11
12

for i in range (4):


x = int(input("Please enter a number between 1 and 100:"))
if 1 <=x<=100:
print("valid no", x)
break
else:
print("invalid number. Try again.")

Please enter a number between 1 and 100: 1000

invalid number. Try again.

Please enter a number between 1 and 100: 2000

invalid number. Try again.

Please enter a number between 1 and 100: 3000

invalid number. Try again.

Please enter a number between 1 and 100: 4

valid no 4

Lab Work
using for

1. Print the elements of the following list using a loop: [1, 4, 9, 16, 25, 36, 49, 64, 81,100]
2. Search for a number x in this tuple using loop: [1, 4, 9, 16, 25, 36, 49, 64, 81,100]

using for & range( )

1. Print numbers from 1 to 100.


2. Print numbers from 100 to 1.
3. Print the multiplication table of a number n.
A while loop is used to repeatedly execute a block of code
as long as a certain condition is true
Use while loop when you don't know how many times you
need to execute the loop beforehand.
While loop = execute some code WHILE some condition
remains true
Example
i = 1
while i < 5:
print(i)
i+=1

1
2
3
4

x=0
while not(1<=x<=100):
x = int(input("Please enter a number between 1 and 100:"))
print("valid no", x)

Please enter a number between 1 and 100: 87

valid no 87

name = input("Enter your name: ")

while name == "":


print("You did not enter your name")
name = input("Enter your name: ")
print(f"Hello {name}")

Enter your name:

You did not enter your name

Enter your name:

You did not enter your name

Enter your name: Salim

Hello Salim
name = input("Enter your name: ")

while name == "":


print("You did not enter your name")

print(f"Hello {name}")

Enter your name: Salim

Hello Salim

age = int(input("Enter your age: "))

while age < 0:


print("Age can't be negative")
age = int(input("Enter your age: "))
print(f"You are {age} years old")

Enter your age: -1

Age can't be negative

Enter your age: -2

Age can't be negative

Enter your age: -3

Age can't be negative

Enter your age: 45

You are 45 years old

food = input("Enter a food you like (q to quit): ")

while not food == "q":


print(f"You like {food}")
food = input("Enter another food you like (q to quit): ")

print("bye")

Enter a food you like (q to quit): pizza

You like pizza

Enter another food you like (q to quit): Wali

You like Wali

Enter another food you like (q to quit): q

bye
num = int(input("Enter a number between 1-10: "))

while num < 1 or num > 10:


print(f"{num} is not valid")
num = int(input("Enter a number between 1-10: "))

print(f"Your number is {num}")

Enter a number between 1-10: 7

Your number is 7

Lab Work
1. Print numbers from 1 to 100.
2. Print numbers from 100 to 1.
3. Print the multiplication table of a number n.
4. Print the elements of the following list using a loop: [1, 4, 9, 16, 25, 36, 49, 64, 81,100]
5. Search for a number x in this tuple using loop: [1, 4, 9, 16, 25, 36, 49, 64, 81,100]

Nested Loops
Nested loop = A loop within nother loop (outer, inner)
outer loop:
inner loop:

while loop inside a while loop while x > 0: while y > 0: print("do something")

for loop inside a for loop for x in range(3): for y in range (9): print("do something")

while loop inside a for loop while x > 0: for y in range (9): print("do something")

for loop inside a while loop for x in range(3): while y > 0: print("do something")
Function
Functions help to organize code into logical blocks that
perform specific tasks.
Function = A block of reusable code. Place () after the
function name to invoke it
print("Happy birthday to you!")
print("You are old!")
print("Happy birthday to you!")
print()

print("Happy birthday to you!")


print("You are old!")
print("Happy birthday to you!")
print()

print("Happy birthday to you!")


print("You are old!")
print("Happy birthday to you!")
print()

Happy birthday to you!


You are old!
Happy birthday to you!

Happy birthday to you!


You are old!
Happy birthday to you!

Happy birthday to you!


You are old!
Happy birthday to you!

def happy_birthday():
print("Happy birthday to you!")
print("You are old!")
print("Happy birthday to you!")
print()

happy_birthday()
happy_birthday()
happy_birthday()

Happy birthday to you!


You are old!
Happy birthday to you!

Happy birthday to you!


You are old!
Happy birthday to you!

Happy birthday to you!


You are old!
Happy birthday to you!

def happy_birthday(name):
print(f"Happy birthday to {name}!")
print("You are old!")
print("Happy birthday to you!")
print()

happy_birthday("Bro")
happy_birthday("Salim")
happy_birthday("Warith")

Happy birthday to Bro!


You are old!
Happy birthday to you!

Happy birthday to Salim!


You are old!
Happy birthday to you!

Happy birthday to Warith!


You are old!
Happy birthday to you!

def happy_birthday(name, age):


print(f"Happy birthday to {name}!")
print(f"You are {age} years old!")
print("Happy birthday to you!")
print()

happy_birthday("Bro", 20)
happy_birthday("Salim", 40)
happy_birthday("Warith", 15)

Happy birthday to Bro!


You are 20 years old!
Happy birthday to you!

Happy birthday to Salim!


You are 40 years old!
Happy birthday to you!
Happy birthday to Warith!
You are 15 years old!
Happy birthday to you!

def display_invoice(username, amount, due_date):


print(f"Hello {username}")
print(f"Your bill of ${amount: .2f} is due: {due_date}")

display_invoice("Brocode", 42.50, "01/01")

Hello Brocode
Your bill of $ 42.50 is due: 01/01

def display_invoice(username, amount, due_date):


print(f"Hello {username}")
print(f"Your bill of ${amount: .2f} is due: {due_date}")

display_invoice("Harith", 100, "01/02")

Hello Harith
Your bill of $ 100.00 is due: 01/02

return = statement used to end a function and send a


result back to the caller
def create_name(first, last):
first = first.capitalize()
last = last.capitalize()
return first + " " + last

full_name = create_name("salim", "diwani")

print(full_name)

Project
1. write a program for weight conversion
2. write a program for temperature conversion
3. write a program for email slicer
4. write a program for compound interest
5. write a program for countdown timer
6. write a program for shopping cart
7. create a quiz game
8. write a program for concession stand
9. write a program for number guessing game
10. write a program for dice roller
11. write a program for encryption
12. develop a project for banking
13. develop a project for slot machine

You might also like