for and while loop in python code example
Example 1: python while
# a while loop repeats its instructions as long as the condition is met
# this one will loop indefinitely
python_is_cool = True
while python_is_cool:
print("I love python!")
# while loops are useful when you don't know the number
# of times you want to iterate in advance
Example 2: python while loop
# A while loop is basically a "if" statement that will repeat itself
# It will continue iterating over itself untill the condition is False
python_is_cool = True
first_time = True
while python_is_cool:
if first_time:
print("python is cool!")
else:
first_time = False
print("Done")
# The while loop can be terminated with a "break" statement.
# In such cases, the "else" part is ignored.
# Hence, a while loop's "else" part runs if no break occurs and the condition is False.
# Example to illustrate the use of else statement with the while loop:
counter = 0
while counter < 3:
print("Inside loop")
counter = counter + 1
else:
print("Inside else")
Example 3: how to write a while statement in python
myvariable = 10
while myvariable > 0:
print(myvariable)
myvariable -= 1
Example 4: python while loop
while <condition>:
<run code here>
# for example,
i = 0
while True:
i += 1
# i will begin to count up to infinity
while i == -1:
print("impossible!")
Example 5: how to do a while loop python
while True: #True can be replaced with a different condition
#result