0

How can i fix my variable in function

I'm confused on why my "tries" can't plus 1 in my code . can anyone help me with my code? Here's the code I wrote : import random number = random.randint(1,100) print("Here's the question\nI'm looking for a number from 1 to 100 ") guess_num = input("Enter a number :") def guessing_func(guess_num): tries = 1 if guess_num < number : print("guess higher ") guess_num = input("Try again :") return guessing_func(guess_num) tries += 1 elif guess_num > number : print("guess lower ") guess_num = input("Try again :") return guessing_func(guess_num) tries += 1 elif guess_num == number : print("You got it ,the number is {0} . \nYou have tried {1} times".format(number , tries )) guessing_func(guess_num)

17th Mar 2018, 1:13 PM
Nathan Lo
Nathan Lo - avatar
4 Respostas
+ 2
You're using recursion, each time you call the function again tries is defined as 1. try using a while statement to keep testing till you get the number. like this. def guessing_func(guess_num): tries = 1 while(True) : if guess_num < number : print("guess higher ") guess_num = input("Try again :") tries += 1 elif guess_num > number : print("guess lower ") guess_num = input("Try again :") tries += 1 elif guess_num == number : print("You got it ,the number is {0} . \nYou have tried {1} times".format(number , tries )) break
17th Mar 2018, 1:43 PM
Tomer Sim
Tomer Sim - avatar
+ 1
you can make your function accept another variable which would be tries def guessing_func(guess_num,tries): accept tries as 1 at the start and then change the return function to: return guessing_func(guess_num,tries+1) at every point.
19th Mar 2018, 9:37 PM
Tomer Sim
Tomer Sim - avatar
0
Thanks a lot Mr. Sim ,but I still cannot figure out how to fix the code a better way Can anyone else give me a more specific answer? I'll be very appreciated!!!!!Thanks I had just improved it , but I still can't get the right output in the end . import random number = random.randint(1,10) tries = 1 print("Here's the question\nI'm looking for a number from 1 to 10 ") guess_num = int(input("Enter a number :")) def guessing_func(guess_num): i = tries while guess_num != number : i += 1 if guess_num < number : print("guess higher ") guess_num = int(input("Try again :")) return guessing_func(guess_num) elif guess_num > number : print("guess lower ") guess_num = int(input("Try again :")) return guessing_func(guess_num) elif guess_num == number : print("You got it ,the number is {0} . \nYou have tried {1} times".format(number , i )) guessing_func(guess_num)
17th Mar 2018, 3:32 PM
Nathan Lo
Nathan Lo - avatar
0
your return is before the +=. It makes the function leave so it will never make it to the +=, just put it on the line before return
17th Mar 2018, 3:33 PM
Markus Kaleton
Markus Kaleton - avatar