简体   繁体   中英

Trying to use a variable that is inside a function in another function

So I am trying to use a variable that is inside a function in another function.

One of them is the "message.py" file, that is in the folder "properties". The file looks like this:

def nachricht():
    global msg
    msg = input("Type: ")
    return msg

The other file is the "badwords_check.py", that is in the folder "module". This file looks like this:

from properties.message import msg
from properties.badwords import BadWords

def badwords_check():
  if any(word in msg for word in BadWords):
    print("Dont use that word!")
    
  else:
    print("Message send!")

The problem now, is that I can't import "msg" from "message.py".

The error code looks like this:

from properties.message import msg
ImportError: cannot import name 'msg' from 'properties.message'

I had tried things like: Global, with/without function(without the function it works, but I need it with a function because some other code and files) and I tried return.

You need to declare the global variable outside the function at the top and then you can modify it inside your function using global msg .

msg= ''
def nachricht():
    global msg
    msg = input("Type: ")
    return msg

To add on to Vaibhav's answer, the function nachricht() is never being called in badwords_check.py.

Hence, there is no input being taken and the variable msg also doesn't exist.

While declaring msg as a global variable, the function should also be called.

from properties.message import *
from properties.badwords import BadWords

#use nachricht()
#then use the below function

def badwords_check():
  if any(word in msg for word in BadWords):
    print("Dont use that word!")
    
  else:
    print("Message send!")

If nachricht() is not used, then msg will simply be a empty string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM