Table of contents
Welcome back to our Python learning journey! Today, we're going to dive into loops. Loops are a fundamental concept in programming that allow us to execute a block of code repeatedly. There are two main types of loops in Python: for
loops and while
loops. We'll explore both types and learn how to leverage them effectively.
For loop
for
loops are used when you have a block of code which you want to repeat a fixed number of times. They are commonly used for iterating over sequences like lists, tuples, or strings.
#Iterating over a string
for x in "panda":
print(x)
#Using the range() function
for i in range(5):
print(i)
In first case, we're printing each character of the string "panda"
, one by one, on a separate line.
range() is a built-in Python function that generates a sequence of numbers from 0 up to, but not including, 5. So, range(5)
produces the sequence [0, 1, 2, 3, 4]. for each number in the sequence generated by range(5)
And in this case, we're printing each number from 0 to 4 on separate lines.
#output
p
a
n
d
a
While Loops
while
loops are used when you want to execute a block of code as long as a condition is true. Careful with while
loops, as they can potentially result in infinite loops if not used properly.
num = 1
while num <= 3:
print(num)
num = num + 1
#output
1
2
3
here we used a while
loop to print the numbers from 1 to 3. The loop runs as long as the condition num <= 3
is satisfied.
Loop Control : Python provides loop control statements like break
, continue
, and pass
to modify the execution of loops.
break
: Terminates the loop prematurely.continue
: Skips the rest of the loop's code for the current iteration and proceeds to the next iteration.pass
: Acts as a placeholder, doing nothing. It is often used when a statement is required syntactically but you don’t want any command or code to execute.# Using break and continue in a loop for i in range(10): if i == 5: continue #Skip printing 3 if i == 8: break #Stop the loop when reaches 7 print(i)
Conclusion:
In conclusion, loops in Python provide a versatile way to repeat tasks and iterate over data structures. Whether it's iterating through a sequence of elements or executing code based on a condition, loops help streamline your code and make it more efficient. By learning loops, you'll have a powerful tool for solving a variety of programming problems.
Stay curious! Happy coding <3