注释
- 单行注释 #
#我是单行注释 - 多行注释 ‘’’ ‘’’
''' 我是多行注释 '''
- 中文支持
#coding=utf-8 print('你好')
变量及类型
在python中,只要定义了⼀个变量,⽽且它有数据,那么它的类型 就已经确定了,不需要咱们开发者主动的去说明它的类型,系统会 ⾃动辨别
可以使⽤type(变量的名字),来查看变量的类型
- Numbers(数字) int(有符号整型) long float complex(复数)
- 布尔类型 true false
- String (字符串)
- List (列表)
- Tuple (元祖)
- Dictionary (字典)
标识符和关键字
- 标识符
标示符由字⺟、下划线和数字组成,且数字不能开头
python中的标识符是区分⼤⼩写的
命名规则:见名知意 驼峰命名法 - 关键字
例如: and as assert while break return print 等,可以通过import keyword来查看关键字
输出
- python中变量的输出
# 打印提升 print('hello world')
- 格式化输出
age=20; name="Zhanxiao" print("我是%s,今年%d岁"%(name,age))
- 常用的格式符号
格式符号 转换
%c 字符
%s 通过str()字符串转换来格式化
%i 有符号十进制整数
%d 有符号⼗进制整数
%u ⽆符号⼗进制整数
%x 或 %X ⼗六进制整数
%e 或 %E 索引符号
%f 浮点实数
%g %f和%e 的简写
%G %f和%E的简写
输入
python2
- raw_input()
- input() 接受表达式
python3 中只有 input() 用法同python2的raw_input()
password = input("请输入密码:")
print('您刚刚输入的密码是:',password)
运算符
- 算数运算符 + - * / % //(取整除) ** (幂)
- 赋值运算符 =
- 复合赋值运算符 += -= *= /= %= **= //=
- 比较/关系运算符 == != <> > < >= <=
- 逻辑运算符 and or not
常用的数据类型转换
print(int(2.4))
print(float("9"))
print(complex(1,8))
print(str(123))
print(repr("3+9"))
print(eval("pow(2,4)")) #eval(expression[, globals[, locals]])
tuple(s ) #将序列 s 转换为⼀个元组
list(s) #将序列 s 转换为⼀个列表
chr(x) #将⼀个整数转换为⼀个字符
unichr(x) #将⼀个整数转换为Unicode字符
ord(x) #将⼀个字符转换为它的整数值
hex(x) #将⼀个整数转换为⼀个⼗六进制字符串
oct(x) #将⼀个整数转换为⼀个⼋进制字符串
if判断语句
-
比较/关系运算符 == != <> > < >= <=
-
逻辑运算符 and or not
age = 50;
if age>20:
print(“年龄大于20”)
if-else
age = 18;
if age>20:
print("年龄大于20")
else:
print("年龄不大于20")
elif (else if)
age = 18;
if age>20:
print("年龄大于20")
elif age>14 and age<=20:
print("2")
elif age>8 and age<=14:
print("3")
else:
print("6")
if 可以嵌套
循环
- while 循环
i = 0 while i<5: print("这是第%d个循环"%(i+1)) i+=1
- while嵌套
- for循环
像while循环⼀样,for可以完成循环的功能。 在Python中 for循环可以遍历任何序列的项⽬,如⼀个列表或者⼀个字符串 等。 name = "alice" for x in name: print(x)
break 和 continue
- break ⽤来结束整个循环
name = "alice" for x in name: if x== 'i': break print(x)
- continue ⽤来结束本次循环,紧接着执⾏下⼀次的循环
name = "alice" for x in name: if x== 'i': continue print(x)
- break/continue只能⽤在循环中,除此以外不能单独使⽤
- break/continue在嵌套循环中,只对最近的⼀层循环起作⽤