CS50P week3 exceptions

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

Notes

try & except(常搭配while死循环)

def main():
    x = get_int()
    print(f"x is {x}")


def get_int():
    while True:
        try:
            return int(input("What's x?"))
        except ValueError:
            print("x is not an integer")

main()

python官方文档的Errors and Exceptions
CSDN:try…except…的详细用法

pass

def main():
    x = get_int("What's x? ")
    print(f"x is {x}")


def get_int(prompt):
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            pass


main()

作业

fuel


# implement a program that prompts the user for a fraction, formatted as X/Y, 
# wherein each of X and Y is an integer, and then outputs, as a percentage rounded to the nearest integer, 
# If, though, 1% or less remains, output E instead to indicate that the tank is essentially empty. 
# And if 99% or more remains, output F instead to indicate that the tank is essentially full.
# If, though, X or Y is not an integer, X is greater than Y, or Y is 0,
# instead prompt the user again. (It is not necessary for Y to be 4.) 
# Be sure to catch any exceptions like ValueError or ZeroDivisionError.

def getxy():
    while True:
        try:
            x,y=input("Fraction: ").split("/")
            x=int(x)
            y=int(y)
            if y==0:
                # 将被除数为0的异常主动触发
                raise ValueError
            # 只有正常的数才能返回
            if 0<= x/y <=1:
                return(x/y)
        except ValueError:
            pass


def main():
    res=round(getxy()*100)
    if res<=1:
        print("E")
    elif res>=99:
        print("F")
    else:
        print(f"{res:}%")

main()

难点:

  • 用raise语句(raise ValueError)主动触发异常,排除分母为0的情况 #主动触发异常
  • 字符转为int,如果转不成功就是valueerror
  • 小数转为百分数 #百分数

taqueria

# enables a user to place an order,prompting them for items, one per line, 
# until the user inputs control-d (which is a common way of ending one’s input to a program). 
# After each inputted item, display the total cost of all items inputted thus far, 
# prefixed with a dollar sign ($) and formatted to two decimal places.
# Treat the user’s input case insensitively. Ignore any input that isn’t an item.

menu={
    "Baja Taco": 4.25,
    "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
}

price=0
while True:
    # item=input不能放在try外,否则找不到EOF
    try:
        # 首字母大写
        item=input("Item: ").title()
        # 判断item是否在menu中,不在则pass
        if item in menu:
            price=price+menu[item]
            print(f"Total: ${price:.2f}")
    except EOFError:
        print()
        #EOF是退出循环不是继续循环
        break

难点:

  • item=input()不能放在try外,否则找不到EOF #EOF
  • 保留两位小数 print(f"Total: ${price:.2f}") #保留小数

grocery

dic小知识

# 申明一个dic
item={}
while True:
    # 这个dic的键是items_name,值是count
    try:
        # 这样结合后面的就将用户输入放入了dic中
        item_name=input().upper()
    except EOFError:
        print()
        break
    if item_name in item:
        item[item_name] += 1
    else:
        item[item_name]=1

# 对字典排序,sorted(item.items())返回键值对
for item_name,count in sorted(item.items()):
    print(f"{count} {item_name}")

难点:

  • 将用户输入放入dic中
    • 死循环
    • 与后面的结合
  • 区分键与值
  • sorted对字典排序
    • sorted(dic.items()) 对键和值进行排序,返回键值对
    • sorted(dic.keys()) 对键排序,返回键
    • sorted(dic.values()) 对值排序,返回值
    • sorted对字典dict排序

outdated

# prompts the user for a date, anno Domini, in month-day-year order, 
# formatted like 9/8/1636 or September 8, 1636,
# wherein the month in the latter might be any of the values in the list below:

month={
    "January":"1",
    "February":"2",
    "March":"3",
    "April":"4",
    "May":"5",
    "June":"6",
    "July":"7",
    "August":"8",
    "September":"9",
    "October":"10",
    "November":"11",
    "December":"12"
}

# try & exception 可以比较方便排除指定成功格式外的全部格式
while True:
    try:
        gets=input("Date: ")
        # 分割 9/8/1636 这类的
        if "/" in gets:
            m,d,y=gets.split("/")
            m=int(m)
            y=int(y)
            d=int(d)
            if 0<m<=12 and 0<d<=31:
                print(f"{y:02}-{m:02}-{d:02}")
                break
            else:
                raise ValueError
        # 分割 September 8, 1636 这类的
        elif "," in gets:
            m1,d0,y1=gets.split(" ")
            if m1 in month:
                m1=int(month[m1])
            else:
                raise ValueError
            y1=int(y1)
            # 注意,d0="8,",通过split只取‘,’前面的部分
            d1=int(d0.split(",")[0])
            if 0<d1<=31:
                print(f"{y1:02}-{m1:02}-{d1:02}")
                break
            else:
                raise ValueError

    except ValueError:
        pass

难点:

  • 区分两种用户输入形式:用两个if语句接收正确输入,结合try&except,不正确的都认为是valueerror #split
  • 2001-06-09而不是2001-6-9:语句print(f"{y1:02}-{m1:02}-{d1:02}")print(f"{n:02}")表示n如果只有一位,前面用0补全
  • try & exception 可以比较方便排除指定成功格式外的全部格式
  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值