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

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

off999 2024-12-20 17:55 13 浏览 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!

相关推荐

独家 | 5 个Python高级特性让你在不知不觉中成为Python高手

你已经使用Python编程了一段时间,编写脚本并解决各种问题。是你的水平出色吗?你可能只是在不知不觉中利用了Python的高级特性。从闭包(closure)到上下文管理器(contextmana...

Python装饰器

Python装饰器是一种用于修改函数或类的行为的特殊语法。它们允许在不修改原始代码的情况下,通过将函数或类作为参数传递给另一个函数来添加额外的功能。装饰器本质上是一个函数,它接受一个函数作为参数,并返...

中高阶Python常规用法--上下文管理器

Python以简单性和通用性著称,是一种深受全球开发人员喜爱的编程语言。它提供了大量的特性和功能,使编码成为一种愉快的体验。在这些功能中,一个经常被新手忽视的强大工具是上下文管理器。上下文管理器是高...

Python小案例67- 装饰器

Python装饰器是一种用于修改函数或类的行为的特殊语法。它们允许在不修改原始代码的情况下,通过将函数或类作为参数传递给另一个函数来添加额外的功能。装饰器本质上是一个函数,它接受一个函数作为参数,并返...

python常用的语法糖

概念Python的语法糖(SyntacticSugar)是指那些让代码更简洁、更易读的语法特性,它们本质上并不会增加新功能,但能让开发者更高效地编写代码。推导式写法推导式是Python最经典的...

python - 常用的装饰器 decorator 有哪些?

python编程中使用装饰器(decorator)工具,可以使代码更简洁清晰,提高代码的重用性,还可以为代码维护提供方便。对于python初学者来说,根据装饰器(decorator)的字面意思并不...

python数据缓存怎么搞 ?推荐一个三方包供你参考,非常简单好用。

1.数据缓存说明数据缓存可以说也是项目开发中比不可少的一个工具,像我们测试的系统中,你都会见到像Redis一样的数据缓存库。使用缓存数据库的好处不言而喻,那就是效率高,简单数据直接放在缓存中...

用于时间序列数据的Graphite监视工具

结合第三方工具,Graphite为IT性能监控提供了许多好处。本文介绍其核心组件,包括Carbon、Whisper以及安装的基本准则。Graphite监视工具可实时或按需,大规模地绘制来自多个来源的时...

Python3+pygame实现的坦克大战

一、显示效果二、代码1.说明几乎所有pygame游戏,基本都遵循一定的开发流程,大体如下:初始化pygame创建窗口while循环检测以及处理事件(鼠标点击、按键等)更新UI界面2.代码创建一个m...

Python之鸭子类型:一次搞懂with与上下文装饰器

引言在鸭子类型的理念的基础之上,从关注类型,转变到关注特性和行为。结合Python中的魔法函数的体系,我们可以将自定义的类型,像内置类型一样被使用。今天这篇文章中,接着该话题,继续聊一下with语法块...

Python必会的50个代码操作

学习Python时,掌握一些常用的程序操作非常重要。以下是50个Python必会的程序操作,主要包括基础语法、数据结构、函数和文件操作等。1.HelloWorldprint("Hello,...

一文掌握Python 中的同步和异步

同步代码(Sync)同步就像在一个流水线上工作,每个任务都等待前一个任务完成。示例:机器A切割钢板→完成后,机器B钻孔→完成后,机器C上色。在Python中,同步代码看起来像这样:im...

python 标注模块timeit: 测试函数的运行时间

在Python中,可以使用内置的timeit模块来测试函数的运行时间。timeit模块提供了一个简单的接口来测量小段代码的执行时间。以下是使用timeit测试函数运行时间的一般步骤:导入...

Python带你找回童年的万花尺

还记得小时候的万花尺吧?这么画:一点也不费脑筋,就可以出来这么多丰富多彩的复杂几何图形。具体而言,可以用万花尺玩具(如图2-1所示)来绘制数学曲线。这种玩具由两个不同尺寸的塑料齿轮组成,一大一小。小的...

Python 时间模块深度解析:从基础到高级的全面指南

直接上干货一、时间模块核心类介绍序号类名说明1datetime.datetime表示一个具体的日期和时间,结合了日期和时间的信息。2datetime.date表示一个具体的日期。3datetime.t...

取消回复欢迎 发表评论: