系列文章目录
【跟小嘉学习Python 程序设计】第一章 开发环境搭建
【跟小嘉学习Python 程序设计】第二章 Python编程基础概念
【跟小嘉学习Python 程序设计】第三章 Python编程基础
前言
本章节讲解Python的基础内容包括了Hello World、数学运算、浮点数误差问题、类型转换、布尔类型、逻辑操作、比较操作等基础内容。
一、Hello World
虽然 Python 提供有交互式的命令模式,但是很多情况下,对于程序的编写定义在源文件之中,在Python里面所有的源文件的后缀名称必须是 *.py 的格式。
范例:hello.py
#!/usr/bin/env python3
# -*- coding:UTF-8 -*-
print("hello world")
程序执行结果
>python hello.py
hello world
在计算机的世界里面,所有的文件都会存在相应的编码,在 现代的开发之中都会出现许多编码形式,例如 unicode、utf-8、ascII、要求你文件保存的编码与程序中定义的编码必须相同,否则会出现乱码,详细文档可以参考我的另一篇关于字符编码的博客。
本程序之中使用了 print() 函数,函数就是一个完成一个特定功能的代码组织结构。
二、数据类型介绍
在Python之中的数据类型包括整型、浮点型、复数、布尔类型、字符串、列表、元组、字典、日期等,并且全部都是引用传递数据类型。
在其他编程语言里面都会将数据类型分为基本数据类型(使用数值传递)、引用类型(引用传递)。
二、简单的概念介绍
2.1、数学运算
在Python之中支持以下几种数学运算
| No | 运算符 | 描述 |
|---|---|---|
| 1 | * | 乘法运算 |
| 2 | + | 加法运算 |
| 3 | - | 减法运算 |
| 4 | / | 除法运算 |
| 5 | // | 除法运算(求商) |
| 6 | % | 取模运算(求余) |
| 7 | ** | 幂运算 |
注:
在Python3之中,//号的用法而python2之中的除法相同;
除法运算在Python2之中,除法是采用取整的方式,即1/2=0,而在python3之中1/2=0.5,1//2=0;
float also accepts the strings “nan” and “inf” with an optional prefix “+” or “-” for Not a Number (NaN) and positive or negative infinity.
浮点数还包括两个字符串表示的
| 字符串 | 描述 |
|---|---|
| nan | 不是一个数 |
| inf | 表示无穷大 |
例:
>>> type(float('nan'))
<class 'float'>
>>> type(float('inf'))
<class 'float'>
>>> type(float('a'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: 'a'
2.2、浮点数误差累积问题
浮点数的表示是有误差的。0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1

2.3、类型转换
| 内建函数 | 描述 |
|---|---|
| abs(x) | 求x的绝对值 |
| int(x) | 把x转换为整型 |
| float(x) | 把x转换为浮点型 |
| complex(re, im) | 通过re(实数部分),im(虚数部分,默认为零)构造一个复数类型 |
既然提到了复数类型,负数可以通过z.real获得实数部分,z.imag获得虚数部分。
例如
z = 1 + 2j
>>> z.imag
2.0
>>> z.real
1.0
在复数的运算里面,有一个概念叫做共轭复数,通过c.conjugate()方法,可以等到C的共轭复数。
共轭复数:对于复数z=a+bj ,称复数z’=a-bj为z的共轭复数。至于共轭复数的特性,自己参考数学相关知识点。
三、 布尔类型相关
3.1、布尔类型
在python之中布尔类型只有两个值,True和False;注这里的大写。实际上 True和 False 就是1和0,分别表示真和假。
由于它们实际上就是 0 和 1,所以它们可以参加数学运算(但不推荐)。
在Python之中以下几种情况都被认为是False:
- None和False
- 任何数值类型的0:0, 0.0, 0j, Decimal(0), Fraction(0, 1)
- 空的序列或集合:empty sequences and collections: ‘’, (), [], {}, set(), range(0)
3.2、逻辑操作
| Operation | Result |
|---|---|
| x or y | if x is false, then y, else x |
| x and y | if x is false, then x, else y |
| not x | if x is false, then True, else False |
3.3、比较操作
| Operation | Meaning |
|---|---|
| < | strictly less than |
| <= | less than or equal |
| > | strictly greater than |
| >= | greater than or equal |
| == | equal |
| != | not equal |
| is | object identity |
| is not | negated object identity |
四、标准输入/输出
4.1、标准输入
在Python之中存在两个版本的输入函数:input、raw_input 其类型定义如下:
input([prompt]) -> string
raw_input([prompt]) ->string
上述两个函数,都有一个同样的可选参数prompt。[]表示参数可选,prompt为提示字符串。如果你指定了该参数将会输出到标准输出,并且不带空行。该函数将会从用户的输入中读取一行,并且转换为字符串(不带有换行符)。
不管是 input 还是 raw_input 其返回值都是 str 类型(字符串)
4.1.1、input
在 Python 3.x 之中使用 input 函数作为用户输入函数,在Python 2.x 之中虽然也存在有 input 函数,不过其返回值是 value 类型是数据,所以我们不建议在 Python 2.x 版本之中使用 input 函数;
# Python2
input([prompt]) -> value
# Python3
input([prompt]) -> string
通过help()内建函数来查看帮助,我们可以发现,raw_input()返回值是string,而input()的返回值是value,这个value的含义就是值的类型。也就是说,如果你输入的类型是整型,那么他就是整型,如果你输入的浮点型,那么他就是浮点型。
4.1.1、raw_input
在 Python 2.x 之中使用 raw_input 函数作为用户输入函数,在输入字符串的时候,raw_input 函数不需要输入字符串,而input函数输入的时候需要加引号。
如果字符串输入的时候不加引号会抛出一个NameError错误,例如:
NameError: name 'a' is not defined
4.2、标准输出
4.2.1、print
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
- 参数一:
*objects,该参数为可变参数,也就是说可以是多个; - 参数二:
sep='',该参数为默认参数,默认值' ',表示分割符,可变参数的分割符; - 参数三:
end='\n',该参数为默认参数,默认值\n,表示结束符,输出的结尾追加该字符串,也就是说print()默认会打印一个换行 - 参数四:
file=sys.stdout,该参数为默认参数,默认值为sys.stdout,该参数表示要输出的位置,默认为标准输出 - 参数五:
flush=Fasle,该参数为默认参数,默认值为False,表示是否强制刷新缓冲区;
4.2.2、注意事项
1、在Python 2.x 之中 print 是关键字,而不是函数,但是在 Python 3.x 之中,print 是函数,而不是关键字,怎么理解呢?
函数必须要加括号,而关键字则不同,可以加括号,也可以不加括号;
在Python 2.x之中,用help(print)来查看帮助会抛出一个 SyntaxError 的错误
2、在Python 2.x之中,print 语句 如果输出结尾加逗号(,), 则表示不输出换行符,如果不加逗号(,) ,则默认有换行符;
print_stmt ::= "print" ([expression ("," expression)* [","]] | ">>" expression [("," expression)+ [","]])
3、print 如果改变输出对象可以使用如下语法
print >>file [("," expression)+ [","]])
其中[]里面的内容如果有东西,必须加, 在输出表达式。 例如print >>fp,123,123。
例如:
- open 函数是打开文件的函数,也是IO的一种,第一个参数是文件名称,第二个参数是打开的模式,可以是’w’、‘rw’、'r’等模式,具体的我们还会在IO篇章深入讲解;
- fp 是文件指针,是open函数返回出来的文件指针,通过这个指针,我们可以进行文件读取和写入;
- fp 是操作系统IO设备,所以如果不在使用 ,需要关闭资源,避免内存泄漏;
4.3、标准错误
所谓标准错误就是程序的错误输出;
五、流程控制
2、if statement(If 条件分支)
1、 if
在我们的需求之中,我们往往会并不是简单的顺序结构。
条件分支则是通过判断表达式执行结果(True/False)来决定执行哪个分支下的代码块。
使用if语句可以实现单分支结构,if语句的语法形式如下:
if_stmt ::= "if" expression ":" suite
( "elif" expression ":" suite )*
["else" ":" suite]
注:
*表示前一项零次或多次;+表示前一项一次或多次;[]表示零次或一次,换句话说,就是可选的;
上述是BNF规范的写法。如果觉得难以理解的话,可以看下面这个(其中,()表示零个或多个,…表示有多个,[]表示可选0个或一个):
if 条件表达式一 :
分支一
(elif 条件表达式二 :
分支二
...)
[else:
分支三]
案例:输入两个数a,b,判断a是否大于b
# -*- coding:UTF-8 -*-
# Author: XiaoJia
a = float(input())
b = float(input())
if a > b:
print("a > b")
2、if…else…
大多数情况下并不是只有一条分支路径供你选择,例如,我们要判断一个整数是奇数还是偶数。
num = int(input("please input one integer number: "))
if num % 2 == 0 :
print(num, " is a even number ")
else:
print(num, " is a odd number")
3、if…elif…elif…else
多条分支的情况,也是很常见的,例如我们输入一个学生的成绩,判断该成绩是优秀、中等、合格、还是不合格。
score = float(input("please input your score : "))
if score >= 90:
print("perfect")
elif score >= 70:
print("good")
elif score >= 60:
print("qualified")
else:
print("unqualified")
3、for statement(for loop)
1、range()与xrange()
1、range()
range(stop) -> range object
range(start, stop[, step]) -> range object
- 参数一:start,表示范围的开始
- 参数二:stop,表示范围的结束
- 参数三:step,表示步长
注:
在Python3.x之中,这个range()的返回值是一个range object,而Python2.x之中返回的list of integers(列表)
2、xrange()
xrange(stop) -> xrange object
xrange(start, stop[, step]) -> xrange object
该方法是Python2.x系列有的,在Python3.x系列是没有的,同时该对象也米有start,stop,step属性
2、for…in…
for循环是Python这种最简单的循环,其语法形式如下
for_stmt ::= "for" target_list "in" expression_list ":" suite
["else" ":" suite]
case 1 : please calculate sum from 1 to 100
mysum = 0
for i in range(1,101):
mysum = mysum + i
print("sum is ", mysum)
3、for…else
mysum = 0
for i in range(1,101):
mysum = mysum + i
else:
print("else")
print("sum is ", mysum)
else的触发条件是循环正常终止(break、return引起的循环结束都不会触发)
Note: There is a subtlety when the sequence is being modified by the loop (this can only occur for mutable sequences, i.e. lists). An internal counter is used to keep track of which item is used next, and this is incremented on each iteration. When this counter has reached the length of the sequence the loop terminates. This means that if the suite deletes the current (or a previous) item from the sequence, the next item will be skipped (since it gets the index of the current item which has already been treated). Likewise, if the suite inserts an item in the sequence before the current item, the current item will be treated again the next time through the loop. This can lead to nasty bugs that can be avoided by making a temporary copy using a slice of the whole sequence, e.g.,
注(这个部分,将在讲列表的时候讲解):
4、while statement(while loop)
1、while
case 1 please calculate sum from 1 to 100
total = 0
i = 0
while i<=100:
total = total + i
i = i + 1
print("the sum is ", total)
2、while…else
total = 0
i = 0
while i<=100:
total = total + i
i = i + 1
else :
print("else")
print("the sum is ", total)
else的触发条件是循环正常终止(break、return引起的循环结束都不会触发)
5、死循环
当你循环的条件恒为真的时候,就会出现这样循环条件无法终止的情况。例如while True : suite
6、pass statement
pass_stmt ::= "pass"
其实就是一个空语句,什么都不执行,在C语言或者c++或Java这种空语句是;。
if True:
pass
while True:
pass
for x in xrange(1,10):
pass
def function():
pass
class Person:
pass
7、break and continue statement
1、break
break_stmt ::= "break"
break语句只作用在与for或while循环之中,而不是嵌套没有该循环的函数或类之中。
它会终止最近当前所在的循环,如果循环有else,则会跳过该else。
如果for循环被终止,则循环控制目标保持当前值
如果循环里面有try…exception…else…finally…时候,遇到break之后,会先执行finally语句的内容再退出循环(这一点,我们将在错误处理的时候讲解)
2、continue
continue_stmt ::= "continue"
同样continue只发生在for和while循环之中,而不是嵌套在没有这些循环内的函数、类定义和finally之中。它会继续当前循环的下一轮。
如果循环里面有try…exception…else…finally…时候,遇到break之后,会先执行finally语句的内容再进行下一轮循环(这一点,我们将在错误处理的时候讲解)
实例代码:
for i in range(1,10):
print("当前是第",i,"次循环")
else:
print('我是else输出的结果')
print("----------分割线------------")
for i in range(1,10):
if i == 5:
break
print("当前是第",i,"次循环")
else:
print('我是else输出的结果')
print("----------分割线------------")
for i in range(1,10):
if i == 5:
continue
print("当前是第",i,"次循环")
else:
print('我是else输出的结果')
本文档介绍了Python编程的基础知识,包括环境搭建、HelloWorld程序、数据类型、数学运算、浮点数误差处理、类型转换、布尔类型及逻辑操作等内容。

4986

被折叠的 条评论
为什么被折叠?



