Home > Software engineering >  Python program to terminate the loop when an invalid input is given my user
Python program to terminate the loop when an invalid input is given my user

Time:03-07

Create a Python program to continuously ask integer input from the number using an infinite while loop. If the number is between 1 and 100, print the number. However, if the number is outside of this range, terminate the loop.

CodePudding user response:

x = int(input())
while(True):
    if x<1 or x>100:
       break
    else:
       x = int(input())

CodePudding user response:

https://www.w3schools.com/python/python_while_loops.asp

https://www.w3schools.com/python/ref_keyword_break.asp

This should do it. Read up on this, and attempt to solve the issue.

If you are really lazy and want this handed to you. Here:

while 2 > 1:
    x = input("Enter a number from 1 to 100: ")
    if int(x) >= 1 and int(x) <= 100:
        break
    else:
        x = input("Enter a number from 1 to 100: ")
print("Congratz, you entered a valid number: "   str(x))
  • Related