0

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!

match
  • 10,388
  • 3
  • 23
  • 41

2 Answers2

2

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
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Thanks so much! I'll keep in mind like you and others mentioned not to use a recursion in this case. Hugely appreciative. – user17833395 Jan 04 '22 at 22:32
-1
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.")
           return string_num_query()
    except ValueError:
        print("User input must be a number.")
        return string_num_query()

   return string_num
B.Quinn
  • 77
  • 1
  • 7