python之变量进阶

变量和数据分开存储

变量中记录数据的地址叫引用

id()为数据的内存地址

可变和不可变类型

不可变

数字类型:int 、bool、float、complex、long(2.x)

字符串:str

元组:tuple

 可变

列表:list

字典:dict

列表 内元素的添加删除不会改变列表地址

字典key只能使用不可变类型 

hash()函数

提取特征码,只能提取不可变类型

设置字典的键值对时,会首先对key进行hash已决定如何在内存中保存字典的数据,以方便后续对字典的操作;增、删、改、查

键值对key必须是不可变类型

键值对value可以是任意类型的数据

局部变量和全局变量

全局变量

num=10
def demo1():
    num=99
    print("demo1 is %s"%num)
def demo2():
    print("demo2 is %s"%num)
demo1()
demo2()
--------------------
D:\Anaconda\python.exe D:/Pycharm/PycharmProjects/python进阶语法/k01_全局变量.py
demo1 is 99
demo2 is 10

Process finished with exit code 0

函数内不会改变全局变量的值,C语言在不定义新变量的情况下是改变的。

#include <stdio.h>
#include <stdlib.h>
int a=50;
void demo1(){
    int a=10;      //不改变a的值
    printf("1-%d\n",a);
}
void demo2(){

    printf("2-%d\n",a);
}
int main()
{

    printf("%d\n",a);
    demo1();
    demo2();
    return 0;
}
-----------------
50
1-10
2-50

Process returned 0 (0x0)   execution time : 0.059 s
Press any key to continue.
---------------------
#include <stdio.h>
#include <stdlib.h>
int a=50;
void demo1(){
    a=10;              //改变a的值
    printf("1-%d\n",a);
}
void demo2(){

    printf("2-%d\n",a);
}
int main()
{

    printf("%d\n",a);
    demo1();
    demo2();
    return 0;
}
---------------------
50
1-10
2-10

Process returned 0 (0x0)   execution time : 0.622 s
Press any key to continue.

在函数内部修改全局变量的值

使用global声明变量名

num=10
def demo1():
    global num #赋值时就不会创建局部变量
    num=99
    print("demo1 is %s"%num)
def demo2():
    print("demo2 is %s"%num)
demo1()
demo2()
---------------------
D:\Anaconda\python.exe D:/Pycharm/PycharmProjects/python进阶语法/k02_修改全局变量.py
demo1 is 99
demo2 is 99

Process finished with exit code 0

函数内参数要在函数调用前声明

开发时应该把模块中的所有全局变量定义在所有函数上方,就可以保证所有的函数都能够正常的访问到每一个全局变量了。

shebang(选择解释器)--import模块---全局变量---函数定义---执行代码

猜你喜欢

转载自blog.csdn.net/qq_41761599/article/details/88886112