Python Forum
unexpected output for global variable
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
unexpected output for global variable
#1
Hello,
I am a beginner in python.
I am trying to use a global variable in local namespace i.e. within a function.The program is following:

def my_func():
	global my_var
	print my_var
	my_var=10
my_var=20
my_func()
print my_var * 5
Output:
20 50
The second output is creating little confusion.i think this should simply multiply my_var's value 20 with 5.
Why it is taking my_var's value 10 here?
Reply
#2
This is one of the reasons why global variables are frowned upon and should never be used.

Since the variable is global, the second you execute my_func, you override the global with the value 10, so setting it to 20
is never seen.

This also demonstrates part of a situation that can leave to a very un-easy problem to find. where two functions are setting the value
of my_var, creating a situation of who's on base.

Instead of using a global, pass the desired value as an argument to the function.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Unexpected output Starter 2 476 Nov-22-2023, 12:08 AM
Last Post: Starter
  Unexpected Output - Python Dataframes: Filtering based on Overlapping Dates Xensor 5 702 Nov-15-2023, 06:54 PM
Last Post: deanhystad
  Unexpected output while using random.randint with def terickson2367 1 508 Oct-24-2023, 05:56 AM
Last Post: buran
  It's saying my global variable is a local variable Radical 5 1,156 Oct-02-2023, 12:57 AM
Last Post: deanhystad
  Unexpected output from df.loc when indexing by label idratherbecoding 6 1,186 Apr-19-2023, 12:11 AM
Last Post: deanhystad
  How to combine two output in one variable? ilknurg 2 1,185 Aug-01-2022, 09:31 AM
Last Post: Gribouillis
  Os command output in variable shows wrong value paulo79 2 1,505 Apr-09-2022, 03:48 PM
Last Post: ndc85430
  Command output to Variable ironclaw 1 1,776 Aug-26-2021, 06:55 PM
Last Post: bowlofred
  Getting a GET request output text into a variable to work with it. LeoT 2 2,995 Feb-24-2021, 02:05 PM
Last Post: LeoT
  Variable scope - "global x" didn't work... ptrivino 5 3,034 Dec-28-2020, 04:52 PM
Last Post: ptrivino

Forum Jump:

User Panel Messages

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