python学习笔记

1、标志符:必须以字母或下划线开头,后跟字母、数字或下划线 

不能含空格,不能使用内置关键字,且区分大小写

2、将字符放在单引号中输出,来区别文本还是数字

〉〉〉“32”
‘32’

3、只有圆括号在数字表达式中是允许的,嵌套使用

((x1-x2)/2*n)+(spam/k**3)

4、变量必须要赋值才能在表达式中使用

5、输出语句print中的表达式从左往右求值并显示

〉〉〉print(3,4,3+4)
3 4 7

print()生成空行输出,print默认通过换行结束文本,可通过end关键字来改变

print("The answer is",end=" ")
print(3+4)

The answer is 7

6、对变量赋新值,旧值不会被新值覆盖,变量只需切换到引用新值,旧值一段时间后不用,会被自动清理掉

7、使用input,用户输入的任何东西会被存为字符串

>>> name=input("Please Enter :")
Please Enter :89
>>> name
'89'

如果想要转化为数字,使用eval:

>>> name=eval(input("Please Enter :"))
Please Enter :89
>>> name
89

通过eval还可以对表达式求值:

>>> ans=eval(input("Enter an expression:"))
Enter an expression:3+7*1
>>> ans
10

8、通过同时赋值来交换xy值,因为是同时的,所以避免了擦去原始值

>>> x,y=eval(input("Please enter your number:"))
Please enter your number:3,4 #用逗号分隔输入的数字
>>> x,y=y,x
>>> print(x,y)
4 3

多个值技巧不适合字符串(非求值)输入,因为逗号不能起到分隔符作用

如果不通过eval获取多个输入,可以通过split将其转为列表 

>>> coords=input("please enter:").split(",")
please enter:3.4,6.25
>>> x,y=float(coords[0]),float(coords[1])
>>> x
3.4
>>> f,l="he ll".split()
>>> f
'he'

9、 for <var> in <sequence>:

                <body> 

sequence通常由列表组成,var依次取sequence中的每个值,sequence的项数决定循环次数

10、range()

>>> list(range(10)) #range(n)产生0~n-1的连续值构成的序列,左闭右开
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(2,4)) #range(start,n),从start开始到n,但不包括n
[2, 3]
>>> list(range(5,10,3)) #range(start,n,step),从start开始到n,不包括n,步长为step
[5, 8]

11、type()显示数据类型

>>> type(1.0)
<class 'float'>
>>> type(1)
<class 'int'>

12、//整数除,/常规除法

>>> 10/3
3.3333333333333335 #返回近似值
>>> 8/4
2.0
>>> 8//4
2
>>> 8.0//4.0 #结果的数据类型取决于操作数的数据类型
2.0
>>> 8.0//4
2.0
>>> 10.0%2
0.0
>>> 10%2
0

13、类型转换

>>> float(int(9.4))
9.0
>>> int(float(9))
9
>>> round(4.5) #浮点数精度问题:可能4.5实际存储的值是4.500000000000000001
4
>>> round(3.5) #round起到四舍五入的作用
4
>>> round(4.123,2) #四舍五入到规定位数
4.12
>>> int("2.6")
Traceback (most recent call last):
  File "<pyshell#41>", line 1, in <module>
    int("2.6")
ValueError: invalid literal for int() with base 10: '2.6'
>>> int("2") #也可用于将数字字符串转为数字
2

14、用int、float代替eval,增加安全性

>>> x=int(input("Please enter your number:"))
Please enter your number:12
>>> x
12

但不能用于同时赋值 

>>> x,y=int(input("Please enter your numbers:"))
Please enter your numbers:12,1
Traceback (most recent call last):
  File "<pyshell#46>", line 1, in <module>
    x,y=int(input("Please enter your numbers:"))
ValueError: invalid literal for int() with base 10: '12,1'

15、math库的使用

>>> import math
>>> math.sqrt(4)
2.0

16 、python的int数据类型可以存储任意大小的整数,如果int值对于底层硬件int太大,就会自动转换为更长的表示,涉及这些长的int计算比只使用短int的低,而Java与C++中的int值超过限定位数会发生溢出导致错误的数值

17、字符串可由单引号或双引号分隔,没有区别,但一定要配对

>>> str1="hello"
>>> str2='spam'
>>> print(str1,str2)
hello spam

18、基本字符串操作

