While can't work in a form that PyCharm tell's my to simplify

Question:

I had this question many days before and today I have the courage to ask in this page my problem.
I did a weird while statement and it doesn’t work… I have been working on it several days but I can’t understand it.

That is the code, I’m asking to the user a number between 1 and 5.

num = int(input("Num? (1-5) : "))

while 1 > num > 5:
    num = int(input("Num? (1-5) : "))
print(f"El numero introduit: {num}")

In theory, if num is bigger than 5 or smaller than 1 the while statement starts but I have this result…

Num? (1-5) : 7
El numero introduit: 7

But if I use this…

num = int(input("Num? (1-5) : "))

while num < 1 or num > 5:
    num = int(input("Num? (1-5) : "))
print(f"El numero introduit: {num}")

I have what I want…

Num? (1-5) : 7
Num? (1-5) :

When I put the second code in PyCharm, it tells me that I can simplify it in the form of the first code but it doesn’t work but why?

It’s because the first code acts like an "and" and the second code have the "or"?

Answers:

Chained conditions combine the conditions using and, so

while 1 > num > 5:

is equivalent to

while 1 > num and num > 5:

which can never be true.

You can simplify the code by using the condition to break out of the loop.

while True:
    num = int(input("Num? (1-5) : "))
    if 1 <= num <= 5:
        break
Answered By: Barmar

1 is not bigger than 7:

while 1 > num < 5:
Answered By: Leo Ward
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.