猜猜随机数为啥我无法输入 - python
Posted
技术标签:
【中文标题】猜猜随机数为啥我无法输入 - python【英文标题】:Guess Random Number Why i m not able to enter input - python猜猜随机数为什么我无法输入 - python 【发布时间】:2017-01-24 17:21:20 【问题描述】:以下是我的代码,用于生成 0 - 9 之间的随机数,并通过用户输入检查它是更高还是更低。当我运行代码时,它没有接受输入并显示
'guessNumber = int(input("Guess a Random number between 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()
【问题讨论】:
请正确格式化您的代码 其实我格式化了..当我复制到这里时,它是这样的。是不是有什么逻辑错误? 正确格式化这里。你得到了什么错误? 【参考方案1】:我认为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
并添加了一个中断,否则它将无限循环(将整数与字符串输入值进行比较)。
【讨论】:
以上是关于猜猜随机数为啥我无法输入 - python的主要内容,如果未能解决你的问题,请参考以下文章
用c#编写猜数游戏要求用户在文本框中输入1到10之间的一个数字。然后单击[猜猜]按钮产生一个随机数字,用户