简体   繁体   中英

Taking a programming course and can´t figure out how to incorporate try and except into a code along the lines of this question

I was assigned an assignment and couldn't figure out how to finish it. I'm supposed to include functions and try-except into the code which I have no experience with.

I have this so far to replace with the spaces with no space but can't filter out the number so I can multiply them and divide.

shares = int(input("Input number of shares"))

new_price = 0

while True:
    try:
        price = input("Enter price (dollars, numerator,denominator):")
        int(price.replace(" ", ""))
    except:
        print("Invalid price!")
Enter a number: vash Traceback (most recent call last): File "except.py", line 1, in <module> number = int(input('Enter a number: ')) ValueError: invalid literal for int() with base 10: 'vash'

If we look when we try to input a non int when we are requiring an int we throw a ValueError now that becomes the condition of our except statement to prevent this

try:
    number = int(input('Enter a number: '))
except ValueError:
    print('That is not a number')

Now our output becomes

Enter a number: vash That is not a number

A try and catch block is used to catch exceptions within the block. Everything inside the try block that raises an exception will throw the next operation to the catch block. This can be useful to prevent the script from crashing when you might expect an exception.

We receive a white-space separated string of integers, then split that string on the white-space, convert each of the components to an int , then use those int s to calculate the price.

while True:
    try:
        response = input("Enter price (dollars, numerator,denominator):")
        dollars, numerator, denominator = map(int, response.split())
        price = dollars + numerator/denominator
    except ValueError:
        print("Invalid price!")

Don't replace the spaces, catch each character (digit) one by one and evaluate it.

If it's a number continue, if it's a space you've reached the end of the first value. So save the value to another variable, say value1. Continue to do the same thing till you reach space again. Save to value2, again. Nest your while loop to the length of the input.

Return your variables, multiply, respond.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM