用有限数量的猜测猜猜我的号码游戏

时间:2015-08-10 00:22:52

标签: python

我是python的新手,我试图猜测我的数字游戏只有5次猜测的限制,到目前为止我所尝试的一切都失败了。我该怎么办呢?我忘了提到我希望程序在播放器使用所有猜测时显示一条消息。下面的代码只显示"你猜对了#34; 5猜测后他们是否猜到了。

import random
print ("welcome to the guess my number hardcore edition ")

print ("In this program you only get 5 guesses\n")

print ("good luck")

the_number = random.randint(1, 100)

user = int(input("What's the number?"))

count = 1
while user != the_number:

    if user > the_number:
     print ("Lower")

    elif user < the_number:
     print ("Higher")

    user = int(input("What's the number?"))
    count += 1
    if count == 5:
     break


print("You guessed it!!, the number is", the_number, "and it only"\
       " took you", count , "tries")

input ("\nPress enter to exit")             

2 个答案:

答案 0 :(得分:2)

您的编辑说您想要区分循环是否因为用户猜对了而结束,或者是因为它们没有猜测。这相当于检测您是否退出while循环,因为它的条件测试为false(他们猜到了数字),或者是因为您点击了break(如果他们用完了猜测就会这样做)。你可以使用循环上的else:子句来做到这一点,当循环结束时触发,当且仅当你没有中断时。您可以通过将打印逻辑放在break之前,在相同的条件下,仅在中断的情况下打印某些内容。这给了你:

while user != the_number:
    ...
    if count == 5:
        print("You ran out of guesses")
        break
else:
    print("You guessed it!!, the number is", the_number, "and it only"\
          " took you", count , "tries")

但是,这会将代码放在不同的地方。最好将“猜对了”的逻辑与更温暖/更冷的逻辑分组,而不是将它们与逻辑的一部分交错以进行多少猜测。你可以通过交换测试事物的位置来做到这一点 - 将'是正确的'逻辑放在与温暖/冷却相同的if中,并将猜测逻辑的数量放在循环条件中(这样会更好)表示为for循环)。所以你有:

for count in range(5):
    user = int(input("What's the number?"))
    if user > the_number:
        print("Lower")
    elif user < the_number:
        print("Higher")
    else:
        print("You guessed it!!, the number is", the_number, "and it only"\
              " took you", count , "tries")
        break
else:
    print("You ran out of guesses")

答案 1 :(得分:1)

您有两种选择:一旦计数器达到一定数量或使用或break循环,您可以for退出循环。根据您的代码,第一个选项最简单:

count = 0
while user != the_number:

    if user > the_number:
     print ("Lower")

    elif user < the_number:
     print ("Higher")

    user = int(input("What's the number?"))
    count += 1
    if count == 5: # change this number to change the number of guesses
        break # exit this loop when the above condition is met