下面是我的代码,用于生成0到9之间的随机数,并检查用户输入是否更高或更低。当我运行代码时,它没有输入并显示
'guessNumber = int(输入(“猜测0-9之间的随机数”)中的错误)文件“”,第1行
有人可以告诉我我在哪里犯错误
#Guess Random Number
#Generate a Random number between 0 to 9
import random
turn = 0
def guessRandom():
secretNumber = random.randint(0,9)
guessNumber = int(input("Guess a Random number between 0-9"))
while secretNumber != guessNumber:
if(secretNumber > guessNumber):
input("You have Guessed the number higher than secretNumber. Guess Again!")
turn = turn + 1
elif (secretNumber < guessNumber):
input("You have guessed the number lower than secretNumber. Guess Again! ")
turn = turn + 1
if(secretNumber == guessNumber):
print("you Have Guessed it Right!")
guessRandom()
答案 0 :(得分:0)
我认为guessRandom()
意味着在方法定义之外,以便调用方法。由于输入未分配为guessNumber
,guessNumber
变量永远不会更改,因此它会不断检查初始猜测。此外,小于/大于标志似乎与预期的消息冲突。此外,turn
超出了方法的范围。
#Generate a Random number between 0 to 9
import random
def guessRandom():
secretNumber = random.randint(0, 9)
guessNumber = int(input("Guess a Random number between 0-9: "))
i = 0
while secretNumber != guessNumber:
if secretNumber < guessNumber:
print "You have guessed a number higher than secretNumber."
i += 1
elif secretNumber > guessNumber:
print "You have guessed a number lower than secretNumber."
i += 1
else:
print("you Have Guessed it Right!")
guessNumber = int(input("Guess Again! "))
return i
turn = 0
turn += guessRandom()
编辑:假设您正在使用input
in Python3(或在旧版本的Python中使用raw_input
),除了ValueError
之外,您可能需要输入字符串。例如,
#Generate a Random number between 0 to 9
import random
def guessRandom():
secretNumber = random.randint(0, 9)
guessNumber = input("Guess a Random number between 0-9: ")
i = 0
while True:
try:
guessNumber = int(guessNumber)
except ValueError:
pass
else:
if secretNumber < guessNumber:
print "You have guessed a number higher than secretNumber."
i += 1
elif secretNumber > guessNumber:
print "You have guessed a number lower than secretNumber."
i += 1
else:
print("you Have Guessed it Right!")
break
guessNumber = input("Guess Again! ")
return i
turn = 0
turn += guessRandom()
我将while
循环条件更改为True
并添加了一个中断,否则它将无限循环(将整数与字符串输入值进行比较)。