第 12 天
模块
什么是模块
模块是包含一组代码或一组功能的文件,可以包含在应用程序中。模块可以是包含单个变量、函数或大型代码库的文件。
创建模块
为了创建一个模块,我们在 python 脚本中编写代码并将其保存为 .py 文件。在项目文件夹中创建一个名为 mymodule.py 的文件。让我们在这个文件中写一些代码。
# mymodule.py file
def generate_full_name(firstname, lastname):
return firstname + ' ' + lastname
在项目目录中创建 main.py 文件并导入 mymodule.py 文件。
导入模块
要导入文件,我们仅使用import关键字和文件名。
# main.py file
import mymodule
print(mymodule.generate_full_name('Asabeneh', 'Yetayeh')) # Asabeneh Yetayeh
从模块导入函数
我们可以在一个文件中有很多函数,我们可以以不同的方式导入所有函数。
# main.py file
from mymodule import generate_full_name, sum_two_nums, person, gravity
print(generate_full_name('Asabneh','Yetayeh'))
print(sum_two_nums(1,9))
mass = 100;
weight = mass * gravity
print(weight)
print(person['firstname'])
从模块导入函数并重命名
在导入过程中,我们可以重命名模块的名称。
# main.py file
from mymodule import generate_full_name as fullname, sum_two_nums as total, person as p, gravity as g
print(fullname('Asabneh','Yetayeh'))
print(total(1, 9))
mass = 100;
weight = mass * g
print(weight)
print(p)
print(p['firstname'])
导入内置模块
与其他编程语言一样,我们也可以通过使用关键字import导入文件/函数来导入模块。让我们导入我们大部分时间都会使用的公共模块。一些常见的内置模块:math、datetime、os、sys、random、statistics、collections、json、re
操作系统模块
使用 python os模块可以自动执行许多操作系统任务。Python 中的 OS 模块提供了创建、更改当前工作目录、删除目录(文件夹)、获取其内容、更改和识别当前目录的功能。
# import the module
import os
# Creating a directory
os.mkdir('directory_name')
# Changing the current directory
os.chdir('path')
# Getting current working directory
os.getcwd()
# Removing directory
os.rmdir()
系统模块
sys 模块提供了用于操作 Python 运行时环境的不同部分的函数和变量。函数 sys.argv 返回传递给 Python 脚本的命令行参数列表。此列表中索引 0 处的项目始终是脚本的名称,索引 1 处的项目是从命令行传递的参数。
script.py 文件示例:
import sys
#print(sys.argv[0], argv[1],sys.argv[2]) # this line would print out: filename argument1 argument2
print('Welcome {}. Enjoy {} challenge!'.format(sys.argv[1], sys.argv[2]))
现在检查这个脚本是如何工作的,我在命令行中写了:
python script.py Asabeneh 30DaysOfPython
结果:
Welcome Asabeneh. Enjoy 30DayOfPython challenge!
一些有用的系统命令:
# to exit sys
sys.exit()
# To know the largest integer variable it takes
sys.maxsize
# To know environment path
sys.path
# To know the version of python you are using
sys.version
统计模块
统计模块提供数值数据的数理统计功能。此模块中定义的流行统计函数:mean、median、mode、stdev等。
from statistics import * # importing all the statistics modules
ages = [20, 20, 4, 24, 25, 22, 26, 20, 23, 22, 26]
print(mean(ages)) # ~22.9
print(median(ages)) # 23
print(mode(ages)) # 20
print(stdev(ages)) # ~2.3
数学模块
包含许多数学运算和常量的模块。
import math
print(math.pi) # 3.141592653589793, pi constant
print(math.sqrt(2)) # 1.4142135623730951, square root
print(math.pow(2, 3)) # 8.0, exponential function
print(math.floor(9.81)) # 9, rounding to the lowest
print(math.ceil(9.81)) # 10, rounding to the highest
print(math.log10(100)) # 2, logarithm with 10 as base
现在,我们已经导入了math模块,其中包含许多可以帮助我们进行数学计算的函数。要检查模块有哪些功能,我们可以使用help(math)或dir(math)。这将显示模块中的可用功能。如果我们只想从模块中导入一个特定的函数,我们可以按如下方式导入它:
from math import pi
print(pi)
也可以一次导入多个函数
from math import pi, sqrt, pow, floor, ceil, log10
print(pi) # 3.141592653589793
print(sqrt(2)) # 1.4142135623730951
print(pow(2, 3)) # 8.0
print(floor(9.81)) # 9
print(ceil(9.81)) # 10
print(math.log10(100)) # 2
但是如果我们想导入数学模块中的所有函数,我们可以使用 * 。
from math import *
print(pi) # 3.141592653589793, pi constant
print(sqrt(2)) # 1.4142135623730951, square root
print(pow(2, 3)) # 8.0, exponential
print(floor(9.81)) # 9, rounding to the lowest
print(ceil(9.81)) # 10, rounding to the highest
print(math.log10(100)) # 2
当我们导入时,我们还可以重命名函数的名称。
from math import pi as PI
print(PI) # 3.141592653589793
字符串模块
字符串模块是一个有多种用途的有用模块。下面的示例显示了 string 模块的一些用法。
import string
print(string.ascii_letters) # abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
print(string.digits) # 0123456789
print(string.punctuation) # !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
随机模块
到目前为止,您已经熟悉了导入模块。让我们再导入一次以熟悉它。让我们导入random模块,它给我们一个介于 0 和 0.9999 之间的随机数...... random模块有很多功能,但在本节中我们将只使用random和randint。
from random import random, randint
print(random()) # it doesn't take any arguments; it returns a value between 0 and 0.9999
print(randint(5, 20)) # it returns a random integer number between [5, 20] inclusive
🌕你走得很远。继续前进!您刚刚完成了第 12 天的挑战,您已经迈出了通往卓越之路的 12 步。现在为你的大脑和肌肉做一些练习。
练习:第 12 天
练习:1级
- 编写一个生成六位数字/字符 random_user_id 的函数。
print(random_user_id()); '1ee33d'
- 修改之前的任务。声明一个名为 user_id_gen_by_user 的函数。它不接受任何参数,但使用 input() 接受两个输入。其中一个输入是字符数,第二个输入是应该生成的 ID 数。
print(user_id_gen_by_user()) # user input: 5 5 #output: #kcsy2 #SMFYb #bWmeq #ZXOYh #2Rgxf print(user_id_gen_by_user()) # 16 5 #1GCSgPLMaBAVQZ26 #YD7eFwNQKNs7qXaT #ycArC5yrRupyG00S #UbGxOFI7UXSWAyKN #dIV0SSUTgAdKwStr
- 编写一个名为 rgb_color_gen 的函数。它将生成 rgb 颜色(3 个值,每个值从 0 到 255)。
print(rgb_color_gen()) # rgb(125,244,255) - the output should be in this form
练习:2级
- 编写一个函数 list_of_hexa_colors ,它返回数组中任意数量的十六进制颜色(# 后面写的六个十六进制数字。十六进制数字系统由 16 个符号组成,0-9 和字母表的前 6 个字母,af。检查任务 6输出示例)。
- 编写一个函数 list_of_rgb_colors ,它返回数组中任意数量的 RGB 颜色。
- 编写一个函数 generate_colors 可以生成任意数量的六色或 rgb 颜色。
generate_colors('hexa', 3) # ['#a3e12f','#03ed55','#eb3d2b'] generate_colors('hexa', 1) # ['#b334ef'] generate_colors('rgb', 3) # ['rgb(5, 55, 175','rgb(50, 105, 100','rgb(15, 26, 80'] generate_colors('rgb', 1) # ['rgb(33,79, 176)']
练习: 3级
- 调用你的函数 shuffle_list,它将一个列表作为参数并返回一个随机列表
- 编写一个函数,返回一个由 0-9 范围内的七个随机数组成的数组。所有数字必须是唯一的。
🎉恭喜!🎉