Jacob Smith
Jacob Smith

Reputation: 123

Python - Using variables between functions

Having some trouble getting this to work... Basically I want to use the var binary (returned from inputF) in the convert function. I returned the variable, passed it in, and defined it... Stuck on what to do :/ I also defined it in main and passed it into the function... Says: Local variable 'binary' referenced before assignment.

def inputF():
  binary = input("Enter bin #: ")
  return(binary)

def convert(binary):
  binary = inputF(binary)
  print(binary)
  return

def main():
  binary = input(binary)
  inputF()
  convert(binary)
  return
main()

Upvotes: 0

Views: 81

Answers (2)

Kingsley
Kingsley

Reputation: 14926

UnboundLocalError: local variable 'binary' referenced before assignment

This is because you are passing the variable binary before it's created.

something = input(binary)

What is the value of binary? (there isn't one).

How about:

binary = input("Enter value for 'binary'> ")

Upvotes: 0

Win
Win

Reputation: 571

The error is coming in main because of the input(binary) statement (the error message should have included a line number pointing at that). If you want main to coordinate the inputF and convert functions, you can do:

def main():
    binary = inputF()
    convert(binary)

Then convert should just do whatever conversion it needs to do. Since you pass binary as an argument, you don't need to call inputF there:

def convert(binary):
    print(binary)
    # Do whatever you need to do

That way, convert doesn't need to worry about input at at all, and just processes the data passed to it as the argument.

Upvotes: 1

Related Questions