# Python does not have a do-while loop. You can however simulate# it by using a while loop over True and breaking when a certain# condition is met.# Example:
i =1whileTrue:print(i)
i = i +1if(i >3):break
################################### THERE IS NO DO-WHILE IN PYTHON ##################################### BEACUSE YOU DON'T NEED IT# Here is the alternativewhileTrue:# INFINITE LOOP (not really) # This is like do'''
stuff to do
'''ifnot(condition):# this is like while (condition)break
# 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 =Truewhile python_is_cool:if first_time:print("python is cool!")else:
first_time =Falseprint("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 =0while counter <3:print("Inside loop")
counter = counter +1else:print("Inside else")
# Program to add natural numbers up to 'n'# sum = 1+2+3+...+n
n =10sum=0
i =1while i <= n:sum=sum+ i
i = i+1# update counter# print the sumprint("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 -whileTrue:(#what ever you want in the loop)#second way - while1:(#what ever you want in the loop)
# a while loop repeats its instructions as long as the condition is met# this one will loop indefinitely
python_is_cool =Truewhile 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
#Make a variable containing an integer like shown below:
i=1while i<=6:print("Hello")#This loop will go on forever and the only way to stop it is to kill your program
secret_word ="python"
counter =0whileTrue:
word =input("Enter the secret word: ").lower()
counter = counter +1if word == secret_word:breakif word != secret_word and counter >7:break
# while True loopwhileTrue:print("This will continue to print this forever")# while variable loop
value =5while value =5:# Since this is true, this will continue on foreverprint("Yes")
'''Example to illustrate
the use of else statement
with the while loop'''
counter =0while counter <3:print("Inside loop")
counter = counter +1else:print("Inside else")
# 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 inrange(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 =0while x <5:# This is the loop condition, the loop will repeat WHILE thid condition is trueprint(x)
x +=1if x ==3:break# This break statment will end the loop no matter what
CAN_loop =True
thenumber =0from time import sleep, time
while CAN_loop:#put your code in here. for example i do this. you can delete the codeprint(Number)
Number = Number +1
sleep(1)if thenumber ==10:
CAN_loop =Falseprint("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 logoprint(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 5if game_level =='easy':
num_of_turns =5# user chose easy - num_of_turns will be assigned the value of 3elif game_level =='hard':
num_of_turns =3# user typed something random - num_of_turns is not updated, stays 0else:print('invalid entry.')# continue guess (flag): this will make it possible for us to get out of the loop
continue_guess =Truewhile continue_guess ==True:if num_of_turns <1:print('goodbye!')
continue_guess =Falseelse:# user guess
guess_number =int(input('guess a number between 1 and 100: '))if guess_number > answer_num:
num_of_turns -=1print(f'guess too high! | {num_of_turns} turns remaining.')elif guess_number < answer_num:
num_of_turns -=1print(f'guess too low! | {num_of_turns} turns remaining.')elif guess_number == answer_num:# user won, get out of the loopprint(f'You guessed it right! | correct guess: {guess_number}')# update your flag from True to False to get out of the loop
continue_guess =Falseelse:# user typed something random, get out of the loopprint('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 logoprint(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 5if game_level =='easy':
num_of_turns =5# user chose easy - num_of_turns will be assigned the value of 3elif game_level =='hard':
num_of_turns =3# user typed something random - num_of_turns is not updated, stays 0else:print('invalid entry.')# continue guess (flag): this will make it possible for us to get out of the loop
continue_guess =Truewhile continue_guess ==True:if num_of_turns <1:print('goodbye!')
continue_guess =Falseelse:# user guess
guess_number =int(input('guess a number between 1 and 100: '))if guess_number > answer_num:
num_of_turns -=1print(f'guess too high! | {num_of_turns} turns remaining.')elif guess_number < answer_num:
num_of_turns -=1print(f'guess too low! | {num_of_turns} turns remaining.')elif guess_number == answer_num:# user won, get out of the loopprint(f'You guessed it right! | correct guess: {guess_number}')# update your flag from True to False to get out of the loop
continue_guess =Falseelse:# user typed something random, get out of the loopprint('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 =3while 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 inrange(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 countersum=0
i =1while i <= n:sum=sum+ i
i = i+1# update counter# print the sumprint("The sum is",sum)
#Multiples of three
i =0whileTrue:print(i)
i = i +3if(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 on6#i=39#i=612#so on151821242730
# It is very important to understand the logic behind the While loop
n =3while 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 variableprint(n)
# do while sample loop in python# do statements in try while number is < 0
i =0
number =-1while number <0:try:
number =int(input("Enter a number: "))print(number)
i +=1except ValueError:print("Invalid input")