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

How to avoid "can be undefined" error in Python?

I am trying to make a simple code to input a positive integer in the most accurate way possible. I mention that I am very new to the language.

Here is my code :

while number != None:
    try:
        while True:
            number = int(input("Donnez la longueur de votre liste: "))
            if number > 0:
                break
    except TypeError:
        print("Tu doit donner un nombre entier")

The warning I get is number can be Undefined I am not aware of what is the specific situation where number is undefined as the while loop breaks only when number is not None ( means defined according to me ). I’m so grateful for your help. It is a challenging time but you would make it easier.

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

>Solution :

You can sidestep any warnings with a more idiomatic loop:

while True:
    number = input("Donnez la longueur de votre liste: ")
    try:
        number = int(number)
    except ValueError:
        print("Tu doit donner un nombre entier")
        continue
    
    if number > 0:
        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