Skip to content Skip to sidebar Skip to footer

Python Alternatives To Global Variables

import random #----------------------------------------------# def main(): create_list_and_find_max_and_min(10) the_smart_way() #------------------------------------

Solution 1:

Yes, there are two alternatives.

First, you can pass the values around instead of using globals. For example, create_list_and_find_max_and_min can create the array locally and return it, then you can pass it in to the_smart_way:

import random  

#----------------------------------------------#defmain():  
    my_array = create_list_and_find_max_and_min(10)  
    print the_smart_way(my_array)
#----------------------------------------------#defcreate_list_and_find_max_and_min(n):
    my_array = []
    n = input("How many numbers do you want in your array?:")
    for i inrange(n):
        my_array.append(random.randint(1,n))
    print"My array is:", my_array
    #----------------------------------------------#min = my_array[0]
    for number in my_array:
        ifmin > number:
            min = number
    print"The minimum value in the array is:", min#----------------------------------------------#max = my_array[0]
    for number in my_array:
        ifmax < number:
            max = number
    print"The maximum value in the array is:", maxreturn my_array
#----------------------------------------------#defthe_smart_way(my_array):
    # "This one uses the built-in Python functions for min/max..."
    min_my_array = min(my_array)
    max_my_array = max(my_array)
    return min_my_array, max_my_array
#----------------------------------------------#if __name__ == '__main__':
    main()

Second, you can create a class that encapsulates the data and the functions that operate on that data:

import random  

#----------------------------------------------#classMyArrayClass(object):
    defcreate_list_and_find_max_and_min(self, n):
        self.my_array = []
        n = input("How many numbers do you want in your array?:")
        for i inrange(n):
            self.my_array.append(random.randint(1,n))
        print"My array is:", self.my_array
        #----------------------------------------------#min = self.my_array[0]
        for number in self.my_array:
            ifmin > number:
                min = number
        print"The minimum value in the array is:", min#----------------------------------------------#max = self.my_array[0]
        for number in self.my_array:
            ifmax < number:
                max = number
        print"The maximum value in the array is:", max#----------------------------------------------#defthe_smart_way(self):
        # "This one uses the built-in Python functions for min/max..."
        min_my_array = min(self.my_array)
        max_my_array = max(self.my_array)
        return min_my_array, max_my_array
#----------------------------------------------#defmain():
    my_array = MyArrayClass()
    my_array.create_list_and_find_max_and_min(10)  
    print my_array.the_smart_way()
#----------------------------------------------#if __name__ == '__main__':
    main()

You should probably understand the reasons global variables are bad practice.

Imagine that you want to create two arrays. With global variables, the second one will replace the first one, which will be gone forever.

create_list_and_fix_max_and_min(10)
create_list_and_fix_max_and_min(20)
# No way to operate on the original array!

With a local variable, you can store both of them:

my_array_1 = create_list_and_fix_max_and_min(10)
my_array_2 = create_list_and_fix_max_and_min(20)
the_smart_way(my_array_1)

Using an object provides the same benefit; the difference between the two ultimately comes down to whether the operations are part of the meaning of the data, or whether the data stand alone and the operations are generic. (Or, sometimes, whether you're more of a functional snob or an OO snob…)

Solution 2:

Functions do things to objects and then return results. You want to keep functions dead-simple and perform all of your logic and processing outside of the function. This will remove the need for global variables and will make your code much, much easier to read.

That being said, here is how I would attack your problem:

import random  

defrandom_list(n=None):
  n = n orint(raw_input('How many numbers do you want in your list? '))    

  return [random.randint(1, n) for i inrange(n)]

if __name__ == '__main__':
  my_list = random_list(10)
  minimum, maximum = min(my_list), max(my_list)

  print'My list is ', my_list
  print'The minimum value in the list is ', minimum
  print'The maximum value in the list is ', maximum

Solution 3:

Here is how I would do this:

import random  

#----------------------------------------------#
def main():
    # note that input can be dangerous since it evaluates arbitrary code
    n = int(raw_input("How many numbers do you want in your array?: "))
    my_list = [random.randint(1, n) for_ in range(n)]
    find_max_and_min(my_list)  
    the_smart_way(my_list)
#----------------------------------------------#
def find_max_and_min(seq):
    print"My array is:", seq
    #----------------------------------------------#
    min_num = seq[0]# Don't want to use same names as bultins herefor number in seq:
        if number < min_num:
            min_num = number
    print"The minimum value in the array is:", min_num
    #----------------------------------------------#
    max_num = seq[0]for number in seq:
        if number > max_num:
            max_num = number
    print"The maximum value in the array is:", max_num
#----------------------------------------------#
def the_smart_way(seq):
    # "This one uses the built-in Python functions for min/max..."# No need for temp variables hereprint min(seq), max(seq)
#----------------------------------------------#if __name__ == '__main__':
    main()

Post a Comment for "Python Alternatives To Global Variables"