Python Forum
Declaring a Global Variable in a Function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Declaring a Global Variable in a Function
#1
I am sorry. I know that this is probably a stupid question. But I am just learning Python and have spent hours trying to figure out what I am doing wrong when trying to declare a global variable in a function. What I am trying to do is modify a variable in the function so that the changed value will be associated with it outside the function. However, when I try to use the variable outside the function it reverts to the initial value set before it was changed, and of course if I don't set an initial value outside the function I get an error saying the variable is not defined. This is a simplified example of what I am trying to understand:

solution = 0

def perform_math():
    global solution
    x = 1
    x = 2
    solution = x + y
    return solution

print(solution)
The program prints 0 instead of 3 when I want it to print 3.
Reply


Messages In This Thread
Declaring a Global Variable in a Function - by Bob1948 - Sep-14-2019, 10:12 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Variable for the value element in the index function?? Learner1 8 672 Jan-20-2024, 09:20 PM
Last Post: Learner1
  Variable is not defined error when trying to use my custom function code fnafgamer239 4 604 Nov-23-2023, 02:53 PM
Last Post: rob101
  It's saying my global variable is a local variable Radical 5 1,187 Oct-02-2023, 12:57 AM
Last Post: deanhystad
  Printing the variable from defined function jws 7 1,339 Sep-03-2023, 03:22 PM
Last Post: deanhystad
  Function parameter not writing to variable Karp 5 955 Aug-07-2023, 05:58 PM
Last Post: Karp
  declaring object parameters with type JonWayn 2 911 Dec-13-2022, 07:46 PM
Last Post: JonWayn
  Retrieve variable from function labgoggles 2 1,058 Jul-01-2022, 07:23 PM
Last Post: labgoggles
  Cant transfer a variable onto another function KEIKAS 5 1,906 Feb-09-2022, 10:17 PM
Last Post: deanhystad
  Function global not readable by 'main' fmr300 1 1,357 Jan-16-2022, 01:18 AM
Last Post: deanhystad
  Variable scope - "global x" didn't work... ptrivino 5 3,071 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