Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to define global variables in a function in Python

How do I declare a global variable in a function in Python?

That is, so that it doesn't have to be declared before but can be used outside of the function.

like image 835
WoooHaaaa Avatar asked Nov 29 '12 14:11

WoooHaaaa


People also ask

Can I define a global variable inside a function in Python?

Global Variables In Python, a variable declared outside of the function or in global scope is known as a global variable. This means that a global variable can be accessed inside or outside of the function.

How do you declare a global variable in Python?

We declare a variable global by using the keyword global before a variable. All variables have the scope of the block, where they are declared and defined in. They can only be used after the point of their declaration.


2 Answers

Yes, but why?

def a():     globals()['something'] = 'bob' 
like image 116
Jon Clements Avatar answered Sep 22 '22 21:09

Jon Clements


def function(arguments):     global var_name     var_name = value #must declare global prior to assigning value 

This will work in any function, regardless of it is in the same program or not.

Here's another way to use it:

def function():     num = #code assigning some value to num     return num 

NOTE: Using the return built-in will automatically stop the program (or the function), regardless of whether it is finished or not.

You can use this in a function like this:

if function()==5 #if num==5:     #other code 

This would allow you to use the variable outside of the function. Doesn't necessarily have to be declared global.

In addition, to use a variable from one function to another, you can do something like this:

import primes as p #my own example of a module I made p.prevPrimes(10) #generates primes up to n for i in p.primes_dict:     if p.primes_dict[i]: #dictionary contains only boolean values         print p.primes_dict[i] 

This will allow you to use the variable in another function or program without having use a global variable or the return built-in.

like image 40
Rushy Panchal Avatar answered Sep 20 '22 21:09

Rushy Panchal