i don't understand how to use a variable outside of a function? - 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: i don't understand how to use a variable outside of a function? (/thread-5371.html) |
i don't understand how to use a variable outside of a function? - Rius2 - Sep-30-2017 from this function: def test(arg) a = 0 if arg >3: a=1 return ahow 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') RE: i don't understand how to use a variable outside of a function? - Larz60+ - Sep-30-2017 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 RE: i don't understand how to use a variable outside of a function? - buran - Sep-30-2017 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 RE: i don't understand how to use a variable outside of a function? - Rius2 - Sep-30-2017 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. RE: i don't understand how to use a variable outside of a function? - buran - Sep-30-2017 here is our tutorial https://python-forum.io/Thread-Basic-Functions RE: i don't understand how to use a variable outside of a function? - nilamo - Oct-04-2017 (Sep-30-2017, 08:16 PM)Rius2 Wrote: so in my case it would be: 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.
RE: i don't understand how to use a variable outside of a function? - wavic - Oct-04-2017 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 aThen 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. |