Python学习笔记一:变量和简单数据类型

Python学习笔记一:变量命名及使用

一、变量命名

首先我们要知道什么是变量,变量就和我们学的数学中的‘x’是一样的效果,用于在python中存储一个我们赋予的值,这个值与变量相关联,如:message=‘Hello World’,就是将Hello World这一字符串赋值给messag
1.变量名只能包含字母,数字,下划线,且不能以数字为开头,如:name_1正确,但1_name就是错误的。

2.不能将python中的关键字和函数名用于变量名。python保留字可以在python中输入
`

>>>import keyword`
>>>keyword.kwlist` 

得到保留字:

['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']`

3.变量名应简短同时具有描述性,如student好于s,student_age好于s_a

二、变量的使用

1.避免使用错误,如:

>>>student='Li Hua'
>>>print(studnt)
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    print(studnt)
NameError: name 'studnt' is not defined
>>> 

程序返回错误,找不到变量名,这是由于我们在输入时误将student中的e遗漏,导致出错。编程中这是常犯错误,一定要细心

2.变量要使用必须赋值
如name=‘Li Hua’,这样才能在函数中使用变量name


  • (注:新手上路,如有不足之处,请各位大佬多多批评指正)***

猜你喜欢

转载自blog.csdn.net/GAO_mm/article/details/106766548