101 Python days: Day 4

Priyanka Meena
2 min readMay 8, 2023

--

While Loop: A while loop allows code to be repeated a number of times as long as the condition is being met. This may be 101 times, just once, or even never. In a while loop, the condition is checked before the code is run, which means it could skip the loop altogether if the condition is not being met to start with.

This article is dedicated to Python codes using a while loop. Let us jump to the examples now.

  1. Ask the user to enter a number. Keep asking until they enter a value over 5 and then display the message “ The last number you entered was a [number]” and stop the program.
num = 0
while num <= 5:
num= int(input("Enter a number : "))
print("The last number you entered was a ", num)

Output:

Enter a number : 3
Enter a number : 5
Enter a number : 7
The last number you entered was a 7

2. Create a variable called compnum and set the value to 50. Ask the user to enter a variable. While their guess is not same as the compnum value, tell them if their guess is too low or too high and ask them to have another guess. If they enter the same value as compnum, display the message “ Well done, you took [count] attempts”.

compnum=50
guess= int(input("Can you guess the number? "))
count=1
while guess!= 50:
if guess <= compnum:
print("Too low")
else:
print("Too high")
count= count +1
guess= int(input("Have another guess: "))
print("Well done, you took", count, "attempts")

Output:

Can you guess the number? 60
Too high
Have another guess: 40
Too low
Have another guess: 50
Well done, you took 3 attempts

--

--