如何在Python 3代码中添加异常处理?

时间:2019-07-10 19:14:33

标签: python-3.x exception

我正在为我拥有的类编写这段代码,我需要一些帮助来添加异常处理。基本上,我需要帮助的是将异常处理适合我的用户输入,因此,如果用户输入的内容不是指定的内容,它将循环返回并要求用户输入正确的答案。我还需要对其中一个函数进行异常处理。到目前为止,这是我的代码。

symbol_list = ['AAPL', 'AXP', 'BA', 'CAT', 'CVX', 'DIS', 'GS', 'HD', 'IBM', 'INTC']

price_list = [150.75, 98.65, 340.53, 129.77, 111.77, 111.42, 175.37, 177.89, 119.83, 47.74] 
invest_dict = {'AAPL': 150.75, 'AXP': 98.65, 'BA':340.53, 'CAT' :129.77, 'CVX' :117.77, 'DIS' :111.42, 'GS':175.37, 'HD':177.89, 'IBM': 119.83, 'INTC':47.74}

print("...............................Lab 8.........................")

def Greeting():
    print("The purpose of this project is to provide Stock Analysis.")



def Conversions(investment_amount):

          investment_amount = float(investment_amount)

          Euro = float(round(investment_amount / 1.113195,2) )

          Pound = float(round(investment_amount / 1.262304,2) )

          Rupee = float(round(investment_amount / 0.014316,2) )

      print("The amount you invest in euro is:  {:.2f}" .format(Euro) )
      print("The amount you invest in pounds is:  {:.2f}" .format(Pound) ) 
      print("The amount you invested in Rupees is:  {:.2f}" .format(Rupee) )



def minimum_stock():
      key_min = min(invest_dict.keys(), key = (lambda k: invest_dict[k]))
      print("The lowest stock you can buy is: ",invest_dict[key_min])



 def maximum_stock():
      key_max = max(invest_dict.keys(), key = (lambda k: invest_dict[k]))
      print("The highest stock you may purchase is: ",invest_dict[key_max])



def invest_range(investment_amount):
            new_list = []
            new_list = [i for i in price_list if i>=50 and i <=200] 
            return(sorted(new_list))


answer = 'yes'
while answer:

print(Greeting())

investment_amount = float(input("Please enter the amount you want to invest:$ "))
if investment_amount!='':
    print("Thank you for investing:$ {:,.2f}".format(investment_amount))


print(Conversions(investment_amount))

for i in invest_dict:
    i = investment_amount
    if i <25:
        print("Not enough funds to purchase stock")
        break
    elif i>25 and i <=250:
        print(minimum_stock())
        break
    elif i >= 250 and i <= 1000:
        print(maximum_stock())
        break

print("This is the range of stocks you may purchase: ", invest_range(investment_amount))

answer = input("Would you like to complete another conversion? yes/no " )
if answer == 'no':
    print("Thank you for investing.")
    break

2 个答案:

答案 0 :(得分:1)

做到这一点的典型方法是

while True:
    try:
        investment_amount = float(input("Please enter the amount you want to invest:$ "))
        break
    except ValueError:
        print("Please enter a dollar amount (a floating-point number)")
print("Thank you for investing: ${:,.2f}".format(investment_amount))

或者,如果您愿意导入内容,则click模块提供了一种执行以下操作的方法:

investment_amount = click.prompt('Please enter the amount you want to invest: $', type=float)

,它将一直询问用户,直到输入的类型正确为止。对于以后的提示,要求是/否,click.confirm()也可以为您完成。

答案 1 :(得分:0)

您可以在进行输入的地方尝试这种错误处理:

while answer:

    print(Greeting())
    try:
        investment_amount = float(input("Please enter the amount you want to invest:$ "))
        print("Thank you for investing:$ {:,.2f}".format(investment_amount))
    except:
        print("Please enter a valid amount...")
        continue

    print(Conversions(investment_amount))

希望这会有所帮助。