The short answer is that Python expects you to use the global
keyword in a function if you desire to modify a global variable. So, you need to do something like the following:
def setname(name):
global myvar
myvar = name
Because you didn't do that, when the Python interpreter entered into setname
it created a new myvar
variable that is local to the function when it evaluated the expression myvar = name
. As soon as that function returned, that local myvar
was effectively deleted. The global myvar
was untouched.
Now, Python allows you read global variables without using the global
keyword. Your printname
function is actually printing something, it just happens to be an empty string because that's what you assigned to the global myvar
variable and it wasn't updated by setname
.
Here is a link to Python FAQ that explains this in more detail:
https://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python
Edit (to address the second question):
I highly recommend reading Python's documentation on Modules. The short, simplified answer is there are two reasons:
- When you import a module, Python instantiates a module object, loads the contents of the module into it, then provides a variable to access that object. The variable is locally scoped to the file in which it is imported. The name of that variable is the name of the module you imported, unless you change it. Functions in the imported modules are methods of that module object; hence, why you need to use
pythontest
to invoke those functions. This leads the second point.
- If you don't want to import the entire module, you have to options. First, you can import specific items from a module. If you want to merely import the functions, for instance, you can use this syntax:
from pythontest import setname, printname
setname("Bob")
printname()
The net effect is that instead of creating a module object Python will, in this example I provided, for each function create a function object and assign that object to a variable that has the name of the function being imported (e.g., the variable setname
references the setname function in pythontest). When you import function objects this way, you don't need to supply the pythontest
prefix.
Second, you can supply a different name to the module (or functions) you're importing when importing them, then use that new name throughout that Python file. Here is an example:
import pythontest as pt
pt.setname("Bob")
pt.printname()
You can even do this with the individual functions/variables you import:
from pythontest import setname as really_cool_setname, printname as showname
really_cool_setname("Bob")
showname()
Side note:
Keep in mind that everything is an object in Python, even importing modules, functions, and variables.