官术网_书友最值得收藏!

Variables

The second major building block of a Python program is called a variable. A variable is pretty much just a box for storing a data value. The variable has a name and we can use that name to access the data stored in the variable or to replace the data with a new value.

The function parameters in the previous examples were variables, as was area:

(name, radius):  

To set the data stored in a variable, we use an assignment statement. An assignment is a statement, so remember this means that it can't be combined with any other statement. It gets a line of source code all for itself and the expressions that are part of it.

An assignment statement consists of the variable's name on the left-hand side of an equal to symbol and the value we want to store in the variable on the right-hand side, as shown in the following code:

outer = "Hello world"  

If the variable didn't already exist, it will be created. Irrespective of whether the variable existed before or not, the value is stored in the variable.

Variables that are created inside a function are only visible inside that function and each time the function runs they're created a new.

The following code provides an example of this in action:

outer = "Hello world"  
def example_function(param): 
    inner = "Hello function: {}".format(param) 
    print(inner, outer) 
example_function("first") 
example_function("second") 
print(inner) 

The last line of the preceding example demonstrates that the variable created inside the function does not exist for code outside the function, as shown in the following output of the code:

This code example also shows what happens when we try to ask Python to do something impossible. It tells us what we did wrong and gives us the information about where the problem occurred and how we got there.

主站蜘蛛池模板: 潞城市| 哈密市| 平远县| 库伦旗| 方山县| 积石山| 财经| 嫩江县| 靖安县| 黔西县| 洛隆县| 休宁县| 夏邑县| 柳江县| 玛纳斯县| 奉节县| 丹阳市| 内江市| 隆子县| 突泉县| 济宁市| 新竹市| 汾西县| 门头沟区| 长岛县| 平邑县| 丹江口市| 磴口县| 吴桥县| 汝阳县| 山阳县| 辽源市| 乌拉特后旗| 漯河市| 郧西县| 长垣县| 霸州市| 德江县| 洛扎县| 临邑县| 柞水县|