Python 例子
本文所使用的 Python 解释器 为 Python 3.7.9 该文为学习 Python时 积攒的 入门小例子
流程控制
-
打印9*9乘法表 i = 1
while i <= 9:
j = 1
while j <= i:
print(i,'*',j,'=',i*j,end = " ")
print()
''' Output is listed as following'''
1 * 1 = 1
1 * 2 = 2 2 * 2 = 4
1 * 3 = 3 2 * 3 = 6 3 * 3 = 9
1 * 4 = 4 2 * 4 = 8 3 * 4 = 12 4 * 4 = 16
1 * 5 = 5 2 * 5 = 10 3 * 5 = 15 4 * 5 = 20 5 * 5 = 25
1 * 6 = 6 2 * 6 = 12 3 * 6 = 18 4 * 6 = 24 5 * 6 = 30 6 * 6 = 36
1 * 7 = 7 2 * 7 = 14 3 * 7 = 21 4 * 7 = 28 5 * 7 = 35 6 * 7 = 42 7 * 7 = 49 6 * 7 = 42
...
-
摄氏温度准换华氏温度 temper=input("Please input transformed temperture sign\n ")
if temper[-1] in ["F","f"]:
C=(eval(temper[0:-1])-32)/1.8
print("Transform temperture is {:2f}C".format(C))
elif temper[-1] in ["C","c"]:
F=(1.8*eval(temper[0:-1])+32)
print("Transform temperture is {:2f}F".format(F))
else:
print("Error Input Format")
-
拆包:将容器中的数据分别给多个变量/组包:将多个数据值赋值一个变量 e = 20
f = 10
e , f = f , e
print( e , f )
g = 100
h = g
print(id(h),id(g))
def func(* args ,**kwargs):
print(args)
print(kwargs)
func(1,2,3,4,5)
def my_sum(*args, **kwargs):
num = 0
for i in args :
num += i
for j in kwargs.values():
num += j
print(f"result is {num}")
my_sum(1,2,3,4,a = 6 , b = 7 , c = 8)
-
turtle import turtle
turtle.setup(650,350,200,200)
turtle.penup()
turtle.fd(-250)
turtle.pendown()
turtle.pensize(25)
turtle.pencolor("purple")
turtle.seth(-40)
for i in range(4):
turtle.circle(40,80)
turtle.circle(-40,80)
turtle.circle(40,80/2)
turtle.fd(40)
turtle.circle(16,180)
turtle.fd(40*2/3)
turtle.done()
递归
-
阶乘 ''' Recursion Finish'''
def factorial1(n):
if(n <= 1):
return n
else:
return n * factorial2(n - 1)
n = input('Please input the number\n')
result = factorial2(int(n))
print('factorial(%d) = %d'%(int(n),result))
''' Not Recursion finish'''
def factorial2(n):
result = n
for i in range(1,n):
result *= i
return result
number=int(input('Please input the number\n'))
print('factorial(%d) = %d'%(number,factorial2(number)))
-
斐波那契数列 ''' Not Recursion finish'''
def Fabornaki(n):
n1 = 1
n2 = 1
n3 = 1
if n < 1 :
print('Error input')
return -1
while ( n - 2 ) > 0:
n3 = n1 + n2
n1 = n2
n2 = n3
n -= 1
return n3
days = int(input('Please input days'))
result = Fabornaki(days)
if result != -1:
print('After %d days,add up to %d rabbits born in'%(days,result))
''' Recursion Finish'''
def fab(n):
if n<1:
print('Error')
return -1
if n==1 or n==2:
return 1
else : return fab(n-1)+fab(n-2)
days = int(input('Please input days'))
result = fab(days)
if result != -1:
print('After %d days,add up to %d rabbits born in'%(days,result))
-
汉诺塔 def hanoi(n,x,y,z):
if n==1:
print(x,'->',z)
else:
hanoi(n-1,x,z,y)
print(x,'->',z)
hanoi(n-1,y,x,z)
n=int(input('Please input floors hanoi:'))
hanoi(n,'X','Y','Z')
-
pickle import pickle
my_list=[123,3.14,'Xiaojiayu',['another list']]
pickle_file=open('my_list.pkl','wb')
pickle.dump(my_list,pickle_file)
pickle_file.close()//pickle -Pack usual data into my_list
异常
- 文件异常
"""BUGS
- TypeError 类型不兼容
- SyntaxError 参数错误
- IndexError 越界错误
- ZeroDivisionError 分母为0的错误
- KeyError 键错误
- NameError 命名错误
- ValueError 值错误
"""
try :
with open('data.txt','w') as f:
f.write('I\'m Pt')
except ValueError as reason:
print('Error'+str(reason))
else:
print('No Error')
finally:
f.close()
'''Second example '''
try :
f=open('pin1.txt')
print(f.read())
f.close()
except OSError as reason:
print('Error File\nReason is'+str(reason))
finally:
f.close()
```
- 密码长度的检测异常
class PasswordLengthError(Exception):
pass
def get_password():
password = input("Enter password")
if(len(password) >= 6):
print("密码长度合格")
else:
raise PasswordLengthError("密码长度不足六位")
if __name__ == "__main__":
try:
get_password()
except PasswordLengthError as psle:
print(psle)
魔法方法
-
init 和__str__魔法方法(烤地瓜实例) class Potato(object):
def __init__(self) :
self.status = "raw"
self.total_time = 0
def cook(self,time):
self.total_time += time
if self.total_time < 3:
self.status = 'raw'
elif self.total_time < 6:
self.status = 'mature also raw'
elif self.total_time < 8:
self.status = 'mature'
else:
self.status = 'too mature'
def __str__(self):
return f"地瓜的状态<<{self.status}>>,烧烤总时间<{self.total_time}>"
potato = Potato()
print(potato)
potato.cook(4)
print(potato)
potato.cook(3)
print(potato)
potato.cook(1)
print(potato)
"""
输出结果:
地瓜的状态<<raw>>,烧烤总时间<0>
地瓜的状态<<mature also raw>>,烧烤总时间<4>
地瓜的状态<<mature>>,烧烤总时间<7>
地瓜的状态<<too mature>>,烧烤总时间<8>
"""
写在最后
Python 的 应用领域 和 广泛的兼容性 ,使得 Pythoncoder 发出 “Life is short ,using Python” 的感叹,我之前是因为初学C语言被指针“霍霍”了,想曲线救国,所以开始学习Python脚本语言,才感到了Python的强大。 拥有数字图像处理的库Opencv,和前端修饰网页的框架Django,小游戏开发的库Pygame,数据矩阵运算的库NumPy,硬件开发的Micro-Python,数据挖掘的BeautifulSoup,正则运算的库Re…足可见Python的用处比较多,但是拥有一定C语言基础,会上手Python更快。 切记:勿眼高手低,勤敲多思考
|