Advertisement
Guest User

Semester2_Session2

a guest
Jan 22nd, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.95 KB | None | 0 0
  1. """
  2. Rules for functions
  3. 1) Define a function BEFORE you call it
  4. 2) Must have at least one instruction in the function body...
  5. must have either 'pass' or a print statement
  6. 3) Be careful with indentation
  7. 4) DO NOT define another function inside a function
  8. """
  9.  
  10. import random as rd
  11.  
  12. def main():
  13.     keepGoing = True
  14.     while keepGoing:
  15.         playARound()
  16.         response = input("Play again? (y/n)? ").strip().lower()[0]
  17.         if response == 'n': keepGoing = False
  18.     print("Bye...")
  19.  
  20. def playARound():
  21.     global guessedCorrectly
  22.     global numGuesses
  23.     computerGeneratesNumber()
  24.     numGuesses = 0
  25.     MAX_ALLOWED = 3
  26.     guessedCorrectly = False
  27.  
  28.     while not guessedCorrectly and numGuesses < MAX_ALLOWED:
  29.         makeAGuess()
  30.         numGuesses += 1
  31.         checkGuess()
  32.  
  33.     outputResult()
  34.     print("end")
  35.  
  36. def computerGeneratesNumber(): #name of the function
  37.     global numToGuess
  38.     # pass
  39.     print("generating a number to guess")
  40.     numToGuess = rd.randint(0, 100)
  41.     print(numToGuess)
  42. # outdenting is the end of the function definition
  43.  
  44. def makeAGuess():
  45.     global userGuess #global is needed so python can change the amount of guesses
  46.     print("Make a guess...")
  47.     validInput = False
  48.     while not validInput:
  49.         try:
  50.             userGuess = int(input("What is your guess? ").strip())
  51.             validInput = True
  52.         except:
  53.             print("non-interger input... try again")
  54.  
  55. def checkGuess():
  56.     global guessedCorrectly
  57.     if userGuess < numToGuess: print("guess is too low") # dont need to set userGuess or numToGuess as global as python just looks it up
  58.     if userGuess > numToGuess: print("guess is too high")
  59.     else:
  60.         guessedCorrectly = True
  61.         print("got it right")
  62.  
  63. def outputResult():
  64.  
  65.     if guessedCorrectly: print("Well Done, you got it right in", numGuesses, "goes!")
  66.     else: print("bad luck, you ran out of guesses. The number was", numToGuess)
  67.  
  68.  
  69. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement