-1

Greeting all, would like to seek for your advice on the encountered issue as the output is not as expected.

my code as below:

score = []
total = 0
def mark():
    counter = 1
    size = int(input("Please Enter The Number of Subjects in Semester: "))
    for cnt in range (size):
        value = int(input(f"Please Enter Mark of Subject {counter} : "))
        score.append(value)
        counter = counter + 1
    total = sum(score)

mark()
print(score)
print(total)

and the output is:

Please Enter The Number of Subjects in Semester: 2
Please Enter Mark of Subject 1 : 10
Please Enter Mark of Subject 2 : 10
[10, 10]
0

Question 1: How can I turn the print(total) output to be sum of the values in the list instead of 0 without using Global variable?

Question 2: Why the list can get append but the score not making the sum?

TAN WEISON
  • 9
  • 1
  • 5
  • It is an issue of scope. You need to include the line ```global total``` inside your function. – sarartur Feb 17 '21 at 06:35
  • Get used to passing parameters into functions and returning results: `return score, total`, and on the calling side: `score, total = mark()`. – deceze Feb 17 '21 at 06:37
  • *"Why the list can get append but the score not making the sum?"* — Because you're *mutating* the list object, which remains the same list object, but you're *reassigning* variable `total`, which makes it a function-local variable entirely independent of the global variable of the same name. – deceze Feb 17 '21 at 07:55

1 Answers1

0

Add

global total

as the first line of your function. As it is, the total in your function is a separate variable from the total outside. As an alternative, you might consider returning score and total from the function; as a rule, global variables are a Bad Idea.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30