0

My problem is that I want to use a variable from a def function, I don't know how to do it or if I even can. Here's the code I'm using

def yandn(prompt='Y/N:'):
    no=1
    while no==1:
      ok=input(prompt)
      if ok.lower()==('y'):
        a=0
        b=0
        break
    elif ok.lower()==('n'):
      a=1
      b=0
print('Blah Blah Blah')
c=1
while c==1:
  d=input('Blah Blah:')
  if d.lower() in valid:
    print('Confirm', d, 'as blah.')
    yandn()
    from yandn import a
    if a==1:
      c=1
    else:
      c=0
1
  • You could 'return a' from yandn Commented Dec 4, 2016 at 0:03

2 Answers 2

3

No. You can't import things from a function. Why not have yandn return a?

Sign up to request clarification or add additional context in comments.

Comments

1

You can't import from function. There is 2 way you can achieve the same, 1 is through global variable, the other 1 is to return variable a from the function which is more recommended.

Using global variable

a = None # initialize global var
def yandn(prompt='Y/N:'):
    global a # indicate a as global var
    # continue with function code

yandn()
# no need import, now var a is accessible

Using return

a = yandn()
# you got the var a from yandn function now

5 Comments

"global variable 'a' is undefined at the module level"
before function yandn is called, global var a does not exist, you can initialize it outside the function with a=None
But c=1 so that it can be the catalyst for the while loop, I'm trying to make c=0 when a=1 and a is in the function yandn, I'm trying to do this so that I can save space on my code and not do tedious "if y==1" constantly. P.S the last comment was removed because I felt it would cause confusion.
i still can't get what you mean, after added global a in function yandn and remove the line from yandn import a, what are the thing that not works now ?
Never mind, I understand now thanks to both of your answers, thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.