Weriton
Weriton

Reputation: 13

The while conditional loop doesn't save itself

First, I just want to say I recently started with programming, so I'm not very good. This is my problem:

x = int(input("Write a number between 1-100: "))
while x > 100:
    x = int(input("The number must be less than 101: "))
while x < 1:
    x = int(input("The number must be higher than 0: "))
else:
    print ("The number is:",x)

There's a way to cheat the code by doing this:

Write a number between 1-100: 101
The number must be less than 101: 0
The number must be higher than 0: 101
The number is: 101

I basically don't want the user to be able to write a number higher than 100 or lower than 1.

I'm sorry for the bad explanation but I tried my best and, one again, i recently started programming.

Upvotes: 1

Views: 89

Answers (3)

Rohit Jain
Rohit Jain

Reputation: 213261

Use logical or to test both the condition in a single while:

while not 1 <= x <= 100:  
    x = int(input("The number must be in range [1, 100]: "))

This will iterate the while loop till the user enters the input less than 1 or greater than 100. You can also notice that, this will lead you to an infinite loop, if user keeps on entering invalid input. I'll let you figure out how to solve this issue.

Upvotes: 2

Shashank
Shashank

Reputation: 13869

I would just do it like this:

x = int(input("Enter a number in the range [1, 100]: "))
while not (1 <= x <= 100):
    x = int(input("That number isn't in the range [1, 100]!: "))
else:
    print ("The number is:",x)

You can of course, use nested if statements to make your prompt more informative of the error as follows:

x = int(input("Enter a number in the range [1, 100]: "))
while not (1 <= x <= 100):
    if x > 100:
        x = int(input("The number must be less than 101: "))
    else:
        x = int(input("The number must be greater than 0: "))
else:
    print ("The number is:",x)

Remember that you can test multiple conditions at once!

Upvotes: 3

johnsyweb
johnsyweb

Reputation: 141810

In Python, unlike other programming languages, expressions like a < b < c have the interpretation that is conventional in mathematics. This means that you can write your while-loop just like this:

x = int(input("Write a number between 1-100: "))
while not 1 <= x <= 100:
    x = int(input("The number must be in the range 1-100: "))
else:
    print ("The number is:", x)

Upvotes: 1

Related Questions