 # randint() Function in Python

## randint() Function in Python

randint() is an inbuilt function of the random module in Python3. The random module gives access to various useful functions and one of them being able to generate random numbers, which is randint().

Syntax :

`randint(start, end)`

Parameters :

`(start, end) : Both of them must be integer type values.`

Returns :

`A random integer in range [start, end] including the end points.`

Errors and Exceptions :

```ValueError : Returns a ValueError when floating
point values are passed as parameters.

TypeError : Returns a TypeError when anything other than
numeric values are passed as parameters.```

Code #1 :

 `# Python3 program explaining work` `# of randint() function` ` ` `# imports random module` `import` `random` ` ` `# Generates a random number between` `# a given positive range` `r1 ``=` `random.randint(``0``, ``10``)` `print``(``"Random number between 0 and 10 is % s"` `%` `(r1))` ` ` `# Generates a random number between ` `# two given negative range` `r2 ``=` `random.randint(``-``10``, ``-``1``)` `print``(``"Random number between -10 and -1 is % d"` `%` `(r2))` ` ` `# Generates a random number between ` `# a positive and a negative range` `r3 ``=` `random.randint(``-``5``, ``5``)` `print``(``"Random number between -5 and 5 is % d"` `%` `(r3))`

Output :

```Random number between 0 and 10 is 5
Random number between -10 and -1 is -7
Random number between -5 and 5 is 2
```

Code #2 : Program demonstrating the ValueError.

 `# imports random module` `import` `random` ` ` `'''If we pass floating point values as` `parameters in the randint() function'''` ` ` `r1 ``=` `random.randint(``1.23``, ``9.34``)` `print``(r1)`

Output :

```Traceback (most recent call last):
r1=random.randint(1.23, 9.34)
File "/usr/lib/python3.5/random.py", line 218, in randint
return self.randrange(a, b+1)
File "/usr/lib/python3.5/random.py", line 182, in randrange
raise ValueError("non-integer arg 1 for randrange()")
ValueError: non-integer arg 1 for randrange()
```

Code #3 : Program demonstrating the TypeError.

 `# imports random` `import` `random` ` ` `'''If we pass string or character literals as` `parameters in the randint() function'''` ` ` `r2 ``=` `random.randint(``'a'``, ``'z'``)` `print``(r2)`

Output :

```Traceback (most recent call last):
File "/home/fb805b21fea0e29c6a65f62b99998953.py", line 5, in
r2=random.randint('a', 'z')
File "/usr/lib/python3.5/random.py", line 218, in randint
return self.randrange(a, b+1)
TypeError: Can't convert 'int' object to str implicitly
```

Applications :

The randint() function can be used to simulate a lucky draw situation.

Let’s say User has participated in a lucky draw competition. The user gets three chances to guess the number between 1 and 10. If guess is correct user wins, else loses the competition.

 `# importing randint function` `# from random module` `from` `random ``import` `randint` ` ` `# Function which generates a new ` `# random number everytime it executes` `def` `generator():` `    ``return` `randint(``1``, ``10``)` `     ` `# Function takes user input and returns` `# true or false depending whether the` `# user wins the lucky draw!` `def` `rand_guess():` ` ` `    ``# calls generator() which returns a` `    ``# random integer between 1 and 10` `    ``random_number ``=` `generator()` `     ` `    ``# defining the number of` `    ``# guesses the user gets` `    ``guess_left ``=` `3` ` ` `    ``# Setting a flag variable to check` `    ``# the win-condition for user` `    ``flag ``=` `0` ` ` `    ``# looping the number of times` `    ``# the user gets chances` `    ``while` `guess_left > ``0``:` ` ` `        ``# Taking a input from the user` `        ``guess ``=` `int``(``input``(``"Pick your number to "` `                      ``"enter the lucky draw\n"``))` ` ` `        ``# checking whether user's guess` `        ``# matches the generated win-condition` `        ``if` `guess ``=``=` `random_number:` ` ` `            ``# setting flag as 1 if user guessses ` `            ``# correctly and then loop is broken` `            ``flag ``=` `1` `            ``break` `         ` `        ``else``:` `             ` `            ``# If user's choice doesn't match` `            ``# win-condition then it is printed` `            ``print``(``"Wrong Guess!!"``)` ` ` `        ``# Decrementing number of ` `        ``# guesses left by 1 ` `        ``guess_left ``-``=` `1` ` ` `    ``# If win-condition is satisfied then,` `    ``# the function rand_guess returns True` `    ``if` `flag ``is` `1``:` `        ``return` `True` ` ` `    ``# Else the function returns False` `    ``else``:` `        ``return` `False` ` ` `# Driver code` `if` `__name__ ``=``=` `'__main__'``:` `    ``if` `rand_guess() ``is` `True``:` `        ``print``(``"Congrats!! You Win."``)` `    ``else` `:` `        ``print``(``"Sorry, You Lost!"``)`

Output :

```Pick your number to enter the lucky draw
8
Wrong Guess!!
Pick your number to enter the lucky draw
9
Wrong Guess!!
Pick your number to enter the lucky draw
0
Congrats!! You Win.
```

Last Updated on October 25, 2021 by admin

## Writing data from a Python List to CSV row-wiseWriting data from a Python List to CSV row-wise

Writing data from a Python List to CSV row-wise Comma Separated Values (CSV) files a type of a plain text document in which tabular information is structured using a particular format.  A CSV file is a bounded text format which uses a

## Get UTC timestamp in PythonGet UTC timestamp in Python

Get UTC timestamp in Python Datetime module supplies classes to work with date and time. These classes provide a number of functions to deal with dates, times and time intervals. Date and datetime are an object in Python, so when you

## Hotel Management Project in PythonHotel Management Project in Python

Hotel Management Project in Python This Project on Hotel Management is a general software developed (using Python) to simplify hotel operations by automating them. In this project, “AnCasa” is the project’s hotel name. It covers major aspects of hotel management;

## Pandas DataFrame.fillna() to replace Null values in dataframePandas DataFrame.fillna() to replace Null values in dataframe

Pandas DataFrame.fillna() to replace Null values in dataframe Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, and makes importing and analyzing data much

## Python – Single and Double QuotesPython – Single and Double Quotes

Single and Double Quotes | Python Python string functions are very popular. There are two ways to represent strings in python. String is enclosed either with single quotes or double quotes. Both the ways (single or double quotes) are correct

## Pandas dataframe.insert() – PythonPandas dataframe.insert() – Python

Pandas insert method allows the user to insert a column in a dataframe or series(1-D Data frame). A column can also be inserted manually in a data frame by the following method, but there isn’t much freedom here. For example,

## How to get rows/index names in Pandas dataframeHow to get rows/index names in Pandas dataframe

In a Pandas DataFrame, the rows or index names represent the labels assigned to each row. It can be useful to extract or work with these row names for various data manipulation tasks. In this article, we will explore different

## File Objects in PythonFile Objects in Python

File Objects in Python A file object allows us to use, access and manipulate all the user accessible files. One can read and write any such files. When a file operation fails for an I/O-related reason, the exception IOError is