简体   繁体   中英

Python Random Guessing Game

Implement the GuessNumber game. In this game, the computer - Think of a random number in the range 0-50. (Hint: use the random module.) - Repeatedly prompt the user to guess the mystery number. - If the guess is correct, congratulate the user for winning. If the guess is incorrect, let the user know if the guess is too high or too low. - After 5 incorrect guesses, tell the user the right answer.

The following is an example of correct input and output.

I’m thinking of a number in the range 0-50. You have five tries to
guess it.
Guess 1? 32
32 is too high
Guess 2? 18
18 is too low
Guess 3? 24
You are right! I was thinking of 24!

This is what I got so far:

import random

randomNumber = random.randrange(0,50)
print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")
guessed = False

while guessed == False:
    userInput = int(input("Guess 1?"))
    if userInput == randomNumber:
        guessed = True
        print("You are right! I was thinking of" + randomNumber + "!")
    elif userInput>randomNumber:
        print(randomNumber + "is too high.")
    elif userInput < randomNumber:
        print(randomNumber + "is too low.")
    elif userInput > 5:
        print("Your guess is incorrect. The right answer is" + randomNumber)

print("End of program")

I've been getting a syntax error and I don't know how to make the guess increase by one when the user inputs the wrong answer like, Guess 1?, Guess 2?, Guess 3?, Guess 4?, Guess 5?, etc...

Since you know how many times you're going through the loop, and want to count them, use a for loop to control that part.

for guess_num in range(1, 6):
    userInput = int(input("Guess " + str(guess_num) + "?"))
    if userInput == randomNumber:
        # insert "winner" logic here
        break
    # insert "still didn't guess it" logic here

Do you see how that works?

You forgot to indent the code that belongs in your while loop. Also, you want to keep track of how many times you guessed, with a variable or a loop as suggested. Also, when giving a hint you probably want to print the number guessed by the player, not the actual one. Eg,

import random

randomNumber = random.randrange(0,50)
print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")
guessed = False
count = 0

while guessed is False and count < 5:
    userInput = int(input("Guess 1?"))
    count += 1
    if userInput == randomNumber:
        guessed = True
        print("You are right! I was thinking of" + randomNumber + "!")
    elif userInput > randomNumber:
        print(str(userInput) + " is too high.")
    elif userInput < randomNumber:
        print(str(userInput) + " is too low.")
    if count == 5:
        print("Your guess is incorrect. The right answer is" + str(randomNumber))
        print("End of program")

You are facing the syntax error because you are attempting to add an integer to a string. This is not possible. To do what you want you need to convert randomNumber in each print statement.

import random

randomNumber = random.randrange(0,50)

print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")
guessed = False

while guessed == False:
    userInput = int(input("Guess 1?"))
    if userInput == randomNumber:
        guessed = True
        print("You are right! I was thinking of" + str(randomNumber) + "!")
    elif userInput>randomNumber:
        print(str(randomNumber) + "is too high.")
    elif userInput < randomNumber:
        print(str(randomNumber) + "is too low.")
    elif userInput > 5:
        print("Your guess is incorrect. The right answer is" + randomNumber)

print("End of program")
import random
arr=[]
for i in range(50):
   arr.append(i)
answer=random.choice(arr)
for trial in range(5):
   guess=int(input("Please enter your guess number between 0-50. You have 5 
   trials to guess the number."))
   if answer is guess:
       print("Congratulations....You have guessed right number")
       break
   elif guess < answer-5:
       print("You guessed too low....Try again")
   elif guess > answer+5:
       print("You guessed too high..Try again")
   else:
       print("Incorrect guess...Try again please")
print("the answer was: "+str(answer))       

Just a three things to add:

The "abstract syntax tree" has a method called literal_eval that is going to do a better job of parsing numbers than int will. It's the safer way to evaluate code than using eval too. Just adopt that method, it's pythonic.

I'm liberally using format strings here, and you may choose to use them. They're fairly new to python; the reason to use them is that python strings are immutable, so doing the "This " + str(some_number) + " way" is not pythonic... I believe that it creates 4 strings in memory, but I'm not 100% on this. At least look into str.format() .

The last extra treat in this is conditional assignment. The result = "low" if userInput < randomNumber else "high" line assigns "low" of the condition is met and "high" otherwise. This is only here to show off the power of the format string, but also to help contain conditional branch complexity (win and loss paths are now obvious). Probably not a concern for where you are now. But, another arrow for your quiver.

import random
from ast import literal_eval

randomNumber = random.randrange(0,50)
print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")

win = False
for guess_count in range(1,6):
    userInput = literal_eval(input(f"Guess {guess_count}: "))
    if userInput == randomNumber:
        print(f"You are right! I was thinking of {randomNumber}!")
        win = True
        break
    else:
        result = "low" if userInput < randomNumber else "high"
        print(f"{userInput} is too {result}")

if win:
    print ("YOU WIN!")
else:
    print("Better luck next time")
print("End of program")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM