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

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

off999 2024-12-20 17:55 15 浏览 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钩子函数实现事件驱动系统(created钩子函数)

钩子函数(HookFunction)是现代软件开发中一个重要的设计模式,它允许开发者在特定事件发生时自动执行预定义的代码。在Python生态系统中,钩子函数广泛应用于框架开发、插件系统、事件处理和中...

Python函数(python函数题库及答案)

定义和基本内容def函数名(传入参数):函数体return返回值注意:参数、返回值如果不需要,可以省略。函数必须先定义后使用。参数之间使用逗号进行分割,传入的时候,按照顺序传入...

Python技能:Pathlib面向对象操作路径,比os.path更现代!

在Python编程中,文件和目录的操作是日常中不可或缺的一部分。虽然,这么久以来,钢铁老豆也还是习惯性地使用os、shutil模块的函数式API,这两个模块虽然功能强大,但在某些情况下还是显得笨重,不...

使用Python实现智能物流系统优化与路径规划

阅读文章前辛苦您点下“关注”,方便讨论和分享,为了回馈您的支持,我将每日更新优质内容。在现代物流系统中,优化运输路径和提高配送效率是至关重要的。本文将介绍如何使用Python实现智能物流系统的优化与路...

Python if 语句的系统化学习路径(python里的if语句案例)

以下是针对Pythonif语句的系统化学习路径,从零基础到灵活应用分为4个阶段,包含具体练习项目和避坑指南:一、基础认知阶段(1-2天)目标:理解条件判断的逻辑本质核心语法结构if条件:...

[Python] FastAPI基础:Path路径参数用法解析与实例

查询query参数(上一篇)路径path参数(本篇)请求体body参数(下一篇)请求头header参数本篇项目目录结构:1.路径参数路径参数是URL地址的一部分,是必填的。路径参...

Python小案例55- os模块执行文件路径

在Python中,我们可以使用os模块来执行文件路径操作。os模块提供了许多函数,用于处理文件和目录路径。获取当前工作目录(CurrentWorkingDirectory,CWD):使用os....

python:os.path - 常用路径操作模块

应该是所有程序都需要用到的路径操作,不废话,直接开始以下是常用总结,当你想做路径相关时,首先应该想到的是这个模块,并知道这个模块有哪些主要功能,获取、分割、拼接、判断、获取文件属性。1、路径获取2、路...

原来如此:Python居然有6种模块路径搜索方式

点赞、收藏、加关注,下次找我不迷路当我们使用import语句导入模块时,Python是怎么找到这些模块的呢?今天我就带大家深入了解Python的6种模块路径搜索方式。一、Python模块...

每天10分钟,python进阶(25)(python进阶视频)

首先明确学习目标,今天的目标是继续python中实例开发项目--飞机大战今天任务进行面向对象版的飞机大战开发--游戏代码整编目标:完善整串代码,提供完整游戏代码历时25天,首先要看成品,坚持才有收获i...

python 打地鼠小游戏(打地鼠python程序设计说明)

给大家分享一段AI自动生成的代码(在这个游戏中,玩家需要在有限时间内打中尽可能多的出现在地图上的地鼠),由于我现在用的这个电脑没有安装sublime或pycharm等工具,所以还没有测试,有兴趣的朋友...

python线程之十:线程 threading 最终总结

小伙伴们,到今天threading模块彻底讲完。现在全面总结threading模块1、threading模块有自己的方法详细点击【threading模块的方法】threading模块:较低级...

Python信号处理实战:使用signal模块响应系统事件

信号是操作系统用来通知进程发生了某个事件的一种异步通信方式。在Python中,标准库的signal模块提供了处理这些系统信号的机制。信号通常由外部事件触发,例如用户按下Ctrl+C、子进程终止或系统资...

Python多线程:让程序 “多线作战” 的秘密武器

一、什么是多线程?在日常生活中,我们可以一边听音乐一边浏览新闻,这就是“多任务处理”。在Python编程里,多线程同样允许程序同时执行多个任务,从而提升程序的执行效率和响应速度。不过,Python...

用python写游戏之200行代码写个数字华容道

今天来分析一个益智游戏,数字华容道。当初对这个游戏颇有印象还是在最强大脑节目上面,何猷君以几十秒就完成了这个游戏。前几天写2048的时候,又想起了这个游戏,想着来研究一下。游戏玩法用尽量少的步数,尽量...

取消回复欢迎 发表评论: