如何生成随机数并将其与令牌输入进行比较?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何生成随机数并将其与令牌输入进行比较?相关的知识,希望对你有一定的参考价值。

因此,我试图制作一个函数def number_guess(num):以便生成一些随机整数并将它们与某些input()进行比较并打印一些语句。

例如,如果我输入:

32 45 48 80

我的目标输出是

32 is too low. Random number was 80.
45 is too high. Random number was 30.
48 is correct!
80 is too low. Random number was 97.

我们还在​​使用种子值900,它将使计算机每次运行程序时都选择相同的随机数。

到目前为止,我的代码是:

# TODO: Import the random module
import random

def number_guess(num):
    # TODO: Get a random number between 1-100

    random.randint(1,100)

    # TODO: Read numbers and compare to random number

    for token in tokens:
        if token < randint:
            print('{} is too low. Random number was {}.'.format(user_input[0], randint))
        elif token > randint:
            print('{} is too high. Random number was {}.'.format(user_input[1], randint))
        elif token == randint:
            print('{} is correct!'.format(randint))


if __name__ == "__main__":
    # Use the seed 900 to get the same pseudo random numbers every time
    random.seed(900)

    # Convert the string tokens into integers
    user_input = input()
    tokens = user_input.split()
    for token in tokens:
        num = int(token)
        number_guess(num)

我尝试过:def number_guess(num): #TODO:获取1-100之间的随机数

    randint = ['']
    random.randint(1,100)

    # TODO: Read numbers and compare to random number

    for num in tokens:
        if token < randint:
            print('{} is too low. Random number was {}.'.format(num[0], randint))
        elif token > randint:
            print('{} is too high. Random number was {}.'.format(num[1], randint))
        elif token == randint:
            print('{} is correct!'.format(randint))

但是我不是很了解格式以及此功能应该如何工作。任何帮助表示赞赏!

答案

您应该替换此:

randint = ['']
random.randint(1,100)

带有此:

randint = random.randint(1,100)
另一答案

您的代码存在几个问题,其主要原因是您对生成的随机数不执行任何操作,并尝试通过名称randint访问它,这将导致“未定义的名称”异常。] >

您的代码的简化版本也将起作用,如下所示:

import random

tokens = [32, 45, 48, 80]

def number_guess():
    secret = random.randint(1,100)
    for token in tokens:
        if token < secret:
            print('{} is too low. Random number was {}.'.format(token, secret))
        elif token > secret:
            print('{} is too high. Random number was {}.'.format(token, secret))
        elif token == secret:
            print('{} is correct!'.format(secret))

if __name__ == "__main__":
    # Use the seed 900 to get the same pseudo random numbers every time
    random.seed(900)
    number_guess()

我删除了用户输入部分,不相关的参数和无关的循环,现在您获得了所有测试令牌的反馈:

32 is too low. Random number was 80.
45 is too low. Random number was 80.
48 is too low. Random number was 80.
80 is correct!
    
另一答案

您需要将您的random.randint()呼叫存储到内存中。

以上是关于如何生成随机数并将其与令牌输入进行比较?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用文件填充数组并将其与用户输入 c++ 进行比较

如何编码照片并将其与网络摄像头输入进行比较?

生成随机布尔概率

phpmyadmin 与 java。有没有办法从 phpmyadmin 获取字符串并将其与键盘输入进行比较?

如何获取当前位置并将其与其他 lolation 或几乎关于 android studio 中的第二个位置进行比较

如何使我的代码生成令牌并将其返回以对用户进行身份验证?