python function------local variable and global variable

Local Variable

  1. Local variable: Literally, it is a variable that can only be used locally, that is to say, a variable that can only be accessed in a specific function or subprogram, and its scope is only inside the function. For Siemens PLC, some local variables are pre-defined in FC or FB, such as in the interface data area, when the main program is called, parameters can be provided for interface variables such as input and output. Therefore, when you define a local variable in FC1, it cannot be called directly if it is not defined in FC2.
  2. It is only valid within the function in which it is defined, but the program allocates memory only once, and the variable will not disappear after the function returns; although the lifetime of a static local variable is the entire project, its function is still the same as that of a local variable, that is, it can only be used in Use the variable within the function that defines the variable. After exiting the function, although the variable still exists, it cannot be used.

Global Variable

  1. Global variable: As the name suggests, it is a variable that can be used by the entire program, and a variable that can be used anywhere. Of course, the premise is that you must define a variable. It is defined outside a function or subprogram, and can also be called an external variable. For example, for Siemens I, Q, M and other variables.

  2. Static global variables: Only valid in the file where it is defined, the effect is the same as global variables, but inside this file.

Note: If global variables and static variables are not initialized manually, they are initialized to 0 by the compiler. The value of a local variable is unknown.

The most obvious difference between static local variables and global variables is that global variables can be used by all functions after they are defined, but static local variables can only be used in one function.

example

Source code:

def discounts(price, rate):
    final_price = price * rate
    old_price = 88 #这里试图修改全局变量
    print('修改后old_price的值是:', old_price)
    return final_price

old_price = float(input('请输入原价:'))
rate = float(input('请输入折扣率:'))
new_price = discounts(old_price, rate)
print('修改后old_price的值是:', old_price)
print('打折后价格是:', new_price)

insert image description here

global keyword

global declares a local variable as a global variable
insert image description here

Guess you like

Origin blog.csdn.net/qq_53571321/article/details/122781560