Apparently I have a problem with my code. When I run the below module with Python 3.3.3 Shell, I get the error SyntaxError: expected an indented block
. Then IDLE highlights elif
on line 7.
def user_input():
print('[1]: ASCII to Binary')
print('[2]: Binary to ASCII')
user_input = input('Please choose [1] or [2]: ')
if user_input == ('1', '[1]'):
#
elif user_input == ('2', '[2]'):
#
else:
print('Please enter a valid input...')
user_input()
You must have actual code in each if
and elif
block, you cannot just use a comment.
Use a pass
statement in such cases:
if user_input == ('1', '[1]'):
pass
elif user_input == ('2', '[2]'):
pass
else:
print('Please enter a valid input...')
user_input()
Also, you can’t actually use user_input
as a local variable name in your function and still be able to call the function by that name. Local variables shadow globals, so the user_input()
call in the else:
suite will raise a TypeError
as it is actually the string referenced by the local variable that’ll be called. Use a different name for the local variable; choice
would be a good option.
Next, you compared strings to tuples, those two types will never be equal Use in
to test if there is a string in the tuple that is equal to the user input:
if choice in ('1', '[1]'):
pass
If you used sets ({element1, element2, ...}
) that’d even be beter, as testing afwindt a set is faster.
You could just invert and combine the tests, and not need those empty blocks at all:
choice = input('Please choose [1] or [2]: ')
if choice not in {'1', '[1]', '2', '[2]'}:
print('Please enter a valid input...')
user_input()
And finally, use a loop, not recursion, to repeat the question on incorrect input. That’ll let you avoid the mistake you made here if not returning the recursive call result up the call chain and avoid the recursion limits (you can’t call functions without returning indefinitely, and you’d be surprised at how many users will try to see how long they can keep up entering bad options).
A while True
loop truly will keep on going:
def user_input():
print('[1]: ASCII to Binary')
print('[2]: Binary to ASCII')
while True:
choice = input('Please choose [1] or [2]: ')
if choice in {'1', '[1]', '2', '[2]'}:
return choice
print('Please enter a valid input...')
The return
exits the function (and so the loop), otherwise the user forever is told to provide valid input.