Reputation: 61
I'm trying to use the results of some input statements as parameters in a function. I've tried putting the input statements before the function and then calling the function up afterwards, like this:
s=input("Enter the message:")
raw_key=input("Enter the raw key for columnar transposition:")
method=input("Enter the key generation method:")
def encryptColumnar(s,raw_key,method):
if method==1:
numkey=key1(raw_key)
if method==2:
numkey=key2(raw_key)
return(columnar(s,numkey))
encryptColumnar(s,raw_key,method)
but it just gives me the error UnboundLocalError: local variable 'numkey' referenced before assignment
. If I just put the input statements before the function, they'll prompt me for input, but they won't recognize that the input is supposed to be used as the function's parameters.
Thanks very much for the help!
EDIT: NEW CODE:
This is currently the code I'm working with:
s=input("Enter the message:")
raw_key=input("Enter the raw key for columnar transposition:")
method=input("Enter the key generation method:")
def encryptColumnar(s,raw_key,method):
if method=='1':
numkey=key1(raw_key)
if method=='2':
numkey=key2(raw_key)
return(columnar(s,numkey))
encryptColumnar(s,raw_key,method)
It doesn't give me the UnboundLocalError anymore, but it also doesn't print anything after I give the parameters to the input statement prompts.
Upvotes: 1
Views: 379
Reputation: 32580
If you're running this on Python 3.x, input()
will not eval()
the user's response like the Python 2 version does - it will return it as a string (it basically behaves like Python 2's raw_input
). Therefore your conditions method == 1
etc. will never be satisfied, leading to numkey
being undefined.
So you have to options:
int
and test against integers:import sys
method = input("Enter the key generation method:")
try:
method = int(method)
except ValueError:
print("You need to enter an integer!")
sys.exit(1)
# ...
if method == 1:
# ...
import sys
method = input("Enter the key generation method:")
if method == '1':
# ...
elif method == '2':
# ...
else:
print("Unknown method!")
sys.exit(1)
See the documentation on exception handling for the details of the except
statement, and the docs on the if
statement for details on the elif
clause. They're not strictly relevant to your problem here, but as @TheSoundDefense pointed out, the error handling of your code could be improved a bit, so there you go ;-)
Upvotes: 1
Reputation: 6935
The problem is that numkey
is not guaranteed to be set by the end of encryptColumnar
. If method
is 3, or anything besides 1 or 2, then there is no numkey=
statement that gets executed, so it's never assigned. Then when you get to return
, you get an error because you're trying to return a variable that was never assigned. At the very least, you should put an else
statement in to make sure numkey
is covered.
Upvotes: 1