Python loops (for loop & while loop)

 Python Loops(for loop & while loop)

Introduction

Imagine you want to print "Hello, world!" 5 times, then in Python, you will simply write print("Hello, world ") 5 times. But what if you want to print it 100 times?
It's not easy, and also it waste lot of your time. So to solve this problem, loops are used. Loops help us repeat a block of code multiple times.

What Is a Loop?

A loop is used to execute a block of code again and again until a condition is met.
Python has two main types of loops:
  1. for loop
  2. while loop

The for Loop

A for loop is used when we know how many times we want to repeat the code or a statement. The syntax of the code is as follows:

code 1:
#print numbers from 1 to 5
for i in range(1,6):
    print(i)

output:
1
2
3
4
5

Understanding range()

range(start, stop) means:
  • start from this number
  • stop before the last number (stop - 1)
e.g. range(1,6) will print the value from 1 to 5

code 2:
#print Hello 5 times
for i in range(5):
    print("Hello")

The while Loop

The while loop runs as long as the condition is true. It requires three steps: initialisation, condition check and incrementation. Syntax is as follows:

code:
#Print numbers from 1 to 5
i=1

while i <= 5:
    print(i)
    i + = 1 

If you forget to increase i, the loop will run forever, which leads to an infinite loop, i.e. the code will run until the memory space gets full. Always update the variable inside the while loop.

Real-life Example

#Multiplication Table
num = int(input("Enter a number:"))

for i in range(1, 11):
    print(num * i)

This prints the multiplication table of the number the user enters in the code.

Break and Continue

Break stops the loop completely, and the compiler moves to the next line. The syntax for the break is as follows:

code:

for i in range(1,6):
    if i == 3:
        break
    print(i)

Output:

1
2

Continue skips iteration according to the condition provided.

code:

for i in range (1,6):
    if i == 3:
        continue
    print(i)

Output:
1
2
4
5

Practice Questions

  1. Print numbers from 1 to 10
  2. Print even numbers from 1 to 10
  3. Print the multiplication table of any number
  4. Find the sum of numbers from 1 to 10
  5. Count down from 10 to 1
 




 


Comments

Popular posts from this blog

Python Input and Output(input() & print())

Python Conditional Statements(if, elif, else)

Introduction To Database Management System