变量常量
变量命名规则
1、变量名只能由字母、数字、下划线组成
2、变量名的首个字符不可以是数字
3、不能使用Python关键字作为变量名
变量命名方式
1、驼峰式
AgeOfOldboy = 56
NumberOfStudents = 80
2、下划线(Python官方推荐)
age_of_oldboy = 56
number_of_students = 80
不建议的方式: 变量名使用中文、拼音; 变量名过长; 变量名词不达意;
常量
常量即不变的量, 在程序运行过程中不会改变的量。在Python中并没有语法的常量, 一般以全部为大写的变量名来代表常量。
AGE_OF_OLDBOY = 56
用户与程序交互
通过input, 可以在执行脚本时进行输入操作
name = input("What is your name?")print("Hello" + name)
代码注释分单行和多行注释, 单行注释用#,多行注释可以用三对双引号""" """
代码注释的原则:
1、不用全部加注释,只需要在自己觉得重要或不好理解的部分加注释即可
2、注释可以用中文或英文,但不要用拼音
基本数据类型
在Python中, 定义变量时并不需要强制指定类型
数字
#int 整型, 在32位系统中, 位宽是32位; 在64位系统中, 位宽是64位
a = 2**60type(a)#
#long 长整型, 在Python中, 理论位宽根据内存决定#注: Python3中不再有long类型
b = 2**64type(b)#在Python3中
#float
c = 3.4type(c)#
字符串
#所有加了引号的字符都被认为字符串#单引号与双引号没有区别
name = "Leney"hometown= 'ShangHai'msg= '''My name is Leney'''
#多引号可以直接定义多行字符串中
lyric = '''Gotta remember we live what we choose
It’s not what you say, it’s what you do
And the life you want is the life you have to make'''
布尔型
#布尔值, 只有两个值True和False, 用于逻辑判断
a = 3b= 10
print(a > b) #False
print(a < b) #True
流程控制
分支
a = 3
#单分支
if a >0:print("The number is a positive integer")#双分支
if a >0:print("The number is a positive integer")else:print("The number is not a positive integer")#多分支
if a >0:print("The number is a positive integer")else if a <0:print("The number is a negtive integer")else:print("The number is zero")
循环
#while#打印从0到100的循环程序
count =0while count <= 100:print("loop", count)
count+= 1
#while的死循环, 理论上回一直执行
count =0whileTrue:print("loop", count)
count+= 1
#终止循环
count =0while count <= 100:print("loop", count)if count == 5:break #通过break会直接终止该循环
count += 1
#continue语法#以下为只输出0到100中5的倍数
count =0while count <= 100:
count+= 1
if count % 5:continue
print("loop", count)#while else 语法
count =0while count <= 5:
count+= 1
print("loop", count)else:print("循环已正常执行结束")