简明Python基础(三)
此为jupyter notebook导出文档,如果习惯jupyter界面可以下载文件 链接:https://pan.xunlei.com/s/VMn5shjbvhvIPMqdURC6TZHXA1 提取码:pafn 复制这段内容后打开手机迅雷App,查看更方便
Python的行
python中没有强制的语句中止符
多行语句
Python语句中一般以新行(换行)作为语句的结束符
thisIsaVeryLongVariableNameSoCantWriteInOneLineVariable1 = 1
thisIsaVeryLongVariableNameSoCantWriteInOneLineVariable2 = 2
thisIsaVeryLongVariableNameSoCantWriteInOneLineVariable3 = 3
plusResult = thisIsaVeryLongVariableNameSoCantWriteInOneLineVariable1 + thisIsaVeryLongVariableNameSoCantWriteInOneLineVariable2 +thisIsaVeryLongVariableNameSoCantWriteInOneLineVariable3
print(plusResult)
6
plusResult = thisIsaVeryLongVariableNameSoCantWriteInOneLineVariable1 +
thisIsaVeryLongVariableNameSoCantWriteInOneLineVariable2 +
thisIsaVeryLongVariableNameSoCantWriteInOneLineVariable3
print(plusResult)
File "<ipython-input-2-4ab6c4dc1efc>", line 2
plusResult = thisIsaVeryLongVariableNameSoCantWriteInOneLineVariable1 +
^
SyntaxError: invalid syntax
plusResult = thisIsaVeryLongVariableNameSoCantWriteInOneLineVariable1 +\
thisIsaVeryLongVariableNameSoCantWriteInOneLineVariable2 +\
thisIsaVeryLongVariableNameSoCantWriteInOneLineVariable3
print(plusResult)
6
语句中包含[],{}或者()这些括号中间换行的就不需要使用多行连接符
days = ('Mon','Tue','Wed',
'Thu','Fri','Sat','Sun')
print(days)
('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
控制语句
条件语句 if
- 代码块是通过缩进来指示的
- 缩进表示一个代码块的开始,逆缩进则表示一个代码块的结束
- 声明以冒号:字符结束,并且开启一个缩进级别
在if 和 else elif 的条件后面别忘记冒号
print("请输入体重(kg):")
weight = float(input())
if weight > 90 :
print("该减肥啦!!!")
if else 语句
C++ java 的else if语句 在Python改为了 elif
print("请输入体重(kg):")
weight = float(input())
if weight > 90 :
print("该减肥啦!!!")
else :
print("身材保持的不错!!!")
print("请输入体重(kg):")
weight = float(input())
if weight > 90 :
print("该减肥啦!!!")
elif 60<weight <= 90 :
print("身材保持的不错!!!")
else :
print("太瘦啦")
while循环语句
循环语句允许执行一条语句或语句块执行多次
num = 2 ** 100
print(num)
count = 0
while num > 0 :
if num % 10 == 6:
count = count + 1
num = num //10
print(count)
1267650600228229401496703205376
5
for 循环语句
for 循环变量 in 序列 :
num = 2 ** 100
print(num)
count = 0
for digit in str(num):
if digit == "6" :
count = count + 1
print(count)
1267650600228229401496703205376
5
使用for和range来枚举列表中的元素
for i in range(5):
print(i)
0
1
2
3
4
for x in range(1,5):
print(x)
1
2
3
4
列表推导式
列表推导式(List Comprehension)提供了一个创建和操作列表的有力工具
列表推导式由一个表达式以及紧跟着这个表达式的for语句构成,for语句还可以跟0个或多个if或for语句
list1 = [1,2,3]
list2 = [4,5,6]
[x * y for x in list1 for y in list2]
[4, 5, 6, 8, 10, 12, 12, 15, 18]
数值判断可以链接使用,例如1<x<3能够判断变量x是否在1和3之间
[x for x in list1 if 4>x>1]
[2, 3]
多重循环
for i in range(1,10):
for j in range(1,i+1):
result = j * i
print('%s x %s = %-5s ' % (j,i,result) , end=' ')
print()
1 x 1 = 1
1 x 2 = 2 2 x 2 = 4
1 x 3 = 3 2 x 3 = 6 3 x 3 = 9
1 x 4 = 4 2 x 4 = 8 3 x 4 = 12 4 x 4 = 16
1 x 5 = 5 2 x 5 = 10 3 x 5 = 15 4 x 5 = 20 5 x 5 = 25
1 x 6 = 6 2 x 6 = 12 3 x 6 = 18 4 x 6 = 24 5 x 6 = 30 6 x 6 = 36
1 x 7 = 7 2 x 7 = 14 3 x 7 = 21 4 x 7 = 28 5 x 7 = 35 6 x 7 = 42 7 x 7 = 49
1 x 8 = 8 2 x 8 = 16 3 x 8 = 24 4 x 8 = 32 5 x 8 = 40 6 x 8 = 48 7 x 8 = 56 8 x 8 = 64
1 x 9 = 9 2 x 9 = 18 3 x 9 = 27 4 x 9 = 36 5 x 9 = 45 6 x 9 = 54 7 x 9 = 63 8 x 9 = 72 9 x 9 = 81
break语句
break语句用在while和for循环中
break语句用来终止循环语句,即循环条件没有False或者序列还没被完全递归完,也会停止执行循环语句
num = 2**100
pos = 0
for digit in str(num) :
pos = pos + 1
if digit == "6":
break
print("2**100 is: %d \nthe first position of 6 is Pos.%d" % (num, pos))
2**100 is: 1267650600228229401496703205376
the first position of 6 is Pos.3
如果在嵌套循环中,break语句将停止执行本层的循环
i = 2
while(i<=10):
flag = 0
j = 2
while(j <= (i/j)):
if i%j == 0 :
flag = 1
break
j = j + 1
if flag == 0 :
print(i,"是素数")
i = i + 1
2 是素数
3 是素数
5 是素数
7 是素数
continue语句
continue语句用来跳过当前循环的剩余语句,然后继续进行下一轮循环
num = 2**100
without6 = ''
for digit in str(num):
if digit == '6':
continue
without6 += digit
print("2**100 is: %d \nwithout 6 is: %s" % (num, without6))
2**100 is: 1267650600228229401496703205376
without 6 is: 12750002282294014970320537
pass语句
pass语句是空语句,是为了保持程序结构的完整性,一般用做占位语句
num = 2**100
without6 = ''
for digit in str(num):
if digit == '6':
pass
else:
without6 += digit
print("2**100 is: %d \nwithout 6 is: %s" % (num, without6))
2**100 is: 1267650600228229401496703205376
without 6 is: 12750002282294014970320537
程序结构
函数
def functionname(parameters):
?? “函数_文档字符串”
?? function_suite
??return [expression]
def fact(n):
result = 1
for i in range(1,n+1):
result = result * i
return result
- 可选参数以集合的方式出现在函数声明中并紧跟着必选参数,可选参数可以在函数声明中被赋予一个默认值。已命名的参数需要赋值。
- 函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明
- 函数可以返回一个元组(使用元组拆包可以有效返回多个值)
def fun_example(listp, intp=0, stringp="A default string"):
"这是一个略微复杂函数的例子,有关函数的说明文档可以写在这里"
listp.append( "A new item" )
intp += 1
return listp, intp, stringp
my_list = [1,2,3]
my_int = 10
v1,v2,v3= fun_example(my_list,my_int)
print(v1)
print(fun_example(my_list,my_int))
print(my_list)
[1, 2, 3, 'A new item']
([1, 2, 3, 'A new item', 'A new item'], 11, 'A default string')
[1, 2, 3, 'A new item', 'A new item']
fun_example.__doc__
全局变量与局部变量
- 全局变量在函数之外声明局部变量在函数内容声明
- 函数参数也是局部变量,不需要在函数内部重复定义!!!
- 全局变量可以不需要任何特殊的声明即能读取,但如果想要修改全局变量的值,就必须在函数开始之处用global关键字进行声明,否则Python会将此变量按照新的局部变量处理(请注意,这点很容易被坑)
number = 5
def func1():
print(number)
func1()
print(number)
5
5
number = 5
def func2():
number = 3
print(number)
func2()
print(number)
3
5
number = 5
def func2():
global number
number = 3
print(number)
func2()
print(number)
3
3
类
- 类(Class)用来描述具有相同的属性和方法的对象的集合
- 它定义了该集合中每个对象所共有的属性和方法
- 对象是类的实例
class ClassName:
?? ‘类的帮助信息’ #类文档自负串
?? class_suite #类体
class_suite由类成员,方法,数据属性组成
class DeepLearner(object):
'DeepLearner是深度学习者的类,这是有关这个类的帮助文档'
learnerCount = 0
def __init__(self, name,schoolName) :
self.name = name
self.schoo1Name = schoolName
DeepLearner.learnerCount = DeepLearner.learnerCount + 1
def getName( self):
return self.name
def getSchoo1Name( self):
return self.schoolName
def displayCount(self):
print("Total DeepLearner count is %d" % DeepLearner.learnerCount)
def displayLearner(self):
print("Name: %s, School: %s" % (self.name,self.schoolName))
print(DeepLearner.__doc__)
DeepLearner是深度学习者的类,这是有关这个类的帮助文档
newLearner1 = DeepLearner('giggle','Zhejiang University')
newLearner2 = DeepLearner('sherry','Zhejiang University of Technology')
print(newLearner1.learnerCount)
newLearner1.displayCount()
2
Total DeepLearner count is 2
文件
Python针对文件的处理有很多内建的函数库可以调用
with open( "test.txt", "wt" ) as out_file:
out_file.write("该文本会写入到文件中\n看到我了吧")
with open( "test.txt", "rt" ) as in_file:
text = in_file.read()
print(text)
异常
Python中的异常由try-except [exceptionname]块处理
def except_function():
try :
10 / 0
except ZeroDivisionError:
print("发生除零异常啦.")
else:
print ("一切正常啦.")
pass
finally:
print ( "final1y必须被执行,不管有没有发生异常.")
except_function()
发生除零异常啦.
final1y必须被执行,不管有没有发生异常.
如果不知道发生什么异常,可以 except: 表示抓取所有异常
导入外部库
外部库可以使用import [libname]关键字来导入
可以用from [libname] import [funcname]来导入所需要的函数
import random
from time import time
import numpy as np
import matplotlib.pyplot as plt
randomint = random.randint(1,100)
print(randomint)
startTime=time()
print(startTime)
x_data = np.linspace(-1,1,100)
y_data = 2* x_data + 1.0
%matplotlib inline
plt.figure()
plt.scatter(x_data,y_data)
duration = time()-startTime
print(duration)
获取帮助信息
如果想知道一个对象(object)是如何工作的,可以调用help(对象)!另外还有一些有用的方法,
dir()会显示该对象的所有方法,还有会显示其文档:
dir(1)
help(int)
a = 12345
a.__neg__()
打.后加tab键获取自动填充放方法选择
|