Python Loops

Loops execute a block of code, and this code executes while the condition is true. In this lesson, we will learn about Python Loops, such as the while loop, the for loop, etc.

while loop in Python

In a while loop, the block of code executes only when the condition is true. It executes as long as the condition is true.

Syntax

Here’s the syntax:

while (condition is true):
    code

Example

The following is an example showing the usage of the while loop in Python,

Demo24.py

# while loop in Python
# Code by studyopedia

a = 0

while (a < 3):
    print("Value = ",a)
    a = a + 1;

Output

Value =  0
Value =  1
Value =  2

for loop in Python

The for loop in Python is used when you can set how many times a statement is to be executed.

Syntax

Here’s the syntax,

for var in sequence:
   code

Example

The following is an example showing the usage of a for loop in Python,

Demo25.py

# for loop in Python
# Code by studyopedia

for w in "Amit":
  print("Words in my name = ",w)

Output

The following is the output,

Words in my name =  A
Words in my name =  m
Words in my name =  i
Words in my name =  t

In this lesson, we learned about the types of loops in Python.

Python Tutorial (English)

Python Tutorial (Hindi)

If you liked the tutorial, spread the word and share the link and our website, Studyopedia, with others.


For Videos, Join Our YouTube Channel: Join Now


Read More:

Python Variables
Python Decision Making Statements
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment