我在使用Python编写基本数字猜谜游戏的代码时遇到了麻烦。游戏的目的是正确猜出程序随机挑选的1到10的数字。我还提供了一些帮助文本,告诉用户他们是否猜到太高或太低。我一直收到语法错误。这是我到目前为止写的代码:
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]: ")
答案 0 :(得分:0)
randint
不是radint
。您正在为每个测试创建一个新的随机数;你应该为while循环之外的随机数分配一个变量。
r = random.randint(1, 10)
您必须缩进if:
else:
块 - Python对布局非常敏感,例如
if number > r:
print "sorry you guessed to high"
您正在与str
进行比较,需要将输入转换为int()
。
number = int(raw_input("What is your guess[1-10]: "))
最后你有一个不必要的else:
条件
所以把它们放在一起:
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
您可以更改while
循环以涵盖条件:
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"