0

Why it shows error "Local variable 'output' might be referenced before assignment?

def is_one_digit(v) if type(v) == int: if -10 < v < 10: output = True else: output = False return output def check(v1, v2, v3): if is_one_digit(v1) and is_one_digit(v2): msg = "Good" else: msg = "Try again" print(msg)

8th Nov 2021, 3:58 PM
Neethu Nath
Neethu Nath - avatar
6 Antworten
+ 4
In the first method, output may be empty (unassigned) if type of v is int and v is not within the specified range. A better way to do this might be to just return the conditional statement, guaranteeing is_one_digit to return a valid boolean value under any circumstances. def is_one_digit(v): return ((type(v)==int) and (-10 < v < 10))
8th Nov 2021, 4:02 PM
Hatsy Rei
Hatsy Rei - avatar
+ 4
Neethu Nath Python supports short-circuiting. For 'and', the second argument is only evaluated if the first one is true. https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not https://code.sololearn.com/cLXQ08VhE2Dy/?ref=app
8th Nov 2021, 4:14 PM
Hatsy Rei
Hatsy Rei - avatar
+ 2
Issue: If v == type Integer, but not 1 digit, what value has output? I think undefined. So try one new line: def is_one_digit(v) : output = False . . .
8th Nov 2021, 4:16 PM
Coding Cat
Coding Cat - avatar
+ 1
Or, 2. way: if type(v) == int: if - 10 < v <10: output = True else: output = False else: output = False return output
8th Nov 2021, 4:23 PM
Coding Cat
Coding Cat - avatar
0
I tried that. It shows error as the input can be a non number.
8th Nov 2021, 4:08 PM
Neethu Nath
Neethu Nath - avatar
0
Hatsy Rei Let me try
8th Nov 2021, 4:20 PM
Neethu Nath
Neethu Nath - avatar