0% found this document useful (0 votes)
31 views

Pythonforloop

The document contains examples of using for loops in Python. It shows how to use break and continue statements to exit or skip iterations of a loop early. It also demonstrates nested loops, where an inner loop runs completely for each iteration of the outer loop. Examples include printing adjective-fruit pairs in a nested loop and calculating the sum of numbers in a list using a for loop.

Uploaded by

Jaya Vakapalli
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Pythonforloop

The document contains examples of using for loops in Python. It shows how to use break and continue statements to exit or skip iterations of a loop early. It also demonstrates nested loops, where an inner loop runs completely for each iteration of the outer loop. Examples include printing adjective-fruit pairs in a nested loop and calculating the sum of numbers in a list using a for loop.

Uploaded by

Jaya Vakapalli
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 4

num = int(input("number:"))

factorial=1

if num < 0:

print("must be positive")

elif num == 0:

print("1")

else:

for i in range(1,num + 1):

factorial = factorial * i

print(factorial)

With the break statement we can stop the loop before it has looped through all
the items:

fruits = ["apple", "banana", "cherry"]

for x in fruits:

print(x)

if x == "banana":

break
fruits = ["apple", "banana", "cherry"]

for x in fruits:

if x == "banana":

break

print(x)

With the continue statement we can stop the current iteration of the loop, and continue with the next:

fruits = ["apple", "banana", "cherry"]

for x in fruits:

if x == "banana":

continue

print(x)

for x in range(6):

print(x)

for x in range(2, 6):

print(x)

for x in range(2, 30, 3):

print(x)
Nested Loops

A nested loop is a loop inside a loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":

Example

Print each adjective for every fruit:

adj = ["red", "big", "tasty"]

fruits = ["apple", "banana", "cherry"]

for x in adj:

for y in fruits:

print(x, y)

# Program to find the sum of all numbers stored in a list

# List of numbers

numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]

# variable to store the sum

sum = 0

# iterate over the list


for val in numbers:

sum = sum+val

# Output: The sum is 48

print("The sum is", sum)

Find the factorial of a number

You might also like