Depends upon condition True or False, while loop is used to execute a group of statements several times.
Syntax of While loop is given below
In above syntax, while checks the condition and if the result is true, the statements is executed written below ( : ) and it will execute several times, till the condition is true. As soon as condition is false, python Interpreter exits out from loop statements.
Example1: Write a Python Program, to display number from 1 to 20 using While loop.
Example 2: Write a Python Program to display even number between 0 to100.
For loop works with sequence like string, List, tuple, range. Based on result on condition of For loop, if condition is true, the for loop statements is executed in sequence. Below is the syntax of For Loop.
For var in sequence:
Example 3: Write a program to display character in string using for loop.
Example 4: Write a program to print the numbers from 15 to 1 in descending order.
In this we need to understand the range () command.
This range () function is used to provide the sequence of numbers. Range (n) gives number from 0 to n-1. Let’s suppose if we write range (15), it will return the value from 0 to 14. Now if we want to return the value from 3 to 10 then we should mention range (3, 11). Here you can also include the step size, means it will display or return te value based on step size.
Example if we write range (1, 10, 3) it will return the value like 1,3,6,9.
Example 5: Write a program to display and find the sum of a list of numbers using loop.
It is the loop that executes forever and never terminates. It can terminate when you use CTRL+C from keyboard. Below is the example that shows how to use Infinite loop.
When a loop is used inside anther loop, we call it Nested Loop. Let’s understand the nested Loop by an example.
Example 6: Write a Python Program to display * in a right angle triangle.
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *