4

作为我大学课程的一部分,我正在学习 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 循环之外,我无法让它生效。

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

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

4

2 回答 2

2

您希望在达到特定条件时打破循环。

if condition:
            # do something
            break # brings you out of the loop
于 2012-11-08T17:19:44.670 回答
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)
于 2020-10-07T12:52:22.817 回答