Tuesday, January 7, 2025

Loops in Python

Loops in Python

Follow Me

Definition of Loops:-

Loops means repeating something over and over until a particular condition is satisfied.


There are two types of Loops in Python:-

For Loop

1. for Loop in Python

Syntax:

for variable in range(start, stop, step): # code to be repeated

Explanation:

  • for: Keyword to start the loop.
  • variable: The name that will hold the current value of the loop at each iteration.
  • in range(start, stop, step):
    • start: Where the loop starts (default is 0).
    • stop: The number the loop goes up to (but doesn't include).
    • step: How much to increase the variable after each loop (default is 1).

Example:

for i in range(0, 5): print(i)
  • This will print numbers 0 to 4.

While Loop
2. while Loop in Python

Syntax:

while condition: # code to be repeated

Explanation:

  • while: Keyword to start the loop.
  • condition: This is a statement that is checked before each loop. If it’s True, the loop runs. If it’s False, the loop stops.
  • The code inside the loop will keep repeating as long as the condition is True.

Example:

i = 0 while i < 5: print(i) i += 1
  • This prints 0 to 4. The loop continues as long as i is less than 5.

Tips to Remember Python Loop Syntax:

  1. for loop: Think of looping through a sequence. In Python, for is often used with range(), which creates a list of numbers.

    • Remember: for variable in range(start, stop):
  2. while loop: Think of repeating something while a condition is true.

    • Remember: while condition:

Quick Tricks to Remember:

  • Indentation: Python uses spaces (indentation) to define the block of code inside the loop. No curly braces {} like other languages.
  • Colons (:): After the loop condition (whether for or while), always remember the colon :. This tells Python that the next lines are part of the loop.

Example to Remember Both Loops:

for loop:

for i in range(5): # Repeat 5 times, from 0 to 4 print(i)

while loop:

i = 0 while i < 5: # Repeat as long as i is less than 5 print(i) i += 1 # Increment i by 1

To summarize:

  • for loop: Use it when you know how many times you want to repeat the loop (like counting).
  • while loop: Use it when you want to repeat the loop as long as a condition is true.

Note:

Once you understand the logic behind each loop, remembering the syntax becomes easy. The key is practicing and writing loops frequently.

No comments:

Post a Comment

Recursion in DSA using Python

Follow me If you want to understand with  Graphical Representation   click on it. You can find the explanatory video at the bottom of this p...