>>> greet="hello bob"
>>> greet[0] #按索引取值
'h'
>>> greet[-1] #负索引:从字符串右端索引
'b'
>>> greet[1:3] #切片,左闭右开
'el'
>>> greet[:5]
'hello'
>>> greet[5:]
' bob'
>>> greet[:]
'hello bob'
>>> "spam"+"eggs" #连接
'spameggs'
>>> 3*"spam"+"eggs" #重复
'spamspamspameggs'
>>> len(greet) #求长度
9
>>> for i in "spam": #循环遍历
	print(i,end=" ")

s p a m 

19、更多字符串方法

>>> mystring="hello hi"  #将字符串切分为字串列表
>>> mystring.split()
['hello', 'hi']
>>> "32,33,34".split(",")
['32', '33', '34']
>>> s="hello,I came here for an argument"
>>> s.capitalize() #只有第一个字符大写,其余全部小写
'Hello,i came here for an argument'
>>> s.title() #每个单词第一个字符大写
'Hello,I Came Here For An Argument'
>>> s.upper() #所有字符转为大写
'HELLO,I CAME HERE FOR AN ARGUMENT'
>>> s.lower() #所有字符转为小写
'hello,i came here for an argument'
>>> s.replace('I','you') #字符替换
'hello,you came here for an argument'
>>> s.count('e') #计算出现次数
5
>>> s.find(",") #出现的第一个位置下标
5
>>> " ".join(["Number","one","the","larch"]) #将列表连接到字符串中,使用“ ”作为分隔符
'Number one the larch'
>>> "spam".join(["Number","one","the","larch"])
'Numberspamonespamthespamlarch'
>>> 

20、print+\n输出跳过一个额外的行

>>> print("hello\n")
hello

>>> 

21、列表作为序列的基本操作(同字符串)

>>> temp=[1,2,3,4]
>>> temp[0]
1
>>> temp[2:4]
[3, 4]
>>> [1,2]+[3,4]
[1, 2, 3, 4]
>>> [1,2]*3
[1, 2, 1, 2, 1, 2]
>>> len(temp)
4

字符串总是字符序列,而列表可以是任意对象的序列

>>> mylist=[1,"spam",4,"u"]

字符串不可变,但列表可变

>>> mylist=[1,"spam",4,"u"]
>>> mylist[0]=3
>>> mylist
[3, 'spam', 4, 'u']
>>> mystring="hello"
>>> mystring[0]='q'
Traceback (most recent call last):
  File "<pyshell#43>", line 1, in <module>
    mystring[0]='q'
TypeError: 'str' object does not support item assignment

22、更多列表的方法

>>> instring=input("please enter:")
please enter:87 104 97 116 32 97 32 83 111 117 114 112 117 115 115 33
>>> chars=[]
>>> for i in instring.split():
	chars.append(chr(int(i))) #在列表末尾添加一项

	
>>> mess="".join(chars)
>>> print(mess)
What a Sourpuss!

23、ASCII编码-字符串转换

>>> ord("a")
97
>>> chr(97)
'a'

24、字符串格式化

  •  {}标记出插槽,数字对应format中值的索引,{<索引>:<宽度>.<精度><类型>}
  • 索引指示format哪个参数被插入插槽中,
  • 冒号后描述指定值插入插槽的外观
  • 宽度表示应占多少空间,值小于指定宽度默认用空格填充,大于的话则占据该值所需空间,0表示使用所需空间
  • 对于正常非定点浮点数,精度表示要打印的有效数字个数,定点数(f),精度表示小数位数
>>> "Hello {0}{1},you may have won {2}".format("Mr.","Smith",10000)
'Hello Mr.Smith,you may have won 10000' 

>>> "This int,{0:5},was placed in a field of width 5".format(7) 
'This int,    7,was placed in a field of width 5'

>>> "This float,{0:10.5},has width 10 and precision 5".format(3.1415926)
'This float,    3.1416,has width 10 and precision 5'


>>> "This float,{0:10.5f},is fixed at 5 decimal places".format(3.1415926)
'This float,   3.14159,is fixed at 5 decimal places'

>>> "This float,{0:0.5},has width 0 and precision 5".format(3.1415926)
'This float,3.1416,has width 0 and precision 5'

>>> "Compare {0} and {0:0.20}".format(3.14)
'Compare 3.14 and 3.1400000000000001243'

