首页 > 解决方案 > Python中的确定循环和不确定循环

问题描述

我需要在此代码上显示“确定循环”和“不确定循环”。(嵌套)

这是一个简单的代码,选择一个随机数,并给你 2 次猜测数字的机会,如果你不能,它会让你知道魔法数字是什么,然后重新开始游戏。

问题:还有其他方法可以让游戏重新开始吗?像一个while或嵌套循环。如果足够,我可以得到意见吗?

代码的问题是,每次你猜测时,它都会打印

 "Can you guess the magic number?"

它怎么能只在代码的开头打印,然后只打印:

"try a lower number"
"try a higher number"

感觉代码嵌套不够,反正我能把它做得更专业吗?

repeat_the_game = True
def start():
    import random
    magic_number = random.randint(1, 10)
    trying = 0
    limit = 2
    while trying < limit:
        guess = int(input("can you guess the magic number?"))
        trying += 1
        if guess > magic_number:
            print("try a lower number")
        elif guess < magic_number:
            print("try a higher number")
        elif guess == magic_number:
            print("wow, you are right")
            break
    else:
        print("sorry, the magic number was", magic_number)

while repeat_the_game:
    start()

标签: pythonloopswhile-loopnested-loops

解决方案


将文本移出循环到打印语句。然后你仍然可以在循环中继续获取输入:

repeat_the_game = True
def start():
    import random
    magic_number = random.randint(1, 10)
    trying = 0
    limit = 2
    print("can you guess the magic number?")
    while trying < limit:
        trying += 1
        guess = int(input())
        if guess > magic_number:
            print("try a lower number")
        elif guess < magic_number:
            print("try a higher number")
        elif guess == magic_number:
            print("wow, you are right")
            break
    else:
        print("sorry, the magic number was", magic_number)

while repeat_the_game:
    start()

但是,如果第二次猜测仍然错误,您可能不想打印“尝试更低/更高的数字”。如果你第二次猜对了,你确实想打印“哇,你是对的”。在额外检查所有尝试是否已经用完之后,我会放置“尝试更低/更高的数字”。您可以在检查之前移动“哇,你是对的”部分:

while trying < limit:
    guess = int(input())
    trying += 1
    if guess == magic_number:
        print("wow, you are right")
        break
    if trying == limit:
        continue
    if guess > magic_number:
        print("try a lower number")
    elif guess < magic_number:
        print("try a higher number")
else:
    print("sorry, the magic number was", magic_number)

推荐阅读