Problem Solving using Python
Prof. Sarju S
Assistant Professor, Dept. of CSE, SJCET Palai
Tuesday, January 05, 2021
Iteration
Page 2
Iteration
Page 3 Prof. Sarju S, Assistant Professor, SJCET Palai
The while statement
► The while loop in Python is used to iterate
over a block of code as long as the test
expression (condition) is true.
► Syntax of while Loop in Python
while test_expression:
Body of while
► Example
i=0
while i <= 10:
sum = sum + i
i = i+1
Page 4 Prof. Sarju S, Assistant Professor, SJCET Palai
The while statement
► Write a Python program which takes integer number as input and reverse
the same.
Page 5 Prof. Sarju S, Assistant Professor, SJCET Palai
The while statement
► Write a Python program which takes integer number as input and reverse
the same.
Page 6 Prof. Sarju S, Assistant Professor, SJCET Palai
The while statement
► Python Program to Check Whether a Number is Palindrome or Not
Page 7 Prof. Sarju S, Assistant Professor, SJCET Palai
The while statement
► Python Program to Check Whether a Number is Palindrome or Not
Page 8 Prof. Sarju S, Assistant Professor, SJCET Palai
The while statement
► Develop a python program
that displays future leap years,
starting with the first occurring
leap year from the current
year, until a final year created
by the use.
Page 9 Prof. Sarju S, Assistant Professor, SJCET Palai
The while statement
► Develop a python program
that displays future leap years,
starting with the first occurring
leap year from the current
year, until a final year created
by the use.
Page 10 Prof. Sarju S, Assistant Professor, SJCET Palai
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.
Page 11 Prof. Sarju S, Assistant Professor, SJCET Palai
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 is", sum)
Page 12 Prof. Sarju S, Assistant Professor, SJCET Palai
The range() function
► We can generate a sequence of numbers using range() function.
range(10) will generate numbers from 0 to 9 (10 numbers).
► We can also define the start, stop and step size as range(start,
stop,step_size). step_size defaults to 1 if not provided.
Page 13 Prof. Sarju S, Assistant Professor, SJCET Palai
#happycoding
Thank You
Prof. Sarju S
Department of Computer Science and Engineering
St. Joseph’s College of Engineering and Technology, Palai
https://www.linkedin.com/in/sarju-s/
Email: [email protected]
Page 14