CS50P week4 libraries

Lecture 4 - CS50’s Introduction to Programming with Python (harvard.edu)

Notes

random

import random

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

cards = ["jack", "queen", "king"]
# 没有返回值,但是会打乱list中的顺序
random.shuffle(cards)
for card in cards:
    print(card)

注意:

  • random.choice()括号中接的是list

sys

import sys

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

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

cowsay

import cowsay
import sys

if len(sys.argv) == 2:
    cowsay.cow("hello, " + sys.argv[1])

注意:

  • sys.argv[0]是文件名,sys.argv[i](i!=0)表示用户在命令行最开始输入的文件名后面的字符串,以空格为分界

API

import json
import sys
import requests

if len(sys.argv) != 2:
    sys.exit()

response = requests.get(
    "https://itunes.apple.com/search?entity=song&term=" + sys.argv[1]
)
# print(json.dumps(response.json(), indent=2)) # 使文件更加好读
o = response.json()
for result in o["results"]:
    print(result["trackName"])

作业

emojize

import emoji

biaoqing=input("Input: ")
print(emoji.emojize(biaoqing,language='alias'))

难点:

figlet

# Expects zero or two command-line arguments:
# Zero if the user would like to output text in a random font.
# Two if the user would like to output text in a specific font, in which case the first of the two should be -f or --font, and the second of the two should be the name of the font.
# Prompts the user for a str of text.
# Outputs that text in the desired font.
import sys
import random
from pyfiglet import Figlet

font_list=Figlet().getFonts()
try:
    if len(sys.argv)==3 :
        # 字体需要在字体表中,sys.argv[1]也应该是'-f'或'--font'
        if sys.argv[2] in font_list and sys.argv[1] in ['-f','--font']:
            getin=input("Input: ")
            print("Output:")
            f=Figlet(font=sys.argv[2])
            print(f.renderText(getin))
        else:
            raise ValueError
    elif len(sys.argv)==1:
        getin=input("Input: ")
        print("Output:")
        # 随机字体
        f=Figlet(font=random.choice(font_list))
        print(f.renderText(getin))
    else:
        raise ValueError
except ValueError:
    # 退出并提示'Invalid usage'
    sys.exit('Invalid usage')

难点:

  • 字体需要在字体表中,所以要先获取一个字体表listfont_list=Figlet().getFonts()
  • 判断某字符是某几种中的一个:if sys.argv[1] in ['-f','--font']
  • 随机字体
    • 随机的选中一款字体:font=random.choice(font_list) 需要用到字体list
    • f=Figlet(font=random.choice(font_list))
  • 退出并提示”xxxxx“:sys.exit('Invalid usage')

adieu


import inflect

names=[]
# 注意inflect的用法,这里应该是p
p=inflect.engine()

while True:
    try:
        # append函数在list最后增加新元素
        names.append(input("Name:"))
    except EOFError:
        print(f"Adieu, adieu, to {p.join(names)}")
        #EOF是退出循环不是继续循环
        break

难点:

  • 按list顺序输出名字,在list末尾增加元素
  • inflect包中join函数的用法

game

import random
# 这层循环用来输入正确的level
while 1:
    try:
        level=int(input("Level:"))
        if level<1:
            raise ValueError
        break
    except ValueError:
        pass
ans=random.randint(1,level)
# 这层循环用来猜数字,也应该是正确的数字
while 1:
    try:
        guess=int(input("Guess:"))
        if guess<ans:
            print("Too small!")
        elif guess>ans:
            print("Too large!")
        elif guess==ans:
            print("Just right!")
            # 退出全部循环
            break
    except ValueError:
        pass

难点:

  • 输入正确的内容:while死循环
  • random
    • ans=random.randint(1,level)生产1<=ans<=level

professor

# Prompts the user for a level, 
# . If the user does not input 1, 2, or 3, the program should prompt again.
# Randomly generates ten (10) math problems formatted as X + Y = , wherein each of X and Y is a non-negative integer with 
#  digits. No need to support operations other than addition (+).
# Prompts the user to solve each of those problems. If an answer is not correct (or not even a number), the program should output EEE and prompt the user again, allowing the user up to three tries in total for that problem. If the user has still not answered correctly after three tries, the program should output the correct answer.
# The program should ultimately output the user’s score: the number of correct answers out of 10.
import random

def main():
   l=get_level()
   times=0
   score=0
   while 1:
        try:
            a=generate_integer(l)
            b=generate_integer(l)
            ans=a+b
            rep=int(input(f"{a} + {b} = "))
            if rep==ans:
                score+=1
            else:
	            # 错误的情况
                raise ValueError
            # 无论正确错误,一个算式结束后次数都要加一
            times+=1
            if times==9:
                print("Score:",score)
                break
        except ValueError:
            print("EEE")
            tt=1
            while 1:
                rep1=int(input(f"{a} + {b} = "))
                if rep1 == ans:
                    score+=1
                    break
                else:
                    print("EEE")
                tt += 1
                if tt==3:
                    print(f"{a} + {b} =",ans)
                    break

def get_level():
    while 1:
        try:
            level=int(input("Level:"))
            if level == 1 or level==2 or level==3:
                break
            else:
                raise ValueError
        except ValueError:
            pass

    return level

def generate_integer(level):
    if level==1:
        n=random.randint(0,9)
    elif level==2:
        n=random.randint(10,99)
    elif level==3:
        n=random.randint(100,999)
    else:
        raise ValueError
    return n
    


if __name__ == "__main__":
    main()

难点:

  • 次数和分数的累计,用死循环可以
  • 输错答案的情况

bitcoin

import json
import requests
import sys

while 1:
    try:
        num=float(sys.argv[1])
        if len(sys.argv)!=2:
            raise requests.RequestException
    except ValueError:
        sys.exit("Command-line argument is not a number")
    except requests.RequestException:
        sys.exit("Missing command-line argument ")
        response=requests.get("https://api.coindesk.com/v1/bpi/currentprice.json?limit=1")
    o=response.json()
    # 嵌套字典取值
    # 注意,根据url取["bpi"]["USD"]["rate_float"]得到的是数字,["bpi"]["USD"]["rate"]得到的是字符串
    rate=o["bpi"]["USD"]["rate_float"]
    print(f"${rate*num:,.4f}")
    # 记得break,不然将一直循环获取rate,打印结果
    break

难点:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值