Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Globals vs Function
#1
Is using a function like this to define variables ok? 
def variables(a, b):
    a = something
    b = another

def some_function():
    do something with variables(a).
    do something with variables(b).
What is the difference between using a function to define variables and just using globals like this?
a = something
b = another

def some_function():
    do something with a.
    do something with b.
Reply
#2
Hello!
If you want to do something with outer to the function variables it's better to pass them as parameters.

num1 = 44
num2 = 55

def addition(a, b):
    returnt a + b

result = addition(num1, num2)
print(result)
Output:
99
Variables defined within the function are local to this function and exist as long as the function is running.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
When you are using global variables in a local scope, you are cross scope boundaries. This can become confusing and hard to track. If you run into a problem with the values of a and b, it can be harder to figure out where a and b are being modified. If you are passing them around as parameters and return values, it becomes easier to track down where they might get modified.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  why globals() exits python when quit() is aliased as q abc12346 4 687 May-23-2023, 08:56 AM
Last Post: Gribouillis
  How to avoid exec(), globals(), locals(), eval() paul18fr 10 5,018 Apr-21-2021, 05:53 PM
Last Post: snippsat
  accessing globals from a function Skaperen 8 4,136 Sep-01-2018, 11:50 PM
Last Post: Skaperen
  Use of Globals CWatters 5 3,829 Nov-13-2017, 09:00 PM
Last Post: CWatters

Forum Jump:

User Panel Messages

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