Python beginner here, if anyone could explain why this code won’t work I would be very thankful.
Please post the code instead of a screenshot.
It looks like the code is working as intended - the exceptions are being caught. You can’t turn a word into a number.
If the intention of your code is using the try
/except
blocks to handle exceptions raised by inputing non-number, and print out the reciprocal if a number is entered, you should use else
block instead of finally
block (Though ZeroDivisionError can still be raised if 0 is entered ).
The finally
block will execute regardless of the result of the try
and except
blocks. So after a non-number is inputed, even though the except
blocks do produce the “This is not a natural number,” printout and even exit()
function is “exiting”, the finally
block still executes, which raises a new TypeError exception since that line is trying to do division between 1 and a string. And error messages before entering the finally
block are displayed at the same time.
Python beginner here, if anyone could explain why this code gives me a giant error I would be very thankful.
code:
value = input('Please enter a natural number: ')
try:
value = int(value)
except ValueError:
try:
value = float(value)
except ValueError:
print('This is not a natural number.')
exit()
finally:
print('The reciprocal of', value, 'is', 1/value)
output:
Please enter a natural number: no
This is not a natural number.
Traceback (most recent call last):
File "main.py", line 3, in <module>
value = int(value)
ValueError: invalid literal for int() with base 10: 'no'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "main.py", line 6, in <module>
value = float(value)
ValueError: could not convert string to float: 'no'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "main.py", line 9, in <module>
exit()
File "/usr/lib/python3.7/_sitebuiltins.py", line 26, in __call__
raise SystemExit(code)
SystemExit: None
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "main.py", line 11, in <module>
print('The reciprocal of', value, 'is', 1/value)
TypeError: unsupported operand type(s) for /: 'int' and 'str'
Hey Skelotron,
You can use triple backticks ``` before and after code block to make it appears like code block. And don’t forget to make sure the code posted is in correct indentations.
You’re getting an error because you are passing letters in as input instead of numbers.
I’ve edited your code for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
You can also use the “preformatted text” tool in the editor (</>
) to add backticks around text.
See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').
Your code is clean when parsed. After running your script input a natural number not letters, not other numbers like float or complex numbers, No!
input natural numbers: any number or combinations from 0 through 9:
1, 3 4, 6, 67 etc.
Great job!
the problem with your code is syntax error and typo( here was a single quotation mark ('
) misplaced in the finally
block. It was removed in the corrected code.)
this is the correct code :value = input('Please enter a natural number: ')
try:
value = int(value)
except ValueError:
try:
value = float(value)
except ValueError:
print(‘This is not a natural number.’)
exit()
finally:
print(‘The reciprocal of’, value, ‘is’, 1 / value)
If the intention is to avoid raising exception when non-number is entered, replacing finally
block with else
block like the following would do the job:
value = input('Please enter a natural number: ')
try:
value = int(value)
except ValueError:
try:
value = float(value)
except ValueError:
print('This is not a natural number.')
exit()
else:
print('The reciprocal of', value, 'is', 1/value)
But when different cases of input are tried, it’s response may not look good:
- When a non-zero positve integer is entered, it raises no exception and prints out the reciprocal, which should be a welcomed response.
- But when a negative positive integer, which is not a natural number, is entered, it also raises no exception and prints out the reciprocal, which may not fit the prompt of the input statement.
- When a non integer is entered, it raises an exception in the
try: value = int(value)
clause but not in thetry: value = float(value)
clause, nothing would be done. - When zero is entered, it will raise no exception in the
try
clauses, but will raise Zero DivisionError when1/value
is executed. - When non number is entered, it raises exception in both
try: value = int(value)
clause andtry: value = float(value)
clauses, and prints out “This is not a natural number”.
If the intention is to use try
/except
/else
blocks to check whether the requirement of the prompt of the input statement (enter a natural number) is met, and to “create” and handle exceptions for different types of non-natural number input before printing out the reciprocal, perhaps we should do the checks in the following order:
- Is the input a number?
- Is the input an integer?
- Is the input a positive non-zero integer?
And the code would go like this:
input_string = input('Please enter a natural number: ')
try:
value = float(input_string)
except ValueError: # The input is not a number
print('This is not a number.')
else: # The input is a number
try:
value = int(input_string)
except ValueError: # The input is not an integer
print('This is not an integer')
else: # The input is an integer
import math
try:
math.log(value) # will give an error when value <= 0
except ValueError:
print("This is not a non-zero positive integer")
else: # The input is a non-zero positive integer, ie natural number
print('The reciprocal of', value, 'is', 1/value)
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.