Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to generate numbers randomly in Python

Shulou Source: shulou.com Published: 2022-06-02 07:14:36 10月02日 Update

Python how to randomly generate numbers, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.

Step 1: install the random library

The random library is a Python standard library that uses random numbers.

You can enter CMD by WIN + R and enter the code at the command prompt

Pip install random

Step two

Now you can start writing code and import random

Import random

Use def to start the function definition, followed by the function name, inside the parentheses are the parameters of the function, and inside are the function implementation code

Def number (): # randomly select 5 digits from 1 to 100 number = random.sample ([b for b in range (1100)], 5) return number

Final output

A = number () print (a)

Run the code, and the effect is as follows

To an upgraded version, write a two-color ball generation code

Let's start with six red number balls

Import randomdef number (): # six red balls randomly selected from No.1-33 blue = random.sample ([b for b in range (1Magne33)], 6)

Blue number ball

# randomly select a red ball from No.1-16 red = random.choice ([r for r in range (1Magne17)]) blue.append (red) return blue

Output

A = number () print (a)

Running result

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Tags: Code function red number generation number help input output run clear content function parameter two-color two-color ball command for this parentheses prompt Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn OPPO Reno NVidia Shulou Information Huawei