Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ##Guessing Game python code ammended by Ken Adams from origional code in course python 102 by Rasperby pi(FutureLern)
- #Choose a number 'x'in range 1 <= x <100 and the program will guess it.
- #One function is used 'number_find' that function uses recursion; in other words in the middle of its own code it calls
- #itself. The optional lines ' print("in recursion " +str(guess))' and
- #' print("End recursion " + str(guess) + ": min, middle, max: " + str(min)+ " " + str(middle) + " " + str(max))'
- #show what is going on. Say we need 6 guesses then six runs of number_find will be open. The sixth run finds the answer so
- #it gets to it's return statement and can close. In the meantime run five had called run six so it sitting waiting for
- #recursion six to finish; when that happens it drops through the rest of it's coding and finds its own return statement so can
- #close. We continue in the same way until everything closes. Notice that the first five recursions seem to hold previous
- #values of min, max and middle, so these previous versions never can have their 'else' statement true so can not print out the
- #answer. Only recursion six can print the answer so we only print one statement, the correct one.
- max = 100
- min = 0
- print("Think of a number between 1 and 100 ")# keep this in your head
- def number_find(min,max,guess):
- guess = guess + 1 # counts the number of times number_find is called
- print("in recursion " +str(guess))## optional statement to see what recursion we are in
- middle = int((max + min)/2)
- answer = input("Is your number [H]igher, [L]ower or the [S]ame as " + str(middle) )
- if answer == "H":
- min = middle
- number_find(min,max,guess)#present values of guess, min, max are passed to another version of number_find
- elif answer == "L":
- max = middle
- number_find(min,max,guess)
- else: #if not lower than middle and not higher than middle, then it must be the middle
- print("Your number is " + str(middle) + ", it took me " + str(guess) + " guess(es)" )
- print("End recursion " + str(guess) + ": min, middle, max: " + str(min)+ " " + str(middle) + " " + str(max))
- return 0 # return 0 lets the present version of recurson to close.
- #Here for the first time nmin=0, max=100 from the earlier definition
- number_find(min,max,0)# we start count at 0 as we have not made any guesses yet
- print("bye")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement