Home  >  Article  >  Backend Development  >  How to randomly generate odd numbers in python

How to randomly generate odd numbers in python

尚
Original
2020-01-15 13:54:2212325browse

How to randomly generate odd numbers in python

How to randomly generate odd numbers in python:

Implementation ideas:

1. You need to use the random module

2.Use The list is displayed to the user

3. Check whether the number is an odd number, and use the append method to write the odd random number into the list

4. In order to ensure that the number entered by the user can be entered For odd numbers with the same number of integers, choose to use the whlie structure

to implement the code:

import random    #导入random模块
NUM = int(input('请输入一个整数:'))  #提示用户输入一个整数
list1 = []                       #设置一个空列表用于展示用户需要的数据
while len(list1) < NUM:          #确保输出的数据是用户需要的个数,并循环输出
    a = random.randint(1,1000000)    #随机生成1-1000000之间的一个整数
    if a % 2 ==1:                #判断随机生成的数是否为奇数,如果为奇数执行下面的代码
        list1.append(a)          #向空列表中加入随机生成的奇数
print(list1)                     #向用户展示生成的奇数

python learning network, free online learning python platform, welcome to follow!

The above is the detailed content of How to randomly generate odd numbers in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn