百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

【Python】随机数和 列表 python3随机数

off999 2024-12-20 17:55 18 浏览 0 评论



Python 随机模块方法

randint(a, b):

返回介于 ab 之间(含两者)的随机整数。如果 a > b,这也会引发 ValueError

import random

random_int = random.randint(1,10)
print(random_int)

>>
PS \Python> python .\random_int.py
4
PS \Python> python .\random_int.py
10
PS \Python> python .\random_int.py
3

可以创建自己的模块并导入它。

#my_module.py

pi = 3.1415
#random_int.py

import random
import my_module

random_int = random.randint(1,10)
print(random_int)


print(my_module.pi)

>>
PS \Python> python .\random_int.py
8
3.1415

生成 Random 浮点数:

与生成整数类似,也有一些函数可以生成随机浮点序列。

  • random.random() -> 返回介于 [0.0 到 1.0] 之间的下一个随机浮点数
  • random.uniform(a, b) -> 返回一个随机浮点数 N,使得 a <= N <= b 如果 a <= b,b <= N <= a 如果 b < a。
  • random.随机。expovariate(lambda) -> 返回与指数分布对应的数字。
  • random.gauss(mu, sigma) -> 返回与高斯分布相对应的数字。

其他分布也有类似的函数,例如 Normal Distribution、Gamma Distribution 等。

import random


random_int = random.randint(1,10)
print(random_int)

random_flot =  random.random()
print(random_flot)

>>

1
0.041635438063850505

项目 1:爱情评分

import random
print("\n")
print("-------Welcome to Love Calculator-------\n")

name1 =  input("What is your name?\n")
name2 =  input("What is their name?\n")

love_score =  random.randint(1, 100)

print(f"Love score of {name1} and {name2} is {love_score}")

>>

-------Welcome to Love Calculator-------

What is your name?
Lisa
What is their name?
Jack
Love score of Lisa and Jack is 34

项目 2:正面或反面

import random

random_side =  random.randint(0, 1)

if random_side == 1:
    print ("Heads")
else:
    print("Tails")

>>

PS \Python> python.exe .\heads_tails.py
Tails
PS \Python> python.exe .\heads_tails.py
Heads

列表:

检查此列表 : 数据结构

fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
print(fruits[2])
print(fruits[-2])

>>

pear
apple
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
print(fruits[2])
print(fruits[-2])

fruits[2] =  "Cheery"   #CHNAGE NAME
print(fruits)

>>

pear
apple
['orange', 'apple', 'Cheery', 'banana', 'kiwi', 'apple', 'banana']

可以将其附加到列表中:

fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']

fruits.append("Nid")
print(fruits)

>>
['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana', 'Nid']

扩展列表:

fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']

fruits.extend(["AP", "gy"])
print(fruits)

>>
['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana', 'Nid', 'AP', 'gy']    

检查列表的长度

fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']

print(len(fruits))

项目 3:谁来支付

names =  input("Enter the names\n")

name_list = names.split(", ")

import random

num_item = len(names)

random_choice = random.randint(0, num_item - 1)
print(names[random_choice])

嵌套列表

fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
vegetables = ['Beetroot', 'Carrots', 'Capsicum', 'Ginger', 'Cauliflower']

fridge = [fruits, vegetables]
print(fridge)

>>

[['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'], ['Beetroot', 'Carrots', 'Capsicum', 'Ginger', 'Cauliflower']]

项目 4:藏宝图

line1 = [" ", " "," "]
line2 = [" ", " "," "]
line3 = [" ", " "," "]
map = [line1, line2, line3]

print("\nHiding your treasure! X marks the spot.")
print("There are three rows and coloumes\n")


postion = input("Where do you want to put the treasure?")

letter = postion[0].lower()

abc = ["a", "b", "c"] #Possiable entry 

letter_index = abc.index(letter) 
#Checking if in "letter" (we entry), that is  there in the list or not 
#This will give us number

number_index = int(postion[1]) - 1 
#Whatever position we entered, -1 because list stars from [0]

map[number_index][letter_index] = "X"

print(f"{line1}\n{line2}\n{line3}")
   


>>


Hiding your treasure! X marks the spot.
There are three rows and coloumes

Where do you want to put the treasure?B3
[' ', ' ', ' ']
[' ', ' ', ' ']
[' ', 'X', ' ']

项目 5:石头剪刀布游戏

import random

rock = '''
    _______
---'   ____)
      (_____)
      (_____)
      (____)
---.__(___)
'''

paper = '''
    _______
---'   ____)____
          ______)
          _______)
         _______)
---.__________)
'''

scissors = '''
    _______
---'   ____)____
          ______)
       __________)
      (____)
---.__(___)
'''


game_images = [rock, paper, scissors]
user_choice = int(input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors.\n"))

if user_choice >= 3 or user_choice < 0: 
    print("Number is Invalid, You lose!")

else:
    print(game_images[user_choice])

    computer_choice = random.randint(0, 2)

    print("Compute Choose:")
    print(game_images[computer_choice])

    if user_choice == computer_choice:
        print ("It's a tie!")
    elif (user_choice == 0 and computer_choice == 2) or \
         (user_choice == 1 and computer_choice == 0) or \
         (user_choice == 2 and computer_choice == 1):
        print ("You win!")
    else:
        print ("You lose!")


>>

What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors.
2

    _______
---'   ____)____
          ______)
       __________)
      (____)
---.__(___)

Compute Choose:

    _______
---'   ____)____
          ______)
       __________)
      (____)
---.__(___)

It's a tie!

相关推荐

Python四种常用的高阶函数,你会用了吗

每天进步一点点,关注我们哦,每天分享测试技术文章本文章出自【码同学软件测试】码同学公众号:自动化软件测试码同学抖音号:小码哥聊软件测试1、什么是高阶函数把函数作为参数传入,这样的函数称为高阶函数例如:...

Python之函数进阶-函数加强(上)(python函数的作用增强代码的可读性)

一.递归函数递归是一种编程技术,其中函数调用自身以解决问题。递归函数需要有一个或多个终止条件,以防止无限递归。递归可以用于解决许多问题,例如排序、搜索、解析语法等。递归的优点是代码简洁、易于理解,并...

数据分析-一元线性回归分析Python

前面几篇介绍了数据的相关性分析,通过相关性分析可以看出变量之间的相关性程度。如果我们已经发现变量之间存在明显的相关性了,接下来就可以通过回归分析,计算出具体的相关值,然后可以用于对其他数据的预测。本篇...

python基础函数(python函数总结)

Python函数是代码复用的核心工具,掌握基础函数的使用是编程的关键。以下是Python函数的系统总结,包含内置函数和自定义函数的详细用法,以及实际应用场景。一、Python内置函数(...

python进阶100集(9)int数据类型深入分析

一、基本概念int数据类型基本上来说这里指的都是整形,下一届我们会讲解整形和浮点型的转化,以及精度问题!a=100b=a这里a是变量名,100就是int数据对象,b指向的是a指向的对象,...

Python学不会来打我(73)python常用的高阶函数汇总

python最常用的高阶函数有counter(),sorted(),map(),reduce(),filter()。很多高阶函数都是将一个基础函数作为第一个参数,将另外一个容器集合作为第二个参数,然...

python中有哪些内置函数可用于编写数值表达式?

在Python中,用于编写数值表达式的内置函数很多,它们可以帮助你处理数学运算、类型转换、数值判断等。以下是常用的内置函数(不需要导入模块)按类别归类说明:一、基础数值处理函数函数作用示例ab...

如何在Python中获取数字的绝对值?

Python有两种获取数字绝对值的方法:内置abs()函数返回绝对值。math.fabs()函数还返回浮点绝对值。abs()函数获取绝对值内置abs()函数返回绝对值,要使用该函数,只需直接调用:a...

【Python大语言模型系列】使用dify云版本开发一个智能客服机器人

这是我的第359篇原创文章。一、引言上篇文章我们介绍了如何使用dify云版本开发一个简单的工作流:【Python大语言模型系列】一文教你使用dify云版本开发一个AI工作流(完整教程)这篇文章我们将引...

Python3.11版本使用thriftpy2的问题

Python3.11于2022年10月24日发布,但目前thriftpy2在Python3.11版本下无法安装,如果有使用thriftpy2的童鞋,建议晚点再升级到最新版本。...

uwsgi的python2+3多版本共存(python多版本兼容)

一、第一种方式(virtualenv)1、首先,机器需要有python2和python3的可执行环境。确保pip和pip3命令可用。原理就是在哪个环境下安装uwsgi。uwsgi启动的时候,就用的哪个...

解释一下Python脚本中版本号声明的作用

在Python脚本中声明版本号(如__version__变量)是一种常见的元数据管理实践,在IronPython的兼容性验证机制中具有重要作用。以下是版本号声明的核心作用及实现原理:一、版本号...

除了版本号声明,还有哪些元数据可以用于Python脚本的兼容性管理

在Python脚本的兼容性管理中,除了版本号声明外,还有多种元数据可以用于增强脚本与宿主环境的交互和验证。以下是一些关键的元数据类型及其应用场景:一、环境依赖声明1.Python版本要求pyth...

今年回家没票了?不,我有高科技抢票

零基础使用抢票开源软件Py12306一年一度的抢票季就要到了,今天给大家科普一下一款软件的使用方法。软件目前是开源的,禁止用于商用。首先需要在电脑上安装python3.7,首先从官网下载对应的安装包,...

生猛!春运抢票神器成GitHub热榜第一,过年回家全靠它了

作者:车栗子发自:凹非寺量子位报道春节抢票正在如火如荼的进行,过年回家那肯定需要抢票,每年的抢票大战,都是一场硬战,没有一个好工具,怎么能上战场死锁呢。今天小编推荐一个Python抢票工具,送到...

取消回复欢迎 发表评论: