Python 基础语法

致谢,菜鸟教程:http://www.runoob.com/python3/python3-tutorial.html

-----------------------------------------------------------------------------------------------

python 基础语法

1.编码

# -*- coding: UTF-8 -*-

2.标识符
第一个字符必须是字母表中字母或下划线 

3.
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']

4.注释
 #  “注释一行“
 ''' 和 """ ”注释一段“

5.
行与缩进
使用缩进来表示代码块,不需要使用大括号 {}

6.
多行语句
A.使用反斜杠(\)来实现多行语句
total = item_one + \
        item_two + \
        item_three
B.在 [], {}, 或 () 中的多行语句,不需要使用反斜杠(\)
total = ['item_one', 'item_two', 'item_three',
        'item_four', 'item_five']

7.
数字(Number)类型
  • int (整数), 如 1, 只有一种整数类型 int,表示为长整型,没有 python2 中的 Long。
  • bool (布尔), 如 True。
  • float (浮点数), 如 1.23、3E-2
  • complex (复数), 如 1 + 2j、 1.1 + 2.2j
8.字符串(String)
  • python中单引号和双引号使用完全相同。
  • 使用三引号('''或""")可以指定一个多行字符串。
  • 转义符 '\'
  • 反斜杠可以用来转义,使用r可以让反斜杠不发生转义。。 如 r"this is a line with \n" 则\n会显示,并不是换行。
  • 按字面意义级联字符串,如"this " "is " "string"会被自动转换为this is string。
  • 字符串可以用 + 运算符连接在一起,用 * 运算符重复。
  • Python 中的字符串有两种索引方式,从左往右以 0 开始,从右往左以 -1 开始。
  • Python中的字符串不能改变。
  • Python 没有单独的字符类型,一个字符就是长度为 1 的字符串。
  • 字符串的截取的语法格式如下:变量[头下标:尾下标:步长]
#!/usr/bin/python3
str='Runoob' print(str) # 输出字符串
print(str[0:-1]) # 输出第一个到倒数第二个的所有字符
print(str[0]) # 输出字符串第一个字符
print(str[2:5]) # 输出从第三个开始到第五个的字符
print(str[2:]) # 输出从第三个开始的后的所有字符
print(str * 2) # 输出字符串两次
print(str + '你好') # 连接字符串
print('------------------------------')
print('hello\nrunoob') # 使用反斜杠(\)+n转义特殊字符
print(r'hello\nrunoob') # 在字符串前面添加一个 r,表示原始字符串,不会发生转义
 

输出结果为:

Runoob
Runoo
R
noo
noob
RunoobRunoob
Runoob你好
------------------------------
hello
runoob
hello\nrunoob

9.等待用户输入

input("\n\n按下 enter 键后退出。")

10.
同一行显示多条语句
Python可以在同一行中使用多条语句,语句之间使用分号(;)分割

11.多个语句构成代码组

代码块、码组:缩进相同的一组语句构成一个代码块,我们称之代码组。

像if、while、def和class这样的复合语句,首行以关键字开始,以冒号( : )结束,该行之后的一行或多行代码构成代码组。

子句:我们将首行及后面的代码组称为一个子句(clause)。






















































































posted @ 2018-12-26 14:55  L-guansheng  阅读(214)  评论(0编辑  收藏  举报