在有限尝试游戏中猜猜我的号码

时间:2012-11-08 17:17:08

标签: python if-statement python-3.x while-loop

作为我在大学课程的一部分,我正在学习python这项任务我一直试图(重新)写这个猜数字游戏,如果用户在5次尝试中未能正确猜测就终止:

    # Guess My Number Mod 5 tries or bust


import random  

print("\nI'm thinking of a number between 1 and 100.")
print("Try to guess it in five tries or less")

my_number = random.randint(1, 100)
guess = int(input("Go on, Take a guess, I dare ya "))
tries = 1

while guess != my_number:
    if guess > my_number:
        print("Lower...")
    else:
        print("Higher...")
guess = int(input("Go on, Take a guess, I dare ya "))
tries += 1
if tries==5:
        input("You failed to guess the number was it that hard?\n Press any key to exit!)"

print("Well done you guessed correctly!The number was", my_number)
print("And it only took you", tries, "tries!\n")

input("\n\nPress the enter key to exit.")

我认为终止原因不起作用,因为我的if语句在while循环之外,我无法使它生效。

还有一些无效的语法,因为我很累,无法发现它。

如果有可能,你们可以给我一些关于如何解决我想做的事情的提示,因为我更有可能以这种方式学习。

2 个答案:

答案 0 :(得分:2)

当您遇到某种情况时,您希望 break 退出循环。

if condition:
            # do something
            break # brings you out of the loop

答案 1 :(得分:0)

如果有人在2020年进行搜索:

import random

n = random.randint(1, 10)

guess_count = 0

guess_limit = 2      #actual try count will be 3

while guess_count <= guess_limit :

    guess = int(input("Enter an integer from 1 to 10: "))

    guess_count += 1
    
    if guess == n:

        print("you guessed it in ", guess_count,"Guesses")

        break
    
else:

    print ("Sorry, the correct number is", n)
相关问题