Python Forum
Def and variable help please
Thread Rating:
  • 1 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Def and variable help please
#1
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.
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
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].
I am trying to help you, really, even if it doesn't always seem that way
Reply
#4
(Sep-11-2018, 06:43 PM)gruntfutuk Wrote: @ichabod801 you've missed end : from first three defs in your sample code.

Duh. Good catch.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020