Class IX Robotics(Introduction to Data - Programming with Python) Lesson 5 Control Statements Session 2024--25
Class IX Robotics(Introduction to Data - Programming with Python) Lesson 5 Control Statements Session 2024--25
Video Tutorials:
Python Programming Tutorial - for loop
Python Programming Tutorial - While loop
Python Programming Tutorial - Loop Controls Break and Continue
Python range Function
Python Loops
Python has two primitive loop commands:
• while loops
• for loops
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a
set, or a string). This is less like the for keyword in other programming languages, and works
more like an iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set
etc.
The for loop does not require an indexing variable to set beforehand.
for x in "banana":
print(x)
The break Statement
With the break statement we can stop the loop before it has looped through all the items:
Exit the loop when x is "banana":
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
Exit the loop when x is "banana", but this time the break comes before the print:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
for x in range(6):
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)
2. Accept number from user and calculate the sum of all number between 1 and given number.
3. Input a number and find out the sum of digits of that number.
7. Write a Python program to find numbers between 100 and 400 (both included) where each digit
of a number is an even number. The numbers obtained should be printed in a comma-separated
sequence.
8. Take 10 integers from keyboard using loop and print their average value on the screen.
10.Input a number and check whether the number is armstrong number or not.