下面的While循环获取一个随机生成的数字,并将其与用户生成的数字进行比较。如果第一个猜测是正确的,tit允许用户使用他们在另一个模块中输入的名称。但是,如果第一个猜测是错误的,而第二个猜测是错误的,那么它应该输出一个硬编码的名称。如果第二个猜测是错误的,它应该告诉用户所有的猜测都是错误的,他们没有超能力。问题是我可以让程序为if和else语句工作,但不能为elif工作。请帮忙。在
def getUserName():
print('Welcome to the Superhero Name Game v 2.0')
print('Copyright \N{COPYRIGHT SIGN}2018. Alex Fraser')
userName=input('Please enter the superhero name you wish to use. ')
return userName
def getUserGuess():
import random
x = random.randint(1,10)
userGuess = int(input('Please enter a number between 1 and 10. '))
return x, userGuess
def superName(n, r, g):
guessCount = 1
while guessCount < 3:
if g == r and guessCount == 1:
#hooray
print(f'Congrats! You can use your chosen name. Your superhero name is {n}')
return
elif g == r and guessCount == 2:
#meh good effort
print('Your superhero name is Captain Marvel.')
return
else:
getUserGuess()
print(r,g)
guessCount += 1
print('All your guesses were incorrect. Sorry you do not have super powers')
print(f'The number you were looking for was {r}')
n = getUserName()
r, g = getUserGuess()
print(r,g)
superName(n,r,g)
您不需要打破}只有在上面的}条件失败时才会运行。您对break语句所做的就是从while循环中跳出。在
if/elif/else
条件。这些不是循环。elif
和{elif
和{你的
else
子句没有意义。它在语法上是有效的,但逻辑上没有意义。你写的是:您希望“告诉用户他们失败了”的逻辑只在while循环结束后触发,因为while循环强制执行“做三次”操作。在
^{pr2}$你在有限的尝试次数上迭代。我觉得把它转换成search-style ^{} :
我们可以更进一步,对消息进行迭代:
^{pr2}$我注意到}。您可能需要重新考虑(此修订版也会更改
getUserGuess
调用实际上并没有改变{r
,这可能也不是您想要的)。这就解释了为什么你从来没有看到第二个成功消息;你输入了第二个猜测,但是程序再次检查了第一个猜测。在相关问题 更多 >
编程相关推荐