目录
Python 3 基础语法(菜鸟教程)
https://www.runoob.com/python3/python3-tutorial.html
一、语法基础
1、转义字符
1)字符串中包含,反斜杠、单引号、双引号时,要使用反斜杠对这些字符进行转义;
- 反斜杠:\\
- 单引号:\'
- 双引号:\"
2)字符串中包含,换行,回车,水平制表符,退格时
- 换行:\n
- 回车:\r
- 水平制表符:\t
- 退格:\b
# 转义字符
print('1、hello\nworld.')
print('2、hello\rworld. ') # world覆盖掉hello
print('3、hello\tworld.')
print('4、hello\b world.') # o被删除
print('5、https:\\\\mp.csdn.net\\')
print('6、老师说:\'大家好\'')
print('7、老师说:\"大家好\"')
输出结果:
1、hello
world.
world.
3、hello world.
4、hell world.
5、https:\\mp.csdn.net\
6、老师说:'大家好'
7、老师说:"大家好"
2、原字符
可让字符串中的转义字符不生效,在字符串前加上r或R。
# 原字符
print(r'1、hello\nworld.')
print(R'2、hello\nworld.')
输出结果:
1、hello\nworld.
2、hello\nworld.
注意事项:使用原字符时,字符串最后一个字符不能是\
print(r'1、hello\nworld.\') # 会报错
3、保留字
import keyword
print(keyword.kwlist)
输出结果:
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', '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']
4、标识符
变量、函数、类、模块、其他对象起的名字,叫标识符,不能使用保留字。
规则:
- 字母,数字,下划线
- 不能以数字开头
- 不能是保留字
- 严格区分大小写
5、变量
name = '玛利亚'
print(name)
print('标识符:',id(name))
print('类型:',type(name))
print('值:' , name)
输出结果:
玛利亚
标识符: 1579111933584
类型: <class 'str'>
值: 玛利亚