默认情况数值右对齐,可更改为左中右对齐

>>> "left justification:{0:<5}".format("Hi!") #左对齐
'left justification:Hi!  '
>>> "right justification:{0:>5}".format("Hi!") #右对齐
'right justification:  Hi!'
>>> "centered:{0:^5}".format("Hi!") #居中对齐
'centered: Hi! '

0>2表示如果小于指定宽度2,用0来填充,而不是空格,1>2表示用1填充 

>>> print("The total value of your change is {0}.{1:0>2}".format(2,5))
The total value of your change is 2.05

>>> print("The total value of your change is {0}.{1:0<2}".format(2,5))
The total value of your change is 2.50

>>> print("The total value of your change is {0}.{1:1>2}".format(2,5))
The total value of your change is 2.15

25、只有当打印字符时,特殊字符才会影响字符串的显示方式

>>> "hello\nhi\n"
'hello\nhi\n'
>>> print("hello\nhi\n")
hello
hi

>>> 

26、文件的处理

 >>> infile=open("graphics_practice.py","r")
>>> data=infile.read()
>>> print(data)
import graphics
win=graphics.GraphWin()

>>> print(infile.readline())

>>> print(infile.readlines())
[]

#read之后会把read的这一段内容从infile的缓存里清除,所以每次read前都要重新open一次

>>> infile=open("graphics_practice.py","r")
>>> print(infile.readline()) #readline返回的字符串总是以换行符结束
import graphics

>>> print(infile.readline()) #对readline连续调用可以从文件中获得连续的行
win=graphics.GraphWin()

>>> infile=open("graphics_practice.py","r")
>>> print(infile.readlines())
['import graphics\n', 'win=graphics.GraphWin()\n']

消除print自带的换行符:

>>> infile=open("graphics_practice.py","r") #循环输出文本前5行
>>> for i in range(5):
	print(infile.readline())

	
import graphics

win=graphics.GraphWin()




>>> infile=open("graphics_practice.py","r") #方法一:利用end消除换行符
>>> for i in range(5):
	print(infile.readline(),end="")

	
import graphics
win=graphics.GraphWin()
>>> infile=open("graphics_practice.py","r") #方法二:利用切片消除换行符
>>> for i in range(5):
	line=infile.readline()
	print(line[:-1])

	
import graphics
win=graphics.GraphWin()

循环遍历文件全部内容:

#使用readlines读取所有文件,然后循环遍历结果列表
#缺点是文件可能非常大,一次读入列表占很大的内存
>>> infile=open("graphics_practice.py","r") 
>>> for line in infile.readlines():
	print(line,end="")

	
import graphics
win=graphics.GraphWin()
>>> infile.close()
#解决方法:python将文件本身视为一系列的行
>>> infile=open("graphics_practice.py","r")
>>> for line in infile:
	print(line,end="")

	
import graphics
win=graphics.GraphWin()
>>> infile.close()

26、简单的图形编程

>>> import graphics #导入图形库
>>> win=graphics.GraphWin() #GraphWin是一个对象,将其赋给变量win
>>> win.close() #通过变量win来操作对象

#另一种导入方式
>>> from graphics import *
>>> win=GraphWin()

 绘制两个点的图形窗口:

>>> win=GraphWin()
>>> p=Point(50,60) #构造函数的一般形式:<class-name>(<param1>,<param2>,...)
>>> p.draw(win)
Point(50.0, 60.0)
>>> p2=Point(140,100) #使用构造函数生成的对象赋给左侧的变量
>>> p2.draw(win) #对象的方法
Point(140.0, 100.0)

>>> p.getX()
50.0
>>> p.getY()
60.0

 绘制红色的圆:

>>> win=GraphWin('shapes')
>>> center=Point(100,100)
>>> circ=Circle(center,30)
>>> circ.setFill('red')
>>> circ.draw(win)
Circle(Point(100.0, 100.0), 30)

 

输入文本: 

>>> win=GraphWin()
>>> center=Point(100,100)
>>> label=Text(center,"Red Circle")
>>> label.draw(win)
Text(Point(100.0, 100.0), 'Red Circle')

 几何形状:

