[英]How do I fix my (supposedly while-loop or if-statement) dice-simulator in Python so it prints the amount of tries its taken before landing on a 6?
[英]How do I fix my while-loop and if conditionals in my guessAge(age) in Python?
以下是我的作业说明。 我试图弄清楚我在做什么错,但是每次我正确输入数字时,它仍然会说错了,如果我输入错了,也不会给出全部六次尝试。
我到底在做什么错?
描述:
编写一个函数,将年龄作为参数,并要求用户猜测该年龄。
用户最多有6次猜测的机会(第6次尝试后,如果有错,请让用户知道他已经超过尝试次数)。
用户可以通过写(
QUIT
,quit
或Quit
)代替年龄来退出游戏,而您必须告诉他一个令人鼓舞的信息,例如:(不要因为困难而放弃!)。如果用户正确猜出了年龄,请告诉他他做得不错,并尝试了多少次才能猜出年龄。
无论发生什么情况,在游戏结束时都要感谢用户的参与。
下面是我到目前为止的代码。
def guessAge(age):
guess = input("Guess the Age") #This counts as one try.
count = 1
maxtries = 5
quit = 'quit', 'QUIT', 'Quit'
while maxtries != 0:
if guess == age:
count += 1
print("Great Job! It took you", count, "try/tries to guess the age. Thank you for playing!")
break
if guess != age:
count += 1
maxtries -= 1
fail = input("Try again. Guess the Age")
if fail == quit:
print("Don't give up just because things are hard! Thank you for playing!")
break
print("You have exceeded the number of tries. Thank you for playing!")
您可能想使用如下形式:
while maxtries != 0:
if guess == age:
# correct
print "you are right... yada yada"
break # break out of while loop
else:
# incorrect
print "you are wrong..."
# no break here
在您的程序中,两种情况都使用break
,这会打破while循环。 我认为那不是你的意思。
我使用了if-else
而不是两个互补的if
,当您遇到互补的情况时(在您的情况下是对还是错),这很好。 这可能会更好,因为if
s覆盖了所有内容,我知道它可以处理所有情况而无需验证两者的逻辑。
另外,要检查会员资格使用in
:
if fail in quit:
break # break loop
如果您不想担心字母大小写,只需小写用户给您的内容:
if fail.lower() == "quit":
break # break loop
这是一种方法:
def guess_age(age):
count = 0
max_tries = 6
quit = ('quit', 'QUIT', 'Quit')
while True:
guess = input("Try to guess the age -->")
count += 1
max_tries -= 1
if guess in quit:
print("Don't give up that easy! Thank you for playing!")
break
elif guess == age:
print("Great Job! It took you", count, "try/tries to guess the age. Thank you for playing!")
break
elif guess != age:
print("Sorry, incorrect!")
if max_tries == 0:
print("You have exceeded the number of tries. Thank you for playing!")
break
您提出的主要错误是你不小心打碎了( break
)了你的第二个if语句的; 顺便说一句,应该只是if-elif或if-else。
编辑:还请注意我如何命名“ max_tries”变量。 这实际上只是一个优先事项,但是“ max_tries”比“ maxtries”更具可读性。 同样,有些人,例如我自己,比“ guessAge”更喜欢“ guess_age”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.