Python3之基础语法
2018-04-01 11:18
495 查看
Python3之基础语法
编码
默认:源码文件以UTF-8编码,字符串都是unicode字符串指定:
# -*- coding: cp-1252 -*-
标识符
第一个字符:字母表中的字符或下划线 _其它部分:由字母、数字、下划线 _ 组成
大小写敏感
python3中,允许非ASCII标识符
关键字
标准库提供了keyword模块,可输出当前版本的所有关键字>>> 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']
注释
单行:以 # 开头多行:多个 # 号;”’ 或 “”“
# 注释1 # 注释2 ''' 注释3 注释4 ''' """ 注释5 注释6 """
缩进
使用缩进来表示代码块,不需要大括号 {}缩进的空格数是可变的
同一代码块的语句必须包含相同的缩进空格数,否则导致运行错误
多行语句
一般一行写完一条语句语句很长时,使用反斜杠 \ 实现多行语句
[], {}, ()中的多行语句,不需要反斜杠 \
total1 = item_one + \ item_two + \ item_tree total2 = ['item_one', 'item_two', 'item_three', 'item_four']
数字类型 Number
int:整数(仅一种整数类型int,表示长整型,没有python2中的Long)bool:布尔(true, false)
floot:浮点数(1.23,3E-2)
complex:复数(1+2j,1.1+2.2j)
字符串 String
单行:单引号 ‘xxx’、双引号 “xxx”,(两者使用完全相同)多行:三引号 ”’ 或 “””
word1 = 'str' word2 = "str" paragraph = '''aaaaa, bbbbb'''
转义符 \,使用 r 让反斜杠不发生转义
# 实例 print('hello\nroob') print(r'hello\nroob') # 输出 hello roob hello\nroob
按字面意义级联字符串,如:”this “”is “”string”会被自动转换为 “this is string”
运算符:+ 连接;* 重复
print('hello ' + 'world') # hello world print('hello' * 2) # hellohello
索引方式:从左往右,以 0 开始;从右往左,以 -1 开始
截取语法:变量[头下标:尾下标],从头下标到尾下标前(不包括尾下标)
str = 'Runoob' print(str[-1]) # 倒数第一个 b print(str[0:-1]) # 第一个到倒数第二个 Runoo print(str[2:]) # 第三个及后面的所有字符 noob
字符串不能改变
没有单独的字符类型,一个字符就是长度为1的字符串
空行
用于分隔两段不同功能或含义的代码,便于代码的维护和重构不属于python语法的一部分
等待用户输入
执行下面的语句,输入内容后,按下 enter 键后,输出内容>>> input("输入:") 输入:aaa 'aaa'
同一行显示多条语句
在同一行使用多条语句,使用分号 ; 分隔代码组
相同缩进的一组语句构成一个代码块(代码组)想if, while, def, class这样的符合语句,首行以关键字开始,以冒号 : 结束,之后的代码构成代码组,首行及后面的代码组成为一个子句(clause)
输出 print
默认换行实现不换行:在变量末尾加上 end=” “
x = "a" y = "b" print(x) print(y) print(x, end = " ") print(y, end = " ") # 输出 a b a b
import 与 from…import
用于导入相应的模块:- 将整个模块导入:import somemodu
9912
le
- 从某个模块中导入某个函数:from somemodule import sonefunction
- 下哦那个某个模块中导入多个函数:from somemodule import firstfunc, secondfunc, thirdfunc
- 将某个模块中的全部函数导入:from somemodule import *
命令行参数
如,-h 参数查看个参数帮助信息:$ python -h usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ... Options and arguments (and corresponding environment variables): -c cmd : program passed in as string (terminates option list) -d : debug output from parser (also PYTHONDEBUG=x) -E : ignore environment variables (such as PYTHONPATH) -h : print this help message and exit [ etc. ]
内容来源:http://www.runoob.com/python3/python3-basic-syntax.html
相关文章推荐
- python基础语法(4)
- Python基础--正则表达式基本语法以及re模块
- Python语法基础(三):切片
- Python语法基础(七):用户文字输入
- Python的基础语法
- python基础语法
- 01Python基础语法
- python3基础语法二
- python机器学习基础语法入门
- python基础语法
- Python 基础语法
- week01_python基础语法__01
- Python 基础语法(二)
- python 基础语法
- 王亟亟的Python学习之路(三)-基础语法以及基本数据类型
- python和shell基础语法对比
- Python 基础语法(一)
- Python 语法基础
- Python基础语法04-数据结构
- python3.x IDLE学习及基础语法(学习head first python 第一章)