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

Why is my function returning 0 after a try-except clause?

This code works as intended if valid input is received the first time around. If the input received is incorrect, it will prompt you to try again, and when valid input is finally received it will go on to return 0.

def string_num_query():
    string_num = 0
    try:
        string_num = int(input("Enter number of strings (1-6): "))
        if string_num < 1 or string_num > 6:
            print("Value must be between 1 and 6.")
            string_num_query()
    except ValueError:
        print("User input must be a number.")
        string_num_query()
    return string_num

I’ve tried following the flow of it and just can’t see where I’ve gone wrong. Any help is much appreciated!

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 :

Your recursive function isn’t returning the value of the recursive call, but rather the hard-coded value of string_num each time.

But, you shouldn’t be using recursion to implement a possibly infinite loop at all. Use a while loop instead and break out of the loop when the value of num is valid.

def string_num_query():
    while True:
        string_num = input("Enter number of strings (1-6): ")
        try:
            num = int(string_num)
        except ValueError:
            print("User input must be a number")
            continue

        if 1 <= num <= 6:
            break

    return num
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