Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Rules for functions
- 1) Define a function BEFORE you call it
- 2) Must have at least one instruction in the function body...
- must have either 'pass' or a print statement
- 3) Be careful with indentation
- 4) DO NOT define another function inside a function
- """
- import random as rd
- def main():
- keepGoing = True
- while keepGoing:
- playARound()
- response = input("Play again? (y/n)? ").strip().lower()[0]
- if response == 'n': keepGoing = False
- print("Bye...")
- def playARound():
- global guessedCorrectly
- global numGuesses
- computerGeneratesNumber()
- numGuesses = 0
- MAX_ALLOWED = 3
- guessedCorrectly = False
- while not guessedCorrectly and numGuesses < MAX_ALLOWED:
- makeAGuess()
- numGuesses += 1
- checkGuess()
- outputResult()
- print("end")
- def computerGeneratesNumber(): #name of the function
- global numToGuess
- # pass
- print("generating a number to guess")
- numToGuess = rd.randint(0, 100)
- print(numToGuess)
- # outdenting is the end of the function definition
- def makeAGuess():
- global userGuess #global is needed so python can change the amount of guesses
- print("Make a guess...")
- validInput = False
- while not validInput:
- try:
- userGuess = int(input("What is your guess? ").strip())
- validInput = True
- except:
- print("non-interger input... try again")
- def checkGuess():
- global guessedCorrectly
- if userGuess < numToGuess: print("guess is too low") # dont need to set userGuess or numToGuess as global as python just looks it up
- if userGuess > numToGuess: print("guess is too high")
- else:
- guessedCorrectly = True
- print("got it right")
- def outputResult():
- if guessedCorrectly: print("Well Done, you got it right in", numGuesses, "goes!")
- else: print("bad luck, you ran out of guesses. The number was", numToGuess)
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement