Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading