Python Forum
Def and variable help please - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Def and variable help please (/thread-12759.html)



Def and variable help please - Mrocks22 - Sep-11-2018

I want to be able to use the variables in test1, test2 and test3 in testall all like this

def test1():
x = 1

def test2():
y = 2

def test3():
z = 3

def testall():
print(x)
print(y)
print(z)

I have tried using the command return but that does not work at it does not allow the execution of code after the return.

The simpler the solution the better because I am quite new at python and don't really understand more complex coding.


RE: Def and variable help please - ichabod801 - Sep-11-2018

Please use Python tags when posting code. It looks like you are trying to use global variables, which is a bad idea. The way you would do this with return statements and parameters is:

def test1():
    return 1

def test2():
    return 2

def test3():
    return 3

def testall(x, y, z):
    print(x)
    print(y)
    print(z)

if __name__ == '__main__':
    x = test1()
    y = test2()
    z = test3()
    testall(x, y, z)
See the functions tutorial link in my signature below for more information. The if __name__ == '__main__': block is only run if the module is run from the command line, but not if it is imported by another module. It's a common way to put test code or what might be 'main' code.


RE: Def and variable help please - gruntfutuk - Sep-11-2018

The variables x, y, z only exist within the scope of each of your functions.

You either call the function and have it print itself, or you call the function and have it return a value that you can use elsewhere (in the code that called the function).

@ichabod801 you've missed end : from first three defs in your sample code. [Sorry, don't know how to tag you].


RE: Def and variable help please - ichabod801 - Sep-12-2018

(Sep-11-2018, 06:43 PM)gruntfutuk Wrote: @ichabod801 you've missed end : from first three defs in your sample code.

Duh. Good catch.