Python LAB 05
Python LAB 05
LAB # 05
Control Statements
OBJECTIVE:
To get familiar with the concept of control statement for simple controlling and repetition of program
statements.
Theory:
Control Statements (Loops)
Programming languages provide various control structures that allow for more
complicated execution paths.
Syntax
while expression:
statement(s)
The condition may be any expression, and true is any non-zero value. The loop iterates
while the condition is true. When the condition becomes false, program control passes to
the line immediately following the loop.
In Python, all the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code. Python uses
indentation as its method of grouping statements.
Example-1: Example-2:
i=1 i=1
while i < 4: while i < 4:
print (i) print i
i+=1 i+=1
print( “END”) print “END”
Output-1: Output-2:
1 END 1
2 END 2
3 END 3
END
Output:
Enter the number: 5 Factorial is 120
The for loop is useful to iterate over the elements of a sequence. It means, the for loop
can be used to execute a group of statements repeatedly depending upon the number of
elements in the sequence. The for loop can work with sequence like string, list, tuple, range
etc.
The syntax of the for loop is given below:
for var in sequence:
statement (s)
The first element of the sequence is assigned to the variable written after „for‟ and then the
statements are executed. Next, the second element of the sequence is assigned to the variable
and then the statements are executed second time. In this way, for each element of the sequence,
the statements are executed once. So, the for loop is executed as many times as there are
number of elements in the sequence.
1 END 1
2 END 2
3 END 3
END
Output-1: Output-2:
Example-3: Example-4:
Name= "python"
for x in range(10,0,-1):
for letter in Name:
print x,
print letter
Output-3: Output-4: 10 9 8 7 6 5 4 3 2 1
py t h o n
Program:
Output:
TASK:
Perform the following tasks using Python source code using loops
1. To generate 10 random numbers from 3 to 13.
CODE:
OUTPUT:
2. To print the odd number from 10 to 100 and even numbers from 200 to 96.
CODE:
OUTPUT:
3. To take a integer value from a user and print the factorial of that number.
CODE:
OUTPUT:
4. To take two integer values from the user and print the table. The first indicates the table
number and the second value represents the limit of the table.
CODE:
OUTPUT:
5. To take two integer values from the user and print out the highest and lowest value. Ask
the user if they want to continue entering more numbers until they choose no.
CODE:
OUTPUT:
OUTPUT: