Python Forum
Function not returning expected value
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Function not returning expected value
#3
Firstly, there's a potential recursion issue with the function. In the elif statement, the function is called again; I suppose that's to initiate the sequence again. If the user keeps entering invalid options, that will eventually lead to an overflow. Instead, try wrapping the entire function body in a while loop. You could indent the if statement to move it under the existing loop.

Also, you don't have to write "while user_int == false". You could do "while not user_int" instead.

It's returning the original value because your return statement is in the same local scope as the original answer. So, the function call in the elif statement of the original code is returning a valid answer. Then, the original function call is returning its answer which was invalid.

Here's how I rewrote it:

def user_input(number_of_answers):
    while True:
        try:
            answer = int(input("> "))
        except:
            print("That's not a number!")
            continue

        if 0 < answer < number_of_answers:
            return answer
        print("That answer is not valid!")
Reply


Messages In This Thread
Function not returning expected value - by Euqinu - Sep-09-2018, 09:25 PM
RE: Function not returning expected value - by stullis - Sep-09-2018, 09:56 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Why my function is returning None? PauloDAS 6 1,805 Jul-17-2022, 11:17 PM
Last Post: Skaperen
  Pausing and returning to function? wallgraffiti 1 2,182 Apr-29-2021, 05:30 PM
Last Post: bowlofred
  Why is the function returning None for a * b instead of number? omm 10 4,352 Nov-05-2020, 01:17 PM
Last Post: omm
  Recursive function returns None, when True is expected akar 0 3,412 Sep-07-2020, 07:58 PM
Last Post: akar
  Having hard time understanding the function self-returning itself twice jagasrik 2 2,523 Aug-15-2020, 08:50 PM
Last Post: deanhystad
  Returning Value from Function with Trackbars vicpylon 3 2,090 May-24-2020, 11:28 PM
Last Post: bowlofred
  Nested Recursive Function not Returning Etotheitau 2 2,296 May-09-2020, 06:09 PM
Last Post: Etotheitau
  Function not returning correct value ActualNoob 3 2,736 Jan-11-2019, 12:35 AM
Last Post: stullis
  zip() function does not work as expected AyCaramba 1 7,464 Jan-31-2018, 05:25 PM
Last Post: Gribouillis
  Recursive function not returning expected output...(Python speech recog module) bigmit37 4 5,925 Jan-10-2017, 02:13 PM
Last Post: bigmit37

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020