Cretan
Cretan

Reputation: 1

"Global" variable from a module can not be changed/used in the scope of a function from another module?

I am writing code for my uni , when I stumbled upon an error. We are studying Modular Programing in Python.

I created a module for keeping my variables organized which are so far only two :

when I try to use participants variable in another module I get the warnings :

Local variable 'participants' value is not used and Shadows name 'participants' from outer scope

The code error I am getting is not being able to change participants values in my main program after using the function from one of my modules which should indeed change participants values.

Here is the module I am trying to use the "global" variable participants in:

from Variables import *

def read_data():
    n = int(input("Enter the number of participants:"))
    participants = n # warnings and "errors"
    for i in range(n):
        score_list.append(int(input()))

Here is the simple Module for my variables

participants = 0
score_list = []

My Question is :

-How do I change the value of participants in my function from another module and it being kept changed trough the whole program ? -Why do I not have any errors with the score_list ?

I am sorry if I wrote something ambiguous or in a disorderly fashion ,it is my first time asking for advice on stack overflow.

Upvotes: 0

Views: 30

Answers (1)

chepner
chepner

Reputation: 530823

You can only operate on the actual variable in the Variables module, not any "local" global variable initialized from Variables.participants.

import Variables


def read_data():
    n = int(input("Enter the number of participants:"))
    Variables.participants = n
    for i in range(n):
        score_list.append(int(input()))

If you aren't worried about other modules that import Variables seeing your change, and do only care about a "local" global, you need to use global participants to avoid creating a function-local variable by the same name.

from Variables import *

def read_data():
    global participants

    n = int(input("Enter the number of participants:"))
    participants = n # warnings and "errors"
    for i in range(n):
        score_list.append(int(input()))

Upvotes: 2

Related Questions