Next Generation Emulation banner
1 - 9 of 9 Posts

· Registered
Joined
·
3 Posts
Discussion Starter · #1 ·
Hello Everyone,

Can anyone tell me how to set a global variable inside a function in python? Also, check the below code or anyone knows the better way to learn python in depth. Any recommendation on below code is it right or not.

globvar = 0
def set_globvar_to_one():
global globvar # Needed to modify global copy of globvar
globvar = 1
def print_globvar():
print globvar # No need for global declaration to read value of globvar
set_globvar_to_one()
print_globvar() # Prints 1
 

· No sir, I don't like it.
Joined
·
7,022 Posts
Indeed. Guess I'll answer the question though.

Global variables must be defined in main() before the function is called.

If you wish to modify a previously defined global variable within a function, you need to to use the "global" keyword.

Code:
x=0

def example()
global x
x += 1
print x

example()
Should display "1" instead of complaining about being undefined.
 

· Premium Member
Joined
·
19,572 Posts
I think this is just a spam account and the question sounds fishy. Setting a global variable in a function? that alone sounds quite funny to me as he should know what a global variable is and he just need to set the value when needed.
 

· No sir, I don't like it.
Joined
·
7,022 Posts
That's because python REQUIRES you to tab out your functions, loops, and conditional statements.

The reason our example code isn't indented (tabbed) is because pressing the tab key just moves the cursor selection around on the webpage. We should have just typed the example up in Notepad and copy-pasted it, but oh well...
 

· Read Only
Joined
·
10,484 Posts
That's because python REQUIRES you to tab out your functions, loops, and conditional statements.

The reason our example code isn't indented (tabbed) is because pressing the tab key just moves the cursor selection around on the webpage. We should have just typed the example up in Notepad and copy-pasted it, but oh well...
Sorry for the really late reply but there is an insert code reply feature.

JavaScript:
const greetings = (name) => {
    return `Hello ${name}`
}

greetings('Silenus') // returns Hello Silenus.
It seems to have Python support too.
Actually is the first time I'm using this.
 
1 - 9 of 9 Posts
This is an older thread, you may not receive a response, and could be reviving an old thread. Please consider creating a new thread.
Top