Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

FOR LOOP

3.5.2
Basic
Example 1: Print Hello ten times

The structure of a for loop is as follows:

Example 2: The program ask the user for a number and


prints it square. The program ask three times and then
print.
Basic
Example 3: The program below print A, then B, then it will
alternate C’s and D’s five times and then finish with letter
E once.

Example 4: The program below print A, then B, then


followed by 5 C’s and 5 D’s and then finish with letter E
once.
The Loop Variable
In the example below, the loop variable is the variable i.

Another example, the loop variable is the variable name.


The Range Function
Range function determines the number of times of loop

Range function determines the number of times of loop


Iterating by Sequence Index
Iterating each item by index offset

If-Statement with Loops


Nested Loops
Use of one loop inside another loop

Loop Control Statement


Example:
Print a rectangle of stars and a right triangle of stars.

Write a Python program to construct the following


pattern, using a nested loop number.
Example:
Write a program that determine the factorial of a number.

Write a program that determine a number is prime or not.


Example:
Given a list of numbers, Iterate it and print only those
numbers which are divisible of 5

Accept n number from user and calculate the sum of all


number between 1 and n including n
SLOW
progress
BETTER
IS

than no
PROGRESS
Exercise Set A
Write a Python program that accepts a word from the
user and reverse it.
Write a Python program that prints all the numbers from
0 to 6 except 3 and 6.
Write a Python program which iterates the integers from
1 to n. For multiples of three – print “electronics” and for
multiples of five – print “engineer” and for multiples of
three and five – print “electronics engineer”
Exercise Set B
Write a Python program to create the multiplication table
(from 1 to 10) of a number.
Write a Python program that accepts a string and
calculate the number of digits and letters.
Write a Python program to print all even numbers from a
given numbers list in the same order and stop the
printing if any numbers that come after 237 in the
sequence.

You might also like