Home > Blockchain >  Why does this python function output include the first variable's value?
Why does this python function output include the first variable's value?

Time:07-18

As a total noob, I encountered the question below while trying to do some exercises online. However, I do not understand the logic here. There's a new function to add salary, but it also prints the first one. Why does the output include the 8000 while printSalary() is a new function command?

salary = 8000

def printSalary():
  salary = 12000
  print("Salary:", salary)
  
printSalary()
print("Salary:", salary)

The Output:

Salary: 12000
Salary: 8000

CodePudding user response:

In python, whenver you define a variable inside a function, it is initialized as a local variable and then can only be used inside that particular function.

In your example, the printSalary() function doesn't update the global variable salary but rather makes a new local variable with the same name. If you want to update the salary variable in global scope, you can use the global keyword.

Here's the code for your reference:

salary = 8000

def printSalary():
  global salary
  salary = 1200
  print("Salary:", salary)
  
printSalary()
print("Salary:", salary)

This will give the output as:

Salary: 1200
Salary: 1200

Hope this clarifies your doubt. You can learn more about this from here.

CodePudding user response:

The exercise is meant to demonstrate global vs local variables. A local variable named "salary" is created and used in the function.

https://www.w3schools.com/python/python_variables_global.asp

  • Related