We've learned about Python variables, data types, operations, and conditional statements in previous articles. Now we'll learn "loops." This is a crucial chapter for understanding how to save time and effort using the same code multiple times.
What is Loops in Python?
In Python, the loop is used to control flow or can say that repeat the same block of code without writting it again. In simple words, programmer uses loop concept to execute the same code again and again as their requirement.
It makes our code easy to understand, shorter, and efficient. Programmers often use when performing repetitive tasks such as numbers, processing items in a list, long calculations etc..
There are two types of loops in Python: For and While.
For Loop in Python
It is used when you know how many times the code in the program will be executed or how many times it may repeat.
Syntax:
for variable in sequence:
#code
Here: "For" - Loop keyword, "num" - Variable name, "in" - iterate (repeat), "range" - 0 to 4 integer (below we read it in detail), ":" - block start.What is Range in Python program?
Range allows coder to decide start, stop and step size (means how much to jump between numbers).
Note: Stop number is not included in the range means if stop number is 3, it goes from 0 to 2.
Syntax:
range(stop)
range(start, stop)
range(start, stop, step)
While Loop in Python
It continusouly run until the condition is True. Once the condition is false, it will exit the from loop.
Syntax:
While condition:
code
Here: "While" - Loop keyword, "sum" - variable name (already mention to start loop from 1.),
"
sum <=5" - condition run until the sum value is equal to 5, "
sum+=1" - increase count by 1 each time (This is called incrementing).
Note: sum+=1 means sum = sum +1
Infinite loop: if condition never false then it is run continusouly.
while True:
print ("Quillix blogspot")
Loop Control Statement
Break
Break statement is used to stop or terminate the loop when a specific condition is met.
Continue
Continue statement is used to skip the current iteration of a loop when a specified condition is met.
you can check in output 5 is skipped.
Pass
It does nothing, coder use when want to add code later.
Nested Loops
Nested loops is used when you want to create pattern, metrics, game and table.
Task 1: Create a Infite loop of number start from 1
Task 2: Create Table of 5 and 10
Task 3: Create a loop to types character from string
Task 4: Create a pattern: Increase star in each line up to 5
Conclusion
This is the third chapter in our Python series. We hope you enjoy it and continue practicing all the tasks and scenarios. If you find this helpful, please share with others.
Learning depends solely on practice, and that's essential when it comes to programming.