Scientific Computing
game.py
in cs100/ch2
. Copy the following into your file. Your program will wait for you to type something in the shell area and press enter.
answer = input("Type something in: ")
print(answer)
Try running it again, but this time type something different when prompted. What’s happening? Write in comments.
Use this new input function to ask the user for a number between 1 and 10. Store the result in a variable guess
.
Use the function random.randint(1,11)
to generate a random number between 1 and 10. Store the result in another variable answer
.
Print out whether the user’s guess matches the correct answer (if the user won or the computer won). Try playing your game!
Put all of the code you wrote into a single function playGame()
which returns True or False depending on whether the user won.
Ask the user at the beginning of the game how many times they would like to play. Use this number to determine how many times you call the playGame()
function. Adapt your final output so that it reads, for example, “Computer won 8/10; Human won 2/10. Computer wins!”
Play this interactive text-based game. Notice how there’s a limited set of inputs that the user can type. Depending on what the user types, something happens. Think about how you might make an interactive story of your own!