Python Python Basics (2015) Logic in Python Try and Except

Sebastiaan van Vugt
Sebastiaan van Vugt
3,466 Points

Python Basics (2015) Challenge Task 3 of 3 does not accept what seems to be an appropriate solution...

This is my solution which I tested successfully in the workspace:

try: num1 = int(input("What is the first number you would like to add? ")) num2 = int(input("What is the second number you would like to add? ")) float(num1) float(num2) except ValueError: 0 else: print(num1 + num2)

With this solution task 1 is not passing anymore. In the workspace I can however not seem to add a return argument in the try function (I hope I'm naming these correctly). Simply said I cannot work from the answer of task 2 which is this:

def add(num1, num2): return float(num1) + float(num2)

To a workable try function as described that would also be accepted...

Thank you for your ideas on what the "right" model answer should be here.

trial.py
try: 
    num1 = int(input("What is the first number you would like to add? "))
    num2 = int(input("What is the second number you would like to add? "))
    float(num1)
    float(num2)
except ValueError:
    0
else:
    print(num1 + num2)

2 Answers

Steven Parker
Steven Parker
173,784 Points

Your workspace program functions a bit differently from what the challenge is asking for.

Some of the things needed by the challenge:

  • you still need to have everything inside a function named "add"
  • the values you will use are passed in as arguments, so you will not need to "input" anything
  • the function must return the results
  • you won't need to "print" anything
  • when an exception occurs, you need to return None
  • the "float" function doesn't change its argument, so you'll need to assign the result to use it
Sebastiaan van Vugt
Sebastiaan van Vugt
3,466 Points

Thanks a lot for the advice. I didn't realise before that the exception could be dealt with in the function. I have figured it out now though :)

def add(num1, num2): try: float(num1) float(num2) except ValueError: return None else: return(float(num1) + float(num2))