In: Computer Science
Now we want to display which error was thrown in our voting program.
Add the appropriate code to the try/except statement so the
exception is displayed.
Run the program and, when prompted, enter the word 'old' so your
output matches the output under Desired Output.
# Set the variable
age = input("What is your age?")
# Insert a try/except statement
# here when you convert the input
# to a number using int()
try:
age = int(age)
if age >= 18:
print("Go vote!")
except:
print("Please enter a valid age!")
Output :
invalid literal for int() with base 10: 'old'
Please enter a valid age!
We're still working with pie. Now we want to use the finally clause to display a message no matter what happens with our code.
Add the appropriate code to the try/except statement so that the
message "Enjoy your pie!" is displayed regardless of the error
caught (or not caught).
Run the program and, when prompted, enter the number 3 so your
output matches the output under Desired Output.
# Get Input
pieces = input("How many pieces of pie do you want? ")
# Attempt to convert to integer
try:
percentage = 1/int(pieces)
except ValueError:
print("You need to enter a number!")
except:
print("Something went wrong!")
else:
print("You get", format(percentage, ".2%"), "of the pie!")
Output:
Enjoy your pie!
You get 33.33% of the pie!
both problems are python
Voting Program
# Set the variable
age = input("What is your age?")
# Insert a try/except statement
# here when you convert the input
# to a number using int()
try:
age = int(age)
if age >= 18:
print("Go vote!")
except:
print("invalid literal for int() with base 10:'"+age +"'")
// This statement is added
print("Please enter a valid age!")
Output :
What is your age?old
invalid literal for int() with base 10:'old'
Please enter a valid age!
Explanation :
We have added a print() function which displays the required output format as " invalid literal for int() with base 10:'old' ". The format is "invalid literal for int() with base 10:'"+age +"'".
Working with Pie
# Get Input
pieces = input("How many pieces of pie do you want? ")
# Attempt to convert to integer
try:
print("Enjoy your pie") // Instead of using
finally here the statement is added.
percentage = 1/int(pieces)
except ValueError:
print("You need to enter a number!")
except:
print("Something went wrong!")
else:
print("You get", format(percentage, ".2%"), "of the pie!")
#finally: // This is written only for explanation why it
is not used here
# print("Enjoy your pie!") // This is only
coment
Output :
Enjoy your pie!
You get 33.33% of the pie!
Explanation :