Loops in Python
While Loop
A
while
loop in Python repeats a block of code as long as a specified condition remainsTrue
.It is ideal when we don’t know beforehand how many times we want to execute a block of code, but want to keep running it as long as a condition holds.
while condition: # Code
Condition: The loop continues as long as the condition is
True
. Once it becomesFalse
, the loop stops.Indentation the body of the loop must be indented to indicate which code is inside the loop.
Breaking out of a loop:
We can use the
break
statement to exit awhile
loop before the condition becomesFalse
(for example, when we meet a specific condition within the loop).else
withwhile
: Python allows an optionalelse
block withwhile
. It runs only if the loop wasn’t exited withbreak
.
For Loop
A
for
loop is used to iterate over a sequence and perform an action for each item.It’s used when we know exactly how many iterations we need to work with.
for item in sequence:
Sequence: This can be any iterable object (list, string, etc). The loop will go through each item in the sequence.
Item: During each iteration, the
item
variable holds the current value from the sequence.Indentation: The code block inside the
for
loop must be indented to indicate it belongs to the loop.my_list= [1, 2, 3, 5] print(my_list[0]) my_list.append("april") print(my_list[4])
range()
function:- A common use of the
for
loop is with therange()
function, which generates a sequence of numbers.
- A common use of the
Similar to
while
, we can use thebreak
statement to stop the loop early.Below are the example loops used in our main example
calc_of_units = 24
name_of_units = "hours"
def days_to_units(num_of_days):
return f"{num_of_days} days are {num_of_days * calc_of_units} {name_of_units}"
def validate_exe():
try:
user_inp_num = int(num_of_days_elem)
if user_inp_num > 0 :
calc_value = days_to_units(user_inp_num)
print(calc_value)
elif user_inp_num == 0:
print("you entered 0")
else:
print("negative num")
except ValueError:
print("not a valid num")
user_inp = " "
while user_inp != "exit":
user_inp = input("input no of days i will convert it to hours\n")
for num_of_days_elem in user_inp.split(", "):
validate_exe()
Comments
Comments improve the readability and maintainability of code.
Single-line comments:
Start with a
#
symbol and continue until the end of the line.These comments are used for brief explanations.
Multi-line comments:
we use triple quotes (
'''
or"""
) to create block commentsTriple quotes can span multiple lines, but technically these are treated as docstrings (often used for documentation rather than commenting out code).