Python 中的randint()函数

在本教程中,我们将学习 Python 中的“randint()”函数。

“randint()”是 Python 中random模块的内置函数。random模块用于访问各种函数,如使用 randint()函数生成随机数。

首先,我们必须导入 Python 中的random模块来使用 randint()函数。这个函数基本上用于创建伪随机性。

语法:


randint(start_range, end_range)

参数:

(start_range,end_range): 两个参数都必须是整型值。

参数:

它将返回范围[start_range,end_range]内的随机整数,包括开始和结束数字。

错误和异常:

值错误:当用户将浮点作为参数传递时,返回一个值错误。

类型错误:当用户将整数值以外的任何东西作为参数传递时,返回类型错误。

例 1:

获取两个正数、两个负数、一个正数和一个负数之间的随机数。


import random as rnd
# First, we will generate the random number between any positive number range
random_1 = rnd.randint(55, 75)
print ("The any random number between 55 and 75 is % s" % (random_1))

# Then, we will generate the random number between two given negative number range
random_2 = rnd.randint(-40, -20)
print ("The any random number between -40 and -20 is % s" % (random_2))

# We will now, generate the random number between a positive number and a negative number range
random_3 = rnd.randint(-20, 20)
print ("The any random number between -20 and 20 is % s" % (random_3))

输出:

1#

The any random number between 55 and 75 is 74
The any random number between -40 and -20 is -40
The any random number between -20 and 20 is -12

2#

The any random number between 55 and 75 is 74
The any random number between -40 and -20 is -29
The any random number between -20 and 20 is -2

例 2:

在这个例子中,我们将看到用户如何在 Python 程序中使用 randint()函数获得 ValueError。


# First, we will import the random module
import random as rnd

# If the user passes any floating point values as the parameters in the randint() # function.

random_1 = rnd.randint(2.543, 12.786)
print (random_1)

输出:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
 in <module>4 # If the user passes any floating point values as the parameters in the randint() function.
      5 
----> 6 random_1 = rnd.randint(2.543, 12.786)
      7 print(random_1)

c:\users\User Name\appdata\local\programs\python\python39\lib\random.py in randint(self, a, b)
    336         """
    337 
--> 338         return self.randrange(a, b+1)
    339 
    340 

c:\users\user name\appdata\local\programs\python\python39\lib\random.py in randrange(self, start, stop, step)
    300         istart = int(start)
    301         if istart != start:
--> 302             raise ValueError("non-integer arg 1 for randrange()")
    303         if stop is None:
    304             if istart > 0:

ValueError: non-integer arg 1 for randrange()</module> 

例 3:

在这个例子中,我们将看到用户如何在 Python 中使用 randint()函数获得 TypeError。


# First, we will import the random module
import random as rnd

# If the user passes any string or character value as the parameters in the 
# randint() function

random_2 = rnd.randint('String', 'Character')
print (random_2)

输出:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
 in <module>4 # If the user passes any string or character value as the parameters in the randint() function
      5 
----> 6 random_2 = rnd.randint('String', 'Character')
      7 print (random_2)

c:\users\user name\appdata\local\programs\python\python39\lib\random.py in randint(self, a, b)
    336         """
    337 
--> 338         return self.randrange(a, b+1)
    339 
    340 

TypeError: can only concatenate str (not "int") to str</module> 

应用:

用户可以使用 randint()函数来模拟抽奖游戏。

假设我们参加了一个抽奖游戏,比如“赌场游戏”。玩家将有三次机会猜测 1 到 36 之间的数字。如果我们猜对了数字,我们就会赢,否则我们就会输。

示例:应用代码


# First, we will import the randint function
# from the random module in Python
from random import randint as rdt

# We will create a function which can generate a new 
# random number everytime the code will execute
def generator_1():
    return rdt(1, 36)

# Now, we will create a function which takes the input from the user and returns
# true or false depending whether the
# user has guessed the correct number and wins the lucky draw or not. 
def random_guess():

    # The calls generator_1() which returns a
    # random integer between 1 and 36
    random_number_1 = generator_1()

    # here, we will define the number of
    # guesses the user will get
    guess_left_1 = 3

    # now, we will set the flag variable for checking
    # the win-condition for the user
    flag_1 = 0

    # Then, we will loop the number of times
    # the user will get the chances
    while guess_left_1 > 0:

        # Here, we will take a input from the user.
        guess_1 = int (input ("Please select your number to "
                      "enter the lucky draw game \n"))

        # then, we will check whether the guess of the user 
        # matched the generated win-condition or not.
        if guess_1 == random_number_1:

            # Then, we will set the flag as 1 if the user have guessed
            # the correct number and then loop will broke
            flag_1 = 1
            break

        else:

            # If the guess of the user does not matched
            # the win-condition then it will print
            print ("You have guessed Wrong Number!!")

        # then, we will decrease the number of 
        # guesses left by 1 
        guess_left_1 -= 1

    # If the condition of winning is satisfied then,
    # the function random_guess will return "True"
    if flag_1 == 1:
        return True

    # Otherwise, the function will return "False"
    else:
        return False

