Home > Mobile >  How to call a function from another file, but use a variable from the current one?
How to call a function from another file, but use a variable from the current one?

Time:09-13

So how to call a function from another file but use a variable from the current one? I think it's very simple, but I can't get the desired effect. I keep getting an error that there is no such variable, even if I write 'global settings' Here is a sample code.

from modules.module import *

settings = "Hello world"
displayText()
input()

FIle 2

def displayText():
    print(settings)

CodePudding user response:

add a parameter in your displayText function.

def displayText(settings):
    print(settings)

Pass the parameter from the actual file

from modules.module import *

settings = "Hello world"
displayText(settings)
input()

CodePudding user response:

Most of the times, you can pass a variable to a function. That has to be defined as a parameter in the function definition. Look at the below example:

def print_value(value):
    print(value) 

Value here is a parameter variable that can be passed to the function by calling it with your variable:

name = "My Name!"
print_value(name)
# Prints out: My Name!
  • Related