Advertisement
kenadams53

Guessing Game

Aug 24th, 2019
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 KB | None | 0 0
  1. ##Guessing Game python code ammended by Ken Adams from origional code in course python 102 by Rasperby pi(FutureLern)
  2. #Choose a number 'x'in range 1 <= x <100 and the program will guess it.
  3. #One function is used 'number_find' that function uses recursion; in other words in the middle of its own code it calls
  4. #itself. The optional lines ' print("in recursion " +str(guess))' and
  5. #' print("End recursion " + str(guess) + ": min, middle, max: " + str(min)+ " " + str(middle) + " " + str(max))'
  6. #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
  7. #it gets to it's return statement and can close. In the meantime run five had called run six so it sitting waiting for
  8. #recursion six to finish; when that happens it drops through the rest of it's coding and finds its own return statement so can
  9. #close. We continue in the same way until everything closes. Notice that the first five recursions seem to hold previous
  10. #values of min, max and middle, so these previous versions never can have their 'else' statement true so can not print out the
  11. #answer. Only recursion six can print the answer so we only print one statement, the correct one.
  12.  
  13. max = 100
  14. min = 0
  15. print("Think of a number between 1 and 100 ")# keep this in your head
  16.  
  17. def number_find(min,max,guess):
  18. guess = guess + 1 # counts the number of times number_find is called
  19. print("in recursion " +str(guess))## optional statement to see what recursion we are in
  20. middle = int((max + min)/2)
  21. answer = input("Is your number [H]igher, [L]ower or the [S]ame as " + str(middle) )
  22. if answer == "H":
  23. min = middle
  24. number_find(min,max,guess)#present values of guess, min, max are passed to another version of number_find
  25. elif answer == "L":
  26. max = middle
  27. number_find(min,max,guess)
  28. else: #if not lower than middle and not higher than middle, then it must be the middle
  29. print("Your number is " + str(middle) + ", it took me " + str(guess) + " guess(es)" )
  30. print("End recursion " + str(guess) + ": min, middle, max: " + str(min)+ " " + str(middle) + " " + str(max))
  31. return 0 # return 0 lets the present version of recurson to close.
  32.  
  33. #Here for the first time nmin=0, max=100 from the earlier definition
  34. number_find(min,max,0)# we start count at 0 as we have not made any guesses yet
  35.  
  36. print("bye")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement