0

I am writing this code for class I have and I need some help adding exception handling. Basically what I need help with is fitting the exception handling around my user inputs so if the user inputs anything other than what is specified it'll loop back and ask the user to input the correct answer. I also need to have an exception handling with one of my functions. This is my code so far.

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
1
  • could you fix the indentations in your code? Commented Jul 10, 2019 at 19:43

2 Answers 2

1

The archetypical way of doing this is something along the lines of

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))

Alternatively, if you're willing to import stuff, the click module has a method to do something like this:

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

which will keep asking the user until the input is of the correct type. For your later prompt, asking for yes/no, click.confirm() can do that for you as well.

Sign up to request clarification or add additional context in comments.

Comments

0

You can try this error handling where input is taken:

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))

Hope this will help.

1 Comment

Thank you very much Ankur singh! I Finally got it to work!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.