# Driver code
if __name__ == '__main__':
    if random_guess() == True:
        print ("Congratulation!! You have Won the game.")
    else :
        print ("Sorry, You have Lost the game!")

输出:

1#

Please select your number to enter the lucky draw game 
 3
You have guessed Wrong Number!!
Please select your number to enter the lucky draw game 
 2
You have guessed Wrong Number!!
Please select your number to enter the lucky draw game 
 34
You have guessed Wrong Number!!
Sorry, you have Lost the game!

2#

Please select your number to enter the lucky draw game 
 14
You have guessed Wrong Number!!
Please select your number to enter the lucky draw game 
 12
You have guessed Wrong Number!!
Please select your number to enter the lucky draw game 
 3
Congratulation!! You have Won the game.

结论

在本教程中,我们讨论了 Python random模块的 randint()函数。我们已经展示了用户在使用 randint()函数时可能遇到的错误类型。我们还讨论了 randint()函数如何用于创建抽奖游戏的应用。


原创文章,作者:EDHRZ,如若转载,请注明出处:https://www.506064.com/n/317530.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
EDHRZEDHRZ
上一篇 2025-01-11 16:27
下一篇 2025-01-11 16:27

相关推荐

  • Python计算阳历日期对应周几

    本文介绍如何通过Python计算任意阳历日期对应周几。 一、获取日期 获取日期可以通过Python内置的模块datetime实现,示例代码如下: from datetime imp…

    编程 2025-04-29
  • 如何查看Anaconda中Python路径

    对Anaconda中Python路径即conda环境的查看进行详细的阐述。 一、使用命令行查看 1、在Windows系统中,可以使用命令提示符(cmd)或者Anaconda Pro…

    编程 2025-04-29
  • Python周杰伦代码用法介绍

    本文将从多个方面对Python周杰伦代码进行详细的阐述。 一、代码介绍 from urllib.request import urlopen from bs4 import Bea…

    编程 2025-04-29
  • Python中引入上一级目录中函数

    Python中经常需要调用其他文件夹中的模块或函数,其中一个常见的操作是引入上一级目录中的函数。在此,我们将从多个角度详细解释如何在Python中引入上一级目录的函数。 一、加入环…

    编程 2025-04-29
  • Python列表中负数的个数

    Python列表是一个有序的集合,可以存储多个不同类型的元素。而负数是指小于0的整数。在Python列表中,我们想要找到负数的个数,可以通过以下几个方面进行实现。 一、使用循环遍历…

    编程 2025-04-29
  • Python程序需要编译才能执行

    Python 被广泛应用于数据分析、人工智能、科学计算等领域,它的灵活性和简单易学的性质使得越来越多的人喜欢使用 Python 进行编程。然而,在 Python 中程序执行的方式不…

    编程 2025-04-29
  • python强行终止程序快捷键

    本文将从多个方面对python强行终止程序快捷键进行详细阐述,并提供相应代码示例。 一、Ctrl+C快捷键 Ctrl+C快捷键是在终端中经常用来强行终止运行的程序。当你在终端中运行…

    编程 2025-04-29
  • 蝴蝶优化算法Python版

    蝴蝶优化算法是一种基于仿生学的优化算法,模仿自然界中的蝴蝶进行搜索。它可以应用于多个领域的优化问题,包括数学优化、工程问题、机器学习等。本文将从多个方面对蝴蝶优化算法Python版…

    编程 2025-04-29
  • Python清华镜像下载

    Python清华镜像是一个高质量的Python开发资源镜像站,提供了Python及其相关的开发工具、框架和文档的下载服务。本文将从以下几个方面对Python清华镜像下载进行详细的阐…

    编程 2025-04-29
  • Python字典去重复工具

    使用Python语言编写字典去重复工具,可帮助用户快速去重复。 一、字典去重复工具的需求 在使用Python编写程序时,我们经常需要处理数据文件,其中包含了大量的重复数据。为了方便…

    编程 2025-04-29

发表回复

登录后才能评论