Python3 基础语法

以下笔记均为Python在Windows环境下的操作记录

 

  • 启动Python解释器 交互模式

命令行输入python,回车,出现解释器欢迎信息、版本好和授权提示:

1 C:\Users\username\python
2 Python 3.6.5rc1 (v3.6.5rc1:f03c5148cf, Mar 14 2018, 03:12:11) [MSC v.1913 64 bit (AMD64)] on win32
3 Type "help", "copyright", "credits" or "license" for more information.
4 >>>      #主提示符,代码从此处开始输入

 

多行结构需要使用从属提示符”...“

退出解释器:Control-Z或quit()命令,再回车,解释器则以0状态码退出

 1 C:\Users\Aoki>python
 2 Python 3.6.5rc1 (v3.6.5rc1:f03c5148cf, Mar 14 2018, 03:12:11) [MSC v.1913 64 bit (AMD64)] on win32
 3 Type "help", "copyright", "credits" or "license" for more information.
 4 >>> ^Z
 5  
 6 C:\Users\Aoki>
 7  
 8  9  
10 C:\Users\Aoki>python
11 Python 3.6.5rc1 (v3.6.5rc1:f03c5148cf, Mar 14 2018, 03:12:11) [MSC v.1913 64 bit (AMD64)] on win32
12 Type "help", "copyright", "credits" or "license" for more information.
13 >>> quit()
  • 解释器语言

Python源文件编码为UTF-8,因此大多数语言都可以用作Python的字符串、标识符和注释,但需要你的编辑器能识别源文件是UTF-8编码的,并且能支持文件中所有的字符。也可为源文件指定字符编码,方法是在首行后插入特殊的注释行来定义源文件的编码:(encoding指代UTF-8编码)

1 # -*- coding: encoding -*-
  • Python数字运算

接受表达式、 +、-、*、/、(),其中除法的/ 返回的是浮点数,//返回整数,%返回余数。

>>> 17 / 3  # classic division returns a float5.666666666666667
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # result * divisor + remainder
17

运算符**可做幂运算

>>> 5**2
25
>>> 2**8
256
>>> 4**16
4294967296
  • 保留字/关键字

保留字不能用作任何标识符名称,可通过以下命令查看所有保留字:

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

 

  • 注释

单行注释以#开头

多行注释可以用‘’‘开始并以’‘’结尾,或用“”“开始并以”“”结尾

  • 行与缩进

用缩进表示代码块,不需要使用大括号{}

缩进空格数可自定义,但同一代码块的语句缩进空格数要一致

if True:
print ("True")else:
print ("False")
  • 多行语句

一条语句过长时,可以用\实现多行语句

total = item_one + \
        item_two + \
        item_three

语句被[], {}, ()跨行括起来时,不需要用\

total = ['item_one', 'item_two', 'item_three',
'item_four', 'item_five']
  • 数字number类型

整数 int,Python3中只有这一种整型

布尔 bool,包括true,false

浮点数 float,小数

复数 complex,如1+2j、1.1+2.2j

  • 字符串 string

字符串用“ ”或' '圈定,Python中单引号和双引号完全相同,但不能混用:

word = '字符串'
sentence = "这是一个句子。"

转义符为反斜杠 \,使用r可使反斜杠语句不发生转义

this is a line with \n  #此句遇到\n换行
r"this is a line with \n"  #此句不发生换行,结尾的\n为字符串的一部分,正常显示
print("this is a \ngood idea")
print(r"this idea is not bade \n, right")
 
结果
this is a
good idea
this idea is not bade \n,right

 

posted @ 2018-09-12 15:23  realsoong  阅读(245)  评论(0)    收藏  举报