>>> win=GraphWin()
>>> rect=Rectangle(Point(30,30),Point(70,70))
>>> rect.draw(win)
Rectangle(Point(30.0, 30.0), Point(70.0, 70.0))
>>> line=Line(Point(20,30),Point(180,165))
>>> line.draw(win)
Line(Point(20.0, 30.0), Point(180.0, 165.0))
>>> oval=Oval(Point(20,120),Point(180,199))
>>> oval.draw(win)
Oval(Point(20.0, 120.0), Point(180.0, 199.0))

>>> win=GraphWin()
>>> p=Point(50,60)
>>> p.draw(win)
Point(50.0, 60.0)
>>> p.move(10,0) #move(dx,dy)让对象在x方向移动dx单位,在y方向移动dy单位,move负责擦除旧图像并在新位置绘制

两个不同的变量指的对象可能完全相同,通过一个变量对对象所做的更改也会对另一个变量可见

>>> lefteye=Circle(Point(80,50),5)
>>> lefteye.setFill('yellow')
>>> lefteye.setOutline('red')
>>> righteye=lefteye
>>> righteye.move(20,0)
>>> win=GraphWin()
>>> lefteye.draw(win)
Circle(Point(100.0, 50.0), 5)
>>> righteye.draw(win)
Traceback (most recent call last):
  File "<pyshell#212>", line 1, in <module>
    righteye.draw(win)
  File "/Users/dailijundediannao/Documents/graphics.py", line 481, in draw
    if self.canvas and not self.canvas.isClosed(): raise GraphicsError(OBJ_ALREADY_DRAWN)
graphics.GraphicsError: Object currently drawn

解决方法可以是为每只眼睛创建一个单独的圆,但过程繁琐,graphics库提供了clone方法

>>> win=GraphWin()
>>> lefteye=Circle(Point(80,50),5)
>>> lefteye.setFill('yellow')
>>> lefteye.setOutline('red')
>>> righteye=lefteye.clone()
>>> righteye.move(20,0)
>>> lefteye.draw(win)
Circle(Point(80.0, 50.0), 5)
>>> righteye.draw(win)
Circle(Point(100.0, 50.0), 5)

27、函数要看到另一个函数中的变量,唯一的方法是将该变量作为参数传入

def drawBar(window, year,height):
...

def main():
    win=GraphWin()
    ...
    drawBar(win,0,principal)

由于win是在main内部创建的,因此不能在drawBar中直接访问

28、函数返回值

>>> def square(x):
	return x**2

>>> square(3)
9

29、示例

>>> def happy():
	return "Happy Birthday to you!\n"

>>> def verseFor(person):
	lyrics=happy()*2+"Happy birthday, dear"+person+".\n"+happy()
	return lyrics

>>> def main():
	for person in ["Fred","Lucy","Elmer"]:
		print(verseFor(person))

		
>>> main()
Happy Birthday to you!
Happy Birthday to you!
Happy birthday, dearFred.
Happy Birthday to you!

Happy Birthday to you!
Happy Birthday to you!
Happy birthday, dearLucy.
Happy Birthday to you!

Happy Birthday to you!
Happy Birthday to you!
Happy birthday, dearElmer.
Happy Birthday to you!

将结果写入文件:

>>> def main():
	outf=open("Happy_Birthday.txt","w")
	for person in ["fred","lucy","elmer"]:
		print(verseFor(person),file=outf)
	outf.close()

多个返回值

>>> def sumdiff(x,y):
	sum=x+y
	diff=x-y
	return sum,diff

>>> num1,num2=input("Please enter two numbers(num1,num2) ").split(",")
Please enter two numbers(num1,num2) 12,13
>>> s,d=sumdiff(float(num1),float(num2))
>>> print("the sum is",s,"and the difference is",d)
the sum is 25.0 and the difference is -1.0

注:python所有函数都返回一个值,没有return语句的函数总是返回None

30、python按值传递参数(python不允许按引用传递参数),如果传递的值是可变对象,则对象所做的更改会对调用者可见

>>> def addInterest(balances,rate):
	for i in range(len(balances)):
		balances[i]=balances[i]*(1+rate)

		
>>> def test():
	amounts=[1000,2200,800,360]
	rate=0.05
	addInterest(amounts,rate)
	print(amounts)

	
>>> test()
[1050.0, 2310.0, 840.0, 378.0]

31、判断结构:

单路判断:

if  <condition>:

        <body>

两路判断:

if  <condition>:

        <body>

