Reputation: 1161
I'm working on writing a simple function that will take the square root of a number. The user is prompted to provide a integer. However, if they provide a string--I'd like there to be a message "You did not give me a number".
See code below:
def square(n):
"""Takes a square root of a number :rtype : int """
if n == int(n):
return pow(n, 2)
try:
answer = int(input("...."))
except ValueError:
print("You did not give me a number!")
final_answer = "{} squared is {}".format(answer, square(answer))
print(final_answer)
Works okay with a integer:
....9
9 squared is 81
With a string:
Traceback (most recent call last):
File , line 28, in <module>
final_answer = "{} squared is {}".format(answer, square(answer))
NameError: name 'answer' is not defined
You did not give me a number!
The error makes perfect sense since answer isn't defined. However, is there a way to just print/return the exception "You did not give me a number" without the NameError message?
Thank you for you help!
Upvotes: 0
Views: 158
Reputation:
You can add an else
block to the end of your try/except
:
try:
answer = int(input("...."))
except ValueError:
print("You did not give me a number!")
else:
final_answer = "{} squared is {}".format(answer, square(answer))
print(final_answer)
The code inside the else
block will only be run if the try
block completes successfully. Here is a link to the documentation for more information.
Upvotes: 3