首页 > 编程语言 >CS50-Python实验3,4

CS50-Python实验3,4

时间:2023-04-05 20:55:18浏览次数:62  
标签:try CS50 Python except sys ## 实验 print font

Week3 Exceptions

Fuel Gauge

题目描述:

输入分数字符串,判断并输出相应的百分数;特例不足1%输出E,超出99%输出F

思路:

1,从字符串中取出x,y;

2,按题中要求计算输出;

题解:

while True:
    try:
        ## 取出x,y
        x, z, y= input("Fraction: ")
        x, y = int(x), int (y)
        
        ##防止出错
        if y == 0:
            raise ZeroDivisionError
        if x > y:
            raise ValueError
        break
    except(ValueError, ZeroDivisionError):
        pass

## 模拟题
if 0 < x/y < 0.99:
    print(f"{round(x/y*100)}%")
elif x/y >= 0.99:
    print("F")
else:
    print("E")

Felipe’s Taqueria

题目描述:

根据用户输入的信息,匹配菜单价格,最终算出最终价格。

题解:

## 菜单信息
menu = {
    "Baja Taco": 4.00,
    "Burrito": 7.50,
    "Bowl": 8.50,
    "Nachos": 11.00,
    "Quesadilla": 8.50,
    "Super Burrito": 8.50,
    "Super Quesadilla": 9.50,
    "Taco": 3.00,
    "Tortilla Salad": 8.00,
}

##total:结果
total = 0

## 计算输出
while True:
    try:
        ## title(): 首字母大写其余小写
        item = input("Item: ").title() 
        if item in menu:
            total += menu[item]
            print(f"Total: ${total:.2f}")
    except EOFError:
        print()
        break

Grocery List

题目描述:

记录用户输入商品,最终输出已输入的商品以及商品数量;

题解:

## 存储商品信息
list = {}


while True:
    ## 输入处理
    try:
        ## upper():字符串大写
        item = input("").upper()
    except EOFError:
        print()
        break
	
    ## 记录商品
    if item in list:
        list[item] += 1
    else:
        list[item] = 1

## 输出结果
for item, cnt in sorted(list.items()):
    print(f"{cnt} {item}")

Outdated

题目描述:

用户输入9/8/1636,September 8, 1636形式,系统转换输出1636-09-08;若用户输出其他形式抛异常。

题解:

## 月份记录
months = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December"
]

##思路:分情况讨论
while True:
    date = input("Date: ")
    month,day,year = "", "", ""
    try:
        ## 9/8/1636
        if len(date.split("/")) == 3: 
            date = date.split("/")
            month, day, year = map(int, date)
        ## September 8, 1636
        else:
            date = date.split(",")
            if len(date) == 2:
                month, day = date[0].split()
                month = months.index(month)+1
                day, year = int(day), int(date[1])
        ##输出
        if 1<=int(month)<=12 and 1<=int(day)<=31:
            print(f"{year:04}-{month:02}-{day:02}")
            break
    except ValueError:
        pass

Week4 Libraries

Emojize

题目描述:

练习python调用库操作;

题解:

from emoji import emojize

print("Output:", emojize(input("Input: ")))

Frank, Ian and Glen’s Letters

题目描述:

The documentation for pyfiglet isn’t very clear, but you can use the module as follows:

from pyfiglet import Figlet

figlet = Figlet()

You can then get a list of available fonts with code like this:

figlet.getFonts()

You can set the font with code like this, wherein f is the font’s name as a str:

figlet.setFont(font=f)

And you can output text in that font with code like this, wherein s is that text as a str:

print(figlet.renderText(s))

题解:

from pyfiglet import Figlet
import random
import sys


fonts = Figlet().getFonts()

# 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.
if len(sys.argv) == 1:
    font = random.choice(fonts)
elif len(sys.argv) == 3:
    if sys.argv[1] in ["-f", "--font"] and sys.argv[2] in fonts:
        font = sys.argv[2]
    else:
        sys.exit("Invalid arguments.")
else:
    sys.exit("Invalid number of arguments.")

## 输出
text = input("Input: ")
print("Output:\n", Figlet(font=font).renderText(text))

Adieu, Adieu

题目描述:

用户输入名字,将所有名字按照inflect中的操作输出;

题解:

import inflect

p = inflect.engine()
names = []
while True:
    try:
        names.append(input("Name: ").strip())
    except EOFError:
        print()
        break

print(f"Adieu, adieu, to {p.join(names)}")

Guessing Game

题目描述:

用户选择猜数等级,然后进行竞猜。竞猜过程中会提示用户信息,直到猜中为止;

题解:

from random import randint

## 选择猜数等级
while True:
    try:
        n = int(input("Level: "))
        if n < 0:
            raise ValueError
        break
    except ValueError:
        pass

## 生成竞猜的数
rand = randint(1, n)

## 用户判断
while True:
    try:
        guess = int(input("Guess: "))

        if guess < rand:
            print("Too small!")
        elif guess > rand:
            print("Too large!")
        else:
            print("Just right!")
            break
    except ValueError:
        pass

Little Professor

题目描述:

用户选择等级进行随机式子生成,最后根据算式正确结果算取所得分数;

题解:

import random


def main():
    level = get_level()
    score = 0

    for _ in range(10):
        x = generate_integer(level)
        y = generate_integer(level)

        ## 计算score
        tries = 0

        while tries < 3:
            try:
                tries += 1
                answer = int(input(f"{x} + {y} = "))

                if answer == x+y:
                    score += 1
                    break
                else:
                    print("EEE")
            except ValueError:
                pass
        print(f"{x} + {y} = {x+y}")

    print("Score", score)

## 获取等级
def get_level():
    while True:
        try:
            level = int(input("Level: "))

            if level in [1, 2, 3]:
                return level
        except ValueError:
            pass
        
## 在范围内生成数字
def generate_integer(level):
    if level == 1:
        return random.randint(0, 9)
    return random.randint(10 ** (level - 1), 10**level - 1)


if __name__ == "__main__":
    main()

Bitcoin Price Index

题目描述:

Expects the user to specify as a command-line argument the number of Bitcoins n, that they would like to buy. If that argument cannot be converted to a float, the program should exit via sys.exit with an error message.

Queries the API for the CoinDesk Bitcoin Price Index at https://api.coindesk.com/v1/bpi/currentprice.json, which returns a JSON object, among whose nested keys is the current price of Bitcoin as a float. Be sure to catch any exceptions, as with code like:

import requests

try:
    ...
except requests.RequestException:
    ...

Outputs the current cost of Bitcoins in USD to four decimal places, using , as a thousands separator.

题解:

import sys
import requests

try:
    response = requests.get("https://api.coindesk.com/v1/bpi/currentprice.json")
    data = response.json()
    current_price = data["bpi"]["USD"]["rate_float"]
except requests.RequestException:
    sys.exit()


try:
    n = float(sys.argv[1])
except IndexError:
    sys.exit("Missing command-line argument")
except ValueError:
    sys.exit("Command-line argument is not a number")
print(f"${n * current_price:,.4f}")

标签:try,CS50,Python,except,sys,##,实验,print,font
From: https://www.cnblogs.com/sinowind/p/17290872.html

相关文章

  • python打印各种图形
    fewf#打印各种图形#正方形n行n列#***#***#***defsquare1(n:int)->None:foriinrange(n):forjinrange(n):print('*',end='')print()#长方形n行n+2列#*****#*****#*****def......
  • 实验三
    TASK1#include<stdio.h>#include<stdlib.h>#include<time.h>#include<windows.h>#defineN80voidprint_text(intline,intcol,chartext[]);//函数声明voidprint_spaces(intn);//函数声明voidprint_blank_lines(intn);//函数......
  • nohup python app.py 1>log.log 2>&1 & 这句话代码咋解释呀,不太明白
    nohuppythonapp.py1>log.log2>&1&这句话代码咋解释呀,不太明白 GPT给的答案 克隆ChatGpt功能nohuppythonapp.py1>log.log2>&1&这句话代码咋解释呀,不太明白  这个命令可以分成几部分:-`nohup`:意思是不挂断,即使终端关闭或者用户退出登录,进程也将继续运行。-......
  • python---飞机大战小游戏(提供源码)
    项目准备:本项目在pycharm平台实现,需要安装pygame等模块游戏功能:敌机会从不同位置出现且具有不同的速度,飞机可以发射子弹击毁敌机,飞机触碰到敌机会被击落,游戏结束效果演示飞机大战视频演示完整代码项目主要有两个文件构成,分别是plane_main.py文件和plane_sprites.py文件。plane_mai......
  • 实验三
    任务一:程序源码:#include<stdio.h>#include<stdlib.h>#include<time.h>#include<windows.h>#defineN80voidprint_text(intline,intcol,chartext[]);voidprint_spaces(intn);voidprint_blank_lines(intn);intmain(){int......
  • Python __ Pandas __ Dataframe 实验课
    基于Dataframe实现以下功能:导入directory.csvimportnumpyasnpimportpandasaspdfdata=pd.read_csv('F:\\directory.csv')dfx=pd.DataFrame(fdata)starbucks=pd.DataFrame(fdata)显示数据集的基本信息print(fdata.head())print(fdata.info())print(fdata.describe(......
  • python-爬虫-css提取-写入csv-爬取猫眼电影榜单
    猫眼有一个电影榜单top100,我们将他的榜单电影数据(电影名、主演、上映时间、豆瓣评分)抓下来保存到本地的excle中本案例使用css方式提取页面数据,所以会用到以下库importtimeimportrequestsimportparsel#解析库,解析cssimportcsv#爬取的数据写入csv创建csv文件标头信息......
  • 实验三
    实验任务1源码#include<stdio.h>#include<stdlib.h>#include<time.h>#include<windows.h>#defineN80voidprint_text(intline,intcol,chartext[]);voidprint_spaces(intn);voidprint_blank_lines(intn);intmain(){intline,......
  • 实验3 函数应用编程
    1.实验任务1#include<stdio.h>#include<stdlib.h>#include<time.h>#include<windows.h>#defineN80voidprint_text(intline,intcol,chartext[]);voidprint_spaces(intn);voidprint_blank_lines(intn);intmain(){int......
  • 实验三
    实验任务1#include<stdio.h>#include<stdlib.h>#include<time.h>#include<windows.h>#defineN80voidprint_text(intline,intcol,chartext[]);voidprint_spaces(intn);voidprint_blank_lines(intn);intmain(){intline,col......