0

I'm working on a school project. I made a test version of my program, because I'm new to Python and I only have experience with C#, so I'm still learning te basics. My problem is the following: Before the function "Fill_Array()" I declared a variable (" max_element_var") that is supposed to store the max number of elements that can be stored in the array ("content_array"). Later in the function I change it's value to the input of the console, which happens, and the function runs as it should, the only problem being is that outside the function the value of " max_element_var" stays "None". What should I do in order to fix this?

#__Test__#
def Test():
    class Que:
        def __init__(self, content, max_element ,actual_elements):
            self.content = content
            self.max_element = max_element
            self.actual_elements = actual_elements

    max_element_var = None
    content_array = []
    def Fill_array():
        print("What should be the max number of elements that can be stored in the array? (Type in an integer!)")
        max_element_var = int(input())
        if(max_element_var>0):
             import random
             random_var = random.randrange(0,max_element_var)
             for x in range(max_element_var-random_var):
                 content_array.append(x)             
        else:
            print("It has to be more than 0!")
            Fill_array()   
    Fill_array()

    actual_elements_var = len(content_array)

    que = Que (content_array, max_element_var, actual_elements_var)

    print("Content: ", que.content)
    print("Max number of elements: ", que.max_element)
    print("Actual number of elements: ", que.actual_elements)
#__Test__#

#__Full__#
def Full():
    pass
#__Full__#

#__Version_selector__#
def Version_selector():
    print("Which version should be used? (Type in the number!)")
    print("1 - Test")
    print("2 - Full")
    answer = int(input())
    if(answer == 1):
        Test()
        Version_selector()
    elif(answer == 2):
        Full()
        Version_selector()
#__Version_selector__#
Version_selector()
  • Some critiques: 1) Is there a reason you declared a local class "Que" inside your function? There are exceptions [but this is generally not a good idea and overly complicates your code](https://stackoverflow.com/questions/22497985/is-it-a-bad-idea-to-define-a-local-class-inside-a-function-in-python). 2) Module imports are also normally never done inside functions i.e. `import random`. 3) For your purpose Version_selector should not be calling itself recursively. Better to use while loop. – DarrylG May 31 '20 at 22:19
  • @elitofsly--convertedthe comments above to create an answer to help simplify things, hopefully. Don't forget the [Zen of Python](https://www.python.org/dev/peps/pep-0020/) – DarrylG May 31 '20 at 22:48

3 Answers3

1

Consider the following code. In the code below you persumably change the value of x but in fact there is a big difference between the x inside the function and outside. The x inside the function is a local variable and will "disappear" once the function ends. If you want to save the value of x you must use return x and save the outcome to a variable. For example, See the function a_saving_example(x)

you may also use a global variable though some say it is bad practice and it is better to use return in your function.

def times_two(x):
    x = x * 2

x = 5
print(x)
times_two(x)
print(x)

output:

5
5

saving example:

def a_saving_example(x):
    x = x * 2
    return x

x = 5
print(x)
x = a_saving_example(x)
print(x)

output:

5
10
snatchysquid
  • 1,283
  • 9
  • 24
0

In python variables are automatically created as local, in the scope of the function which used them alone. To solve your problem you may either (1) return the variable, passing it from one function the other explicitly. (2) declare it as global so all functions have access to it.

More about scopes here and here.

DoreenBZ
  • 328
  • 1
  • 8
0

Modified code to correct some issues.

  1. Import normally done at top of module (not within functions)
  2. Remove nested class definition inside function (obfuscates things in simple code)
  3. Changed recursive calls to a while loop (a better way to repeat execution of a function from beginning in Python since no tail recursion).

Code Refactoring

import random

class Que:
  def __init__(self, content, max_element ,actual_elements):
      self.content = content
      self.max_element = max_element
      self.actual_elements = actual_elements

def Fill_array():
  " Returns requested size and array "
  while True:
    prompt = """"What should be the max number of elements that can be stored in the array?  Type in an integer!: """
    max_element_var = int(input(prompt))
    if max_element_var > 0:
      random_var = random.randrange(0,max_element_var)
      return max_element_var, [x for x in range(max_element_var-random_var)]
    else:
      print("It has to be more than 0!")

def Test():
  max_element_var, content_array = Fill_array()
  actual_elements_var = len(content_array)
  que = Que (content_array, max_element_var, actual_elements_var)

  print("Content: ", que.content)
  print("Max number of elements: ", que.max_element)
  print("Actual number of elements: ", que.actual_elements)
#__Test__#

#__Full__#
def Full():
    pass
#__Full__#

#__Version_selector__#
def Version_selector():
  while True:
    prompt = """Which version should be used? (Type in the number!)
    1 - Test
    2 - Full
    3 - Quit\n\t"""

    answer = int(input(prompt))
    if answer == 1:
      Test()
    elif answer == 2:
      Full()
    else:
      break

#__Version_selector__#
Version_selector()
DarrylG
  • 16,732
  • 2
  • 17
  • 23