# 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")
# 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: "))
while (condition):
print("I keep printing while the condition is True")
else:
print("I will be written when loop finished. if you use break in loop I won't be executed")
#there are 2 ways to make a while loop in python
#first way -
while True:
(#what ever you want in the loop)
#second way -
while 1:
(#what ever you want in the loop)
#Make a variable containing an integer like shown below:
i=1
while i<=6:
print ("Hello")
#This loop will go on forever and the only way to stop it is to kill your program
# while True loop
while True:
print("This will continue to print this forever")
# while variable loop
value = 5
while value = 5:
# Since this is true, this will continue on forever
print("Yes")
# a 'while' loop runs until the condition is broken
a = "apple"
while a == "apple":
a = "banana" # breaks loop as 'a' no longer equals 'apple'
# a 'for' loop runs for the given number of iterations...
for i in range(10):
print(i) # will print 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
# ... or through a sequence
array = [3, 6, 8, 2, 1]
for number in array:
print(number) # will print 3, 6, 8, 2, 1
x = 0
while x < 5: # This is the loop condition, the loop will repeat WHILE thid condition is true
print(x)
x += 1
if x == 3:
break # This break statment will end the loop no matter what
CAN_loop = True
thenumber = 0
from time import sleep, time
while CAN_loop:
#put your code in here. for example i do this. you can delete the code
print(Number)
Number = Number + 1
sleep(1)
if thenumber == 10:
CAN_loop = False
print("we are gonna stop counting")
# the below game will help you see how you can use while in Python
# we can use the random number generator
from random import randint
# docstring: https://peps.python.org/pep-0257/
logo = '''
❓❓❓ WELCOME TO GUESS THE NUMBER ❓❓❓
'''
# display logo
print(logo)
# randomly generate a number
answer_num = randint(1, 100)
print(answer_num)
# number of turns, start at 0
num_of_turns = 0
# game difficulty
game_level = input('Choose game difficulty - type "easy" or "hard": ').lower()
# check what the user chose
# user chose easy - num_of_turns will be assigned the value of 5
if game_level == 'easy':
num_of_turns = 5
# user chose easy - num_of_turns will be assigned the value of 3
elif game_level == 'hard':
num_of_turns = 3
# user typed something random - num_of_turns is not updated, stays 0
else:
print('invalid entry.')
# continue guess (flag): this will make it possible for us to get out of the loop
continue_guess = True
while continue_guess == True:
if num_of_turns < 1:
print('goodbye!')
continue_guess = False
else:
# user guess
guess_number = int(input('guess a number between 1 and 100: '))
if guess_number > answer_num:
num_of_turns -= 1
print(f'guess too high! | {num_of_turns} turns remaining.')
elif guess_number < answer_num:
num_of_turns -= 1
print(f'guess too low! | {num_of_turns} turns remaining.')
elif guess_number == answer_num:
# user won, get out of the loop
print(f'You guessed it right! | correct guess: {guess_number}')
# update your flag from True to False to get out of the loop
continue_guess = False
else:
# user typed something random, get out of the loop
print('invalid entry!')
continue_guess = False
# the below game will help you see how you can use while in Python
# we can use the random number generator
from random import randint
# docstring: https://peps.python.org/pep-0257/
logo = '''
❓❓❓ WELCOME TO GUESS THE NUMBER ❓❓❓
'''
# display logo
print(logo)
# randomly generate a number
answer_num = randint(1, 100)
print(answer_num)
# number of turns, start at 0
num_of_turns = 0
# game difficulty
game_level = input('Choose game difficulty - type "easy" or "hard": ').lower()
# check what the user chose
# user chose easy - num_of_turns will be assigned the value of 5
if game_level == 'easy':
num_of_turns = 5
# user chose easy - num_of_turns will be assigned the value of 3
elif game_level == 'hard':
num_of_turns = 3
# user typed something random - num_of_turns is not updated, stays 0
else:
print('invalid entry.')
# continue guess (flag): this will make it possible for us to get out of the loop
continue_guess = True
while continue_guess == True:
if num_of_turns < 1:
print('goodbye!')
continue_guess = False
else:
# user guess
guess_number = int(input('guess a number between 1 and 100: '))
if guess_number > answer_num:
num_of_turns -= 1
print(f'guess too high! | {num_of_turns} turns remaining.')
elif guess_number < answer_num:
num_of_turns -= 1
print(f'guess too low! | {num_of_turns} turns remaining.')
elif guess_number == answer_num:
# user won, get out of the loop
print(f'You guessed it right! | correct guess: {guess_number}')
# update your flag from True to False to get out of the loop
continue_guess = False
else:
# user typed something random, get out of the loop
print('invalid entry!')
continue_guess = False
# There are 2 types of loops in python
# while loops and for loops
# a while loops continues for an indefinite amount of time
# until a condition is met:
x = 0
y = 3
while x < y:
print(x)
x = x + 1
>>> 0
>>> 1
>>> 2
# The number of iterations (loops) that the while loop above
# performs is dependent on the value of y and can therefore change
######################################################################
# below is the equivalent for loop:
for i in range(0, 3):
print(i)
>>> 0
>>> 1
>>> 2
# The for loop above is a definite loop which means that it will always
# loop three times (because of the range I have set)
# notice that the loop begins at 0 and goes up to one less than 3.
# Program to add natural
# numbers up to
# sum = 1+2+3+...+n
# To take input from the user,
# n = int(input("Enter n: "))
n = 10
# initialize sum and counter
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is", sum)
#Multiples of three
i = 0
while True:
print(i)
i = i + 3
if(i > 30):
break
#output will be:
0 #First it will count i=0, starts from zero and for example if you put i=1,it will start from 1.
3 #Here i=0, i=0+3, so i=3 and i becomes 3 for next value. so on
6 #i=3
9 #i=6
12 #so on
15
18
21
24
27
30
# It is very important to understand the logic behind the While loop
n = 3
while n>0:
print(n)
n = n - 1 # This can also write as (n -= 1)
print('Blastoff')
# Remember when the n=0, it does not run
# it comes out of the while loop but the value remains in the variable
print(n)
# do while sample loop in python
# do statements in try while number is < 0
i = 0
number = -1
while number < 0:
try:
number = int(input("Enter a number: "))
print(number)
i += 1
except ValueError:
print("Invalid input")