首页 > 其他分享 >CS50P: 4. Libraries

CS50P: 4. Libraries

时间:2024-07-15 11:18:23浏览次数:17  
标签:sys random argv Libraries CS50P print import hello

libraries, modules

libraries are bits of code written by you or others we can use in our program

Python allows us to share functions or features with others as "modules"

random

python: random

random is a library that comes with Python that we could import into our own project

we need keyword import

import

作用

import the contents of the functions from some module

使用random模块中的函数

import random
coin = random.choice(["heads", "tails"])
print(coin)

random is the module we are importing. Inside that module, there is the choice function -- random.choice(seq)

参数:list

返回值:list中的随机一个元素

from

from: allows us to be very specific about what we’d like to import

import: bringing the entire contents of the functions of a module

from random import choice
coin = choice(["heads", "tails"])

注:使用时直接用函数名

functions

random.randint(a, b)

return random int in [a,b] 区间

random.shuffle(x)

shuffle a list into a random order

注意:没有返回,而是直接作用于list

statistics

python: statistics

mean function

print(statistics.mean([100, 90]))

接收列表,返回平均值

Command-Line Arguments

take input from the command-line命令行参数

sys

a module that allows us to take arguments at the command line

python: sys

argv

a function within the sys module

import sys
print("hello, my name is", sys.argv[1])
  • sys.argv是一个list

  • 命令行输入 python3 sys.py chase

  • sys.argv[0] 是 sys.py

  • "chase tsai" 视作一个命令(加了引号)

IndexError

如果使用命令 python3 sys.py,返回 IndexError: list index out of range

改进

way 1

try:
    print("hello, my name is", sys.argv[1])
except IndexError:
    print("Too few arguments")

way 2

if len(sys.argv) < 2:
    print("Too few arguments")
elif len(sys.argv) > 2:
    print("Too many arguments")
else:
    print("hello, my name is", sys.argv[1])

sys.exit()

exit the program if an error was introduced by the user

if len(sys.argv) < 2:
    sys.exit("Too few arguments")

常常用来结束整个程序

slice

To take a slice of a list means to take a subset of it

for arg in sys.argv[1:]:
    print("hello, my name is", arg)
  • : 必须有

  • sys.argv[1:-2] 表示取左一到右二之间的子序列

packages

One of the reasons Python is so popular is that there are numerous powerful third-party libraries that add functionality. We call these third-party libraries, implemented as a folder, "packages".

find other third-party packages at PyPI

learn more on PyPI’s entry for cowsay: a well-known package that allows a cow to talk to the user

pip

install packages quickly onto your system

APIs

APIs or “application program interfaces” allow you to connect to the code of others

requests

python: library’s documentation.

requests is a package that allows our program to behave as a web browser would

import requests
import sys

if len(sys.argv) != 2:
    sys.exit()
    
"""
looking for a song, with a limit of one result, that relates to the term called weezer
"""
response = requests.get("https://itunes.apple.com/search?entity=song&limit=1&term=" + sys.argv[1])	
print(response.json())

第10行是把python连接到浏览器,就像我们在Safari中输入urls,按enter键

Apple documentation about this API: what is returned is a JSON file. Running python3 itunes.py weezer, you will see the JSON file returned by Apple.

However, the JSON response is converted by Python into a dictionary!!!

JSON

python的一个库

功能:manipulate JSON data, nicely printing on the screen

python: JSON.

应用样例

修改上例代码

import requests
import sys
import json

if len(sys.argv) != 2:
    sys.exit()
response = requests.get("https://itunes.apple.com/search?entity=song&limit=1&term=" + sys.argv[1])
print(json.dumps(response.json(), indent=2))

进一步观察,删除 &limit=1 并插入代码:

o = response.json()
for result in o["results"]:
    print(result["trackName"])

会得到所有的trackName:

Making Our Own Libraries

sayings.py

def main():
    hello("world")
    goodbye("world")
    
def hello(name):
    print(f"hello, {name}")

def goodbye(name):
    print(f"goodbye, {name}")

main()

say.py

import sys
from sayings import hello
if len(sys.argv) == 2:
    hello(sys.argv[1])

sayings.py是我们自己写的module,用 from sayings import hello ,python会知道是在saying.py中找hello函数,然后执行它以下的所有代码

运行

命令行 python3 say.py chase

hello, world
goodbye, world
hello, chase

_name_

只想输出 hello, xxx ,解决方法:

if __name__ == "__main__":
    main()

__name__ 是特殊变量,python将它自动设置成 "__main__" 当在command line运行该程序,本例中即 python3 sayings.py 。而我们在command line只运行了say.py程序,sayings.py程序只是import的,所以 __name__ 没有自动初始化,不会被执行

标签:sys,random,argv,Libraries,CS50P,print,import,hello
From: https://www.cnblogs.com/chasetsai/p/18302177

相关文章

  • CS50P: 2. Loops
    control+C终止循环while循环#meow3timesi=0whilei<3:print("meow")i+=1 #python中没有i++for循环foriin[0,1,2]:print("meow")i初始为1,依次取2、3in可以让i按序取遍list中的元素,其中元素可以是int,dict,str,etc.for_in......
  • CS50P: 1. Conditionals
    运算符python中有>=和<=,其余和C一样python支持90<=score<=100CPython||or&and布尔运算TrueorFalse选择语句ififx<y:print("xislessthany")ifx>y:print("xisgreaterthany")ifx==y:......
  • 乌班图Ubuntu 24.04初始化MySQL报错error while loading shared libraries: libaio.so
    由于乌班图24.04LTS已经发布了,因此准备新业务逐步往这上面迁移,毕竟支持有效期比22.04更长准备在24.04上进行MySQL的初始化,因为习惯自定义安装存储目录,所以使用mysql-8.0.37-linux-glibc2.28-x86_64.tar.xz这个最新的二进制版本。按照22.04版本整理的安装笔记进行操作,第一步安装......
  • 062篇 - 实用的库和框架(Useful Libraries and Frameworks)
    大家好,我是元壤教育的张涛,一名知识博主,专注于生成式人工智能(AIGC)各领域的研究与实践。我喜欢用简单的方法,帮助大家轻松掌握AIGC应用技术。我的愿景是通过我的文章和教程,帮助1000万人学好AIGC,用好AIGC。在本章中,我们将探讨一系列能够显著提高提示词工程师工作效率的实用库......
  • Vitis Accelerated Libraries 学习笔记--OpenCV 安装指南
    目录1.简介2.安装过程2.1安装准备2.2常见错误2.2.1核心共享库报错3.通过实例测试 4.总结1.简介使用VitisVisionLibraryVitis视觉库,为什么要安装opencv库?在使用VitisVisionLibrary时,安装OpenCV库是因为许多视觉库的功能都提供了示例设计测试平台,使用......
  • Vitis HLS 学习笔记--Vitis Accelerated Libraries介绍
    目录1.简介2.库的组织结构 2.1结构级别L1/L2/L32.2文件内容3.分类介绍3.1 blas3.2codec3.3 data_analytics3.4 data_compression3.5 data_mover3.6 database3.7 dsp3.8graph3.9 hpc3.10 motor_control3.11 quantitative_finance3.12 securi......
  • idea 项目更改jdk版本后,External Libraries中jdk仍为旧版本
    根据网上搜索,修改Preferences、pom.xml、mavensettings.xml中的jdk版本后,发现ExternalLibraries中jdk仍为旧版本。表示仍旧有漏修改的地方。File->ProjectStructure   ProjectSettings->Project中SDK和LanguageLevel都需要修改  Project Settings->......
  • error while loading shared libraries: libgsl.so.27: cannot open shared object
     001、问题(base)[root@pc1src]#treemixtreemix:errorwhileloadingsharedlibraries:libgsl.so.27:cannotopensharedobjectfile:Nosuchfileordirectory 002、查找该共享库(base)[root@pc1src]#find/-name"libgsl.so.27"##说明已经安......
  • linux puppeteer 截图提示缺少chrome-linux/chrome error while loading shared libra
    puppeteer/.local-chromium/linux-1002410/chrome-linux/chrome:errorwhileloadingsharedlibraries:libXdamage.so.1:cannotopensharedobjectfile:Nosuchfileordirectory按照错误对照进行安装执行,缺啥安啥......
  • 推荐 10 个非常有用的 Golang Libraries
    推荐10个非常有用的GolangLibraries原创 GoOfficialBlog GoOfficialBlog 2024-03-2518:16 山东 听全文Go语言的标准库非常好用。通常情况下,你不需要任何额外的库来完成任务。但是在某些情况下,可能需要使用一些库。今天将与你分享日常工作中很有用的10个......