简体   繁体   中英

I am trying to do the basic number guessing game on python

I am having trouble writing the code of the basic number guessing game in Python. The objective of the game is to correctly guess a number from 1 to 10 picked at random by the program. I also put some help text that tells the users if they guessed too high or too low. I keep getting a syntax error. This is the code i wrote so far:

 print "Welcome to the number guessing game"
 print "I have my number..."
 import random
 while True:

    random.randint(1, 10)
    number = raw_input("What is your guess[1-10]: ")
    if number > random.radint(1, 10):
         print "sorry you guessed to high"
    elif number < random.radint(1, 10):
         print "You guessed to low"
    elif number == random.radint(1, 10):
         print "You guessed right thanks for playing"
         break
    else: raw_input("What is your guess[1-10]: ")

It is randint not radint . You are creating a new random number for every test; you should assign a variable to a random number outside of the while loop.

r = random.randint(1, 10)

You must indent if: else: blocks - Python is layout sensitive, eg

if number > r:
    print "sorry you guessed to high"

You are comparing against a str , need to convert the input to an int() .

number = int(raw_input("What is your guess[1-10]: "))

You have an unnecessary else: condition at the end.
So putting it all together:

import random
print "Welcome to the number guessing game"
print "I have my number..."
r = random.randint(1, 10)
while True:
    number = int(raw_input("What is your guess[1-10]: "))
    if number > r:
        print "sorry you guessed to high"
    elif number < r:
        print "You guessed to low"
    else:
        print "You guessed right thanks for playing"
        break

You could change the while loop to cover the condition:

import random
print "Welcome to the number guessing game"
print "I have my number..."
number = 0
r = random.randint(1, 10)
while number != r:
    number = int(raw_input("What is your guess[1-10]: "))
    if number > r:
        print "sorry you guessed to high"
    elif number < r:
        print "You guessed to low"
print "You guessed right thanks for playing"

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