Home > OS >  While can't work in a form that Pycharm tell's my to simplify
While can't work in a form that Pycharm tell's my to simplify

Time:12-13

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 doesnt 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 doesnt work but WHY???

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

Sry if I typed something wrong, im from Spain.

Thx u so much.

CodePudding user response:

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

CodePudding user response:

1 is not bigger than 7:

while 1 > num < 5:
  • Related