Python Forum

Full Version: i don't understand how to use a variable outside of a function?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
from this function:
def test(arg)
a = 0
if arg >3:
    a=1
return a
how do i use it in another function?:

def main():
    arg = rand.randrange(0,7)
    test(arg)
    if a = 1:
        print('I don't know what i'm doing')
Pass as an attribute
>>> def func1():
...     return 15
...
>>> def func2(value):
...     print('Value x 2 = {}'.format(value * 2))
...
>>> def main():
...     a = func1()
...     func2(a)
...
>>> main()
Value x 2 = 30
based on your code:
import random

def test(arg):
    if arg > 3:
        a = 1
    else:
        a = 0
    return a

def main():
    arg = random.randrange(0,7)
    a = test(arg) # here you can use any name, not neccessary to be a
    if a == 1:
        print("I don't know what i'm doing")
more pythonic would be

import random
def test(arg):
    return arg >3

def main():
    arg = random.randrange(0,7)
    if test(arg):
        print("I don't know what i'm doing")
also note the double quotes of the string - otherwise you need to escape the single quotes
so in my case it would be:
def test(arg)
    a = 0
    if arg > 5:
        a = 1
   return a

def main():
    arg = random.randrange
    z = test(arg)
    if z ==1:
        Print('Will this work?')
Thank both of you , now i think i can grasp functions.
(Sep-30-2017, 08:16 PM)Rius2 Wrote: [ -> ]so in my case it would be:
arg = random.randrange

Well, no.  You never call random.randrange, so arg is just a reference to the function itself.  So "Will this work" should never be printed.
Any function returns an object which you can assign to a variable.
So you define one. Simplified because I am lazy today:
def test(arg):
    return a
Then define another:
def second(some_argument):
    b = test(some_argument)
    if b != 'stupid example':
        return 'Good enough'
Now call 'second':
s = 'No?'
second(s)
You can pass any argument to a function and use it inside another one. some_argument could be any python object, however, it is called. Of course, its type has to be suitable to use it at all.