While (this condition is true) {
execute this code
}
execute this code if that condition is false
Ex:
number=int(input("Enter a positive integer: "))
while number<1:
print("That is not a positive integer. Try again")
number=int(input("Enter a positive integer: "))
print("\nGood job!")
We begin by asking for the user to enter a positive number - input returns a str then we convert it into an integer via int. If the integer is anything less than 1, then it is not positive. In those cases, we tell the user to try again, and then ask again for the integer. The second ask for integer inside the loop is the "update".
So for example, this could play out like so:
Enter a positive integer: -3
That is not a positive integer. Try again
Enter a positive integer: 0
That is not a positive integer. Try again
Enter a positive integer: -100
That is not a positive integer. Try again
Enter a positive integer: 2
Good job!
What's going on here is
before the loop
number=int(input("Enter a positive integer: ")) executes
user enters -3
number<1 evaluates to True
the loop is entered
print("That is not a positive integer. Try again") executes
number=int(input("Enter a positive integer: ")) executes
user enters 0
number<1 evaluates to True
the loop is entered
print("That is not a positive integer. Try again") executes
number=int(input("Enter a positive integer: ")) executes
user enters -100
number<1 evaluates to True
the loop is entered
print("That is not a positive integer. Try again") executes
number=int(input("Enter a positive integer: ")) executes
user enters 2
number<1 evaluates to False
the loop is NOT entered
print("\nGood job!") executes
1
u/Naive_Programmer_232 Oct 14 '26
Sure,
Ex:
We begin by asking for the user to enter a positive number -
inputreturns a str then we convert it into an integer viaint. If the integer is anything less than 1, then it is not positive. In those cases, we tell the user to try again, and then ask again for the integer. The second ask for integer inside the loop is the "update".So for example, this could play out like so:
What's going on here is