else:

        <body>

多路判断:

if <condition1>:

        <body1>

elif<condition2>:

        <body2>

else:

        <default body3>  

多路判断中else子句可选

32、比较字符串是按字典序,所有大写字母都在小写字母前面(如“Bbbb”在“aaaa”之前)

python的布尔表达式类型为bool,布尔值true和false由字面量True和False表示

>>> 3<4
True
>>> "Hello">"hello"
False

 33、如果模块被导入,那__name__变量的值是模块的名称,如果直接运行,值是__main__

 

 通过if __name__=='__main__'保证在直接调用程序时自动运行main,导入模块时不运行

34、异常处理

try:

        <body>

except  <ErrorType>:

        <handler>

报错的最后一行说明了错误类型 

>>> import math
>>> def main():
	try:
		a=float(input("enter:"))
		b=float(input("enter:"))
		c=float(input("enter:"))
		dis=math.sqrt(b*b-4*a*c)
		r1=(-b+dis)/(2*a)
		r2=(-b-dis)/(2*a)
		print("\nThe solution are:",r1,r2)
	except ValueError:
		print("\nNo real roots")

		
>>> main()
enter:1
enter:2
enter:3

No real roots
>>> main()
enter:x

No real roots

异常实际是一种对象,在错误类型后跟上as <variable>,python会将该变量赋值为实际的异常对象,转换为一个字符串,可用于检查该信息,看看是什么导致了ValueError

>>> import math
>>> def main():
	try:
		a=float(input("enter:"))
		b=float(input("enter:"))
		c=float(input("enter:"))
		dis=math.sqrt(b*b-4*a*c)
		r1=(-b+dis)/(2*a)
		r2=(-b-dis)/(2*a)
		print("\nThe solution are:",r1,r2)
	except ValueError as excobj:
		if str(excobj)=="math domain error":
			print("No Real Roots")
		else:
			print("Invalid coefficient given")
	except:
		print("\nsomething went wrong,sorry!")

		
>>> main()
enter:1
enter:2
enter:3
No Real Roots

33、python支持复合条件

if x1>=x2>=x3:
    maxval=x1

但5>=2>=4的情况下条件返回false,应改为

if x1>=x2 and x1>=x3:
    maxval=x1

34、python函数传参是否改变原值

>>> a=5
>>> def func(a):
	a=8

	
>>> func(a) #a是不可变变量,在函数中改变不会影响原值
>>> a
5
>>> b=[1,2]
>>> def func(c):
	c[0]=10

	
>>> func(b) #列表是可变变量,调用函数后原值会改变
>>> b
[10, 2]

35、每个对象认为是类的一个实例,Circle是类的名称,用于调用构造方法

myCircle=Circle(Point(0,0),20)

类形式的定义:

class <class-name>:
    <method-definition>

实例:寻找gpa最高的学生

class Student:
    def __init__(self,name,hours,qpoints):
        self.name=name
        self.hours=float(hours)
        self.qpoints=float(qpoints)
    def getName(self):
        return self.name
    def getHours(self):
        return self.hours
    def getQpoints(self):
        return self.qpoints
    def gpa(self):
        return self.qpoints/self.hours
def makeStudent(infoStr):
    name,hours,qpoints=infoStr.split("\t")
    return Student(name,hours,qpoints)
def main():
    filename=input("Please enter the name of the grade file:")
    infile=open(filename,'r')
    best=makeStudent(infile.readline())
    for line in infile:
        s=makeStudent(line)
        if s.gpa()>best.gpa():
            best=s
    infile.close()
    print("The best student is",best.getName())
    print("hours:",best.getHours())
    print("Gpa:",best.gpa())
if __name__=='__main__':
    main()

类的每个方法第一个参数都是self,它包含了该方法所在对象的引用,在方法调用时,第一个形参对应该对象,如

die1=MSDie(18)
die1.setValue(8)

中 die1.setValue(8)相当于self=die1,value=8

__init__的作用是为对象的实例变量提供初始值,实例变量不同于常规的局部函数变量(一旦函数终止,其值将消失)它用于记住特定对象的状态(相当于全局变量)

>>>die1=Die(13)
>>>print(die1.getValue())
1
>>>die1.setValue(8)
>>>print(die1.getvalue())
8

不要在类之外直接访问实例变量,因为实例变量是私有变量

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值