python3.6需要使用randin的帮助

2024-10-01 07:19:26 发布

您现在位置:Python中文网/ 问答频道 /正文

from random import randint

Secret = randint(1, 100)

Chances = 5

BotGuess = randint(1, 100)

while(BotGuess != Secret and Chances != 0):
    BotGuess = randint(1, 100)
    print("Bot: I guess " + str(BotGuess) + "!")
    Chances -= 1

    if (BotGuess > Secret):
        print("You: Nope! Try guessing lower")

    elif (BotGuess < Secret):
        print("You: Nope! Try guessing higher")

    elif (BotGuess == Secret and Chances > 0):
        print("You: Wow! You win.")

    elif (Chances == 0):
        print("You: You're out of chances! You lose")


    else:
        print("Shouldn't be possible")

当我告诉机器人猜得更高,他的范围从(1100)到他的猜测+1到100之间,我该如何实现?反之亦然,因为我让他猜得更低。对python不太熟悉。在

另外,任何关于我的代码的外观和流程的提示都非常感谢!在


Tags: andfromimportyousecretrandomprintrandint
3条回答

您可以将猜测的范围存储在变量中,即minGuess和{}。您可以在开头分别将它们设置为1和{}。现在,当您告诉bot猜测更高的值时,只需将minGuess变量设置为BotGuesss + 1。当然,每次你的代码中有BotGuess = randint(1, 100),你就用BotGuess = randint(minGuess, maxGuess)来代替它。在

还有一个关于代码的提示:变量通常应该以小写字母开头。变量以大写字母开头,通常表示类。这是实用的,这样您就可以更容易地理解其他人的代码。Here是一个完整的风格指南。在

您可以使用在条件语句中更改的变量,而不是给randint指定固定参数:

from random import randint

Secret = randint(1, 100)

Chances = 5

min_guess = 1
max_guess= 100

BotGuess = randint(1, 100)

while(BotGuess != Secret and Chances != 0):
    BotGuess = randint(min_guess, max_guess)
    print("Bot: I guess " + str(BotGuess) + "!")
    Chances -= 1

    if (BotGuess > Secret):
        print("You: Nope! Try guessing lower")
        max_guess = BotGuess - 1

    elif (BotGuess < Secret):
        print("You: Nope! Try guessing higher")
        min_guess = BotGuess + 1

    elif (BotGuess == Secret and Chances > 0):
        print("You: Wow! You win.")

    elif (Chances == 0):
        print("You: You're out of chances! You lose")


    else:
        print("Shouldn't be possible")

一次测试运行给出了以下输出:

^{pr2}$

nbro在评论中建议你改进写作风格。他说你的代码应该改成这样:

import random


def main():
    secret = random.randint(1, 100)
    chances = 5
    bot_guess = random.randint(1, 100)
    while bot_guess != secret and chances > 0:
        bot_guess = random.randint(1, 100)
        print(f'Bot: I guess {bot_guess}!')
        chances -= 1
        if bot_guess > secret:
            print('You: Nope! Try guessing lower.')
        elif bot_guess < secret:
            print('You: Nope! Try guessing higher.')
        elif bot_guess == secret and chances > 0:
            print('You: Won! You win.')
        elif chances == 0:
            print('You: You are out of chances! You lose.')
        else:
            raise ValueError('should not be possible')


if __name__ == '__main__':
    main()

如果你想要一个更接近你要求的程序,下面的代码可以帮助你更好地改变你自己的程序,使之成为一个更智能的机器人:

^{pr2}$

相关问题 更多 >