xxxxxxxxxx
X: while
{how do I use a while loop in Python?}
{while loop}
{The while loop repeatedly executes a block of code as long as a condition is true. Example: while x < 10: x += 1}
xxxxxxxxxx
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!")
xxxxxxxxxx
# 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")
xxxxxxxxxx
j = 0
while j < 3:
print("hello") # Or whatever you want
j += 1
#This runs the loop until reaches 3 and above
xxxxxxxxxx
# while loop runs till the condition becomes false
number = 0
while number > 10: # prints number till 10
print(number)
number += 1
while loops python
xxxxxxxxxx
condition = True
while condition == True:
execute the following
This is basically saying the while a certain variable is equal to something, go ahead and do this.
You can also say when a certain variable is NOT equal to something do this, or when something is True or False, do...
xxxxxxxxxx
while <Condition>:
<code>
#example
i = 10
while i == 10:
print("Hello World!")
xxxxxxxxxx
i = 1
while i<10:
print("hello world")
i+=1
#note the i++ syntax is not valid in python
xxxxxxxxxx
# Program to add natural numbers up to 'n'
# sum = 1+2+3+...+n
n = 10
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is", sum)
# To take input from the user,
# n = int(input("Enter n: "))