Python if...elif...else and Nested if
Syntax of for Loop
for val in sequence: Body of for
Here,
val
is the variable that takes the value of the
item inside the sequence on each iteration. Loop continues until we
reach the last item in the sequence. The body of for
loop is separated from the rest of the code using indentation.Example: Python for Loop
# 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
# print the sum
print("The sum is",sum)
OutputThe sum is 48
The
while
loop in Python is used to iterate over a block
of code as long as the test expression (condition) is true. We
generally use this loop when we don't know beforehand, the number of
times to iterate.Syntax of while Loop
while test_expression: Body of while
In
while
loop, test expression is checked first. The body of the loop is entered only if the test_expression
evaluates to True
. After one iteration, the test expression is checked again. This process continues untill the test_expression
evaluates to False
.In Python, the body of the
while
loop is determined through indentation. Body starts with indentation
and the first unindented line marks the end. Python interprets any
non-zero value as True
. None
and 0
are interpreted as False
.Example: Python while Loop
# Program to add natural
# numbers upto n where
# n is provided by the user
# sum = 1+2+3+...+n
# take input from the user
n = int(input("Enter n: "))
# initialize sum and counter
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is",sum)
OutputEnter n: 10 The sum is 55
Python break and continue Statement
break statement
Thebreak
statement terminates the loop containing it. Control of the program
flows to the statement immediately after the body of the loop. If it is
inside a nested loop (loop inside another loop), break
will terminate the innermost loop.Syntax of break
break
Flowchart of break
The working of
break
statement in for loop and while loop is shown below.Example: Python break
# Program to show the use of break statement inside loop
for val in "string":
if val == "i":
break
print(val)
print("The end")
Outputs t r The end
thank you.
ReplyDeletepython3 tutorial
java tutorial