Lab#5
Lab#5
LAB # 05
THEORY
A loop can be used to tell a program to execute statements repeatedly. In other word, to
keep a computer doing useful work we need repetition, looping back over the same block
of code again and again.
Type of Loop Statements in Python:
There are 2 types of loop statements in Python language. They are,
1. for
2. while
Output:
>>> %Run task1.py
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o Current
Letter : n
Output:
>>> %Run task2.py
Programming is fun
Programming is fun
Programming is fun
Programming is fun
Programming is fun
In while loop first the condition (boolean expression) is tested; if it is false the loop is
finished without executing the statement(s). If the condition is true, then the statements
are executed and the loop executes again and again until the condition is false. Each loop
contains a loop-continuation-condition, a Boolean expression that controls the body’s
execution.
Output:
>>> %Run task3.py
Programming is fun!
Programming is fun!
Programming is fun!
Programming is fun! Programming is fun!
EXERCISE
A.Point out the errors, if any, in the following Python programs.
1. Code
for(;;) {
printf("SSUET") }
Output:
2. Code
count = 4 while
n < 8
count = count + 3:
print(count)
Output:
3.Code
Output:
2.Code
i = 1 while
i>0:
print(i)
i = i + 1
Output
1
2
3
4
5
6
7
8
9
.
.
.
.
.
.
infinity
3.Code
for v in range(3, 9, 2):
print(v)
Output
1. Write a program that prints the first 10 natural numbers and their sum using ‘for loop’.
Sample output:
The first 10 natural number are :
1 2 3 4 5 6 7 8 9 10
The Sum is : 55
Source Code:
num = 10 if
num < 0:
print("Enter a positive number") else:
sum = 0
# use while loop to iterate until zero
while(num > 0): sum += num num -= 1
print("The sum of the natural numbers is", sum)
Output:
2. Write a program to print the multiplication table of the number entered by the user.
The table should get displayed in the following form.
29 x 1 = 29
29 x 2 = 58
…
29 x 10 = 290
Source Code:
num = int(input("Enter the number: "))
3. Write a program that take vowels character in a variable named “vowels” then
print each vowels characters in newline using ‘for loop’.
Source Code:
print("Enter the Character: ") c = input() if
c=='a' or c=='e' or c=='i' or c=='o' or c=='u':
print("\nIt is a Vowel") elif c=='A' or c=='E' or
c=='I' or c=='O' or c=='U':
print("\nIt is a Vowel") else:
print("\nIt is a Consonant") Output: