首页
学习
活动
专区
圈层
工具
发布

试除块
EN

Stack Overflow用户
提问于 2022-05-04 11:08:46
回答 2查看 93关注 0票数 1

我如何在python“试除”块中编写这个代码呢?我有一个字典(键和值),这些值是整数。在一个“试除”块中,我将输入我选择的键,并将值进行汇总。我正在退出我的最后一项投入。使用"ctrl +d“,然后程序应该给我输入的键值之和。

代码语言:javascript
复制
fruits = {
    "mango": 4.00, "lemon": 2.00,
    "orange": 3.00, "apple": 2.00,
    "avocado": 2.50, "pineapple": 5.00,
    "Watermelon": 6.50, "grapes": 4.5
    }
price = 0
while True:
    try:
        n = input("Order: ")

        if n in fruits:
            price += fruits.get(n)

    except(EOFError, KeyboardInterrupt):
        print(f"Sum of inputs is: {price}")
        break

这是我上面的代码。

那密码怎么了?

我没有得到我想要的。

我不想在我用"control + d“退出之前,程序提示我。当输入最后一个键时,我想退出。然后程序会为我打印值之和。

EN

回答 2

Stack Overflow用户

发布于 2022-05-04 11:19:23

不要使用异常来处理代码中的控制流。使用条件离开循环。

我不想在我用"control + d“退出之前,程序提示我。当输入最后一个键时,我想退出。

这是不可能的--程序“循环太快”,以至于在对值进行求和时,您无法正确地退出该程序--除非您在对值进行汇总后强迫程序在一段时间内保持睡眠()

代码语言:javascript
复制
from time import sleep

fruits = {"mango": 4.00, "lemon": 2.00, "orange": 3.00, "apple": 2.00,
    "avocado": 2.50, "pineapple": 5.00, "watermelon": 6.50, "grapes": 4.5}

cost = 0
while True:
    try:
        n = input("Order: ")
    
        if n not in fruits:
            print("Invalid choice.")

        # sum if in dict, else use 0
        cost += fruits.get(n, 0) 
        
        sleep(2) # force a 2 second pause _every_ time to allow Ctrl-D/C
    except KeyboardInterrupt:
        break

print(f"Sum of inputs is: {cost}")

但这很难看--更好的选择是像“我完成了.”那样处理空输入:

代码语言:javascript
复制
fruits = {"mango": 4.00, "lemon": 2.00, "orange": 3.00, "apple": 2.00,
    "avocado": 2.50, "pineapple": 5.00, "watermelon": 6.50, "grapes": 4.5}

cost = 0

print( *(f"{n} costs {p}" for n,p in fruits.items()), sep="\n")

while True:
    n = input("Order: ")
   
    if not n:    # empty string is "Falsy" - same as most empty 
        break    # iterables, 0, and some other values

    if n not in fruits:
        print("Invalid choice.")

    cost += fruits.get(n, 0)     # add 0 if not in dict


print(f"Sum of inputs is: {cost}")

要获得

代码语言:javascript
复制
mango costs 4.0
lemon costs 2.0
orange costs 3.0
apple costs 2.0
avocado costs 2.5
pineapple costs 5.0
Watermelon costs 6.5
grapes costs 4.5

Order: lemon
Order: water                   # invalid choice
Invalid choice.
Order: grapes
Order:                         # empty input breaks 
Sum of inputs is: 6.5          # 2 + 4.5

您不应该使用sum作为变量名,该名称由sum()函数中的build获取。

异常是用来处理错误的,而不是用来引导代码流的。

票数 1
EN

Stack Overflow用户

发布于 2022-05-04 11:34:10

您可以使用finally打印最终价格。

代码语言:javascript
复制
fruits = {
"mango": 4.00, "lemon": 2.00,
"orange": 3.00, "apple": 2.00,
"avocado": 2.50, "pineapple": 5.00,
"Watermelon": 6.50, "grapes": 4.5
}

price = 0

while True:
try:
    n = input("Order: ")
    price += fruits[n]
    print("Item added.")

except:
    print("Item is not in the list.")

finally:
    print("Sum: " + str(price))

此外,您还可以在打印sum后打印空字符串以获得更好的界面。

代码语言:javascript
复制
fruits = {
"mango": 4.00, "lemon": 2.00,
"orange": 3.00, "apple": 2.00,
"avocado": 2.50, "pineapple": 5.00,
"Watermelon": 6.50, "grapes": 4.5
}

price = 0

while True:
    try:
        n = input("Order: ")
        price += fruits[n]
        print("Item added.")

    except:
        print("Item is not in the list.")

    finally:
        print("Sum: " + str(price))
        print("")

如果你想得到最后的和,你可以在while之外打印它。

代码语言:javascript
复制
fruits = {
"mango": 4.00, "lemon": 2.00,
"orange": 3.00, "apple": 2.00,
"avocado": 2.50, "pineapple": 5.00,
"Watermelon": 6.50, "grapes": 4.5
}

price = 0

while True:

    try:
        n = input("Order: ")
        price += fruits[n]
        print("Item added.")

    except:
        print("Item is not in the list.")
        break

print("Sum: " + str(price))
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72111947

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档