Sep-09-2018, 09:25 PM
I have just started learning Python and I'm writing a simple text adventure game... I thought it would be a good idea to write a function that you could tell how many answers there are to pick from, then it would make sure the user enters an integer, and that it's within the range of answers.
So I wrote the code below, however if an incorrect number is entered, using the example below, let's say 6 was entered, it will correctly say that the number isn't valid and asks again, but then even if you put a correct number after that it will only return the first incorrect answer (6 in my example)
I have since re-written this function and got it to work a different way - but I feel like there's probably an important lesson to learn here about functions, as I really can't see why it wouldn't work! So if anyone could tell me why it doesn't work I would be very grateful!
So I wrote the code below, however if an incorrect number is entered, using the example below, let's say 6 was entered, it will correctly say that the number isn't valid and asks again, but then even if you put a correct number after that it will only return the first incorrect answer (6 in my example)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
def user_input(number_of_answers): user_int = False while user_int = = False : try : answer = int ( input ( "> " )) user_int = True except : print ( "That's not a number!" ) for i in range ( 1 , number_of_answers + 1 ): print ( "i = " , i) print ( "answer = " , answer) if i = = answer: print ( "Matched!" ) break elif i = = number_of_answers: print ( "That answer is not valid" ) user_input(number_of_answers) return answer user_answer = user_input( 5 ) print (user_answer) |