1.计算圆的面积和周长
from math import pi
class Circle():
def __init__(self,r):
self.r=r
def zhouchang(self):
return 2*pi*self.r
def area(self):
return pi*self.r*self.r
a=int(input('请输入圆的半径:'))
circle=Circle(a)
zc=circle.zhouchang()
print('周长是:',zc)
s=circle.area()
print('面积是:',s)
运行结果:
请输入圆的半径:2
周长是: 12.566370614359172
面积是: 12.566370614359172
2.考羊肉串练习
羊肉串在0~3分钟之内状态为生的
在3~6分钟之内状态为半生不熟
在7~10分钟之内为烤熟状态
大于10分钟为烤焦
class KYRC():
def __init__(self):
self.cooke_time=0
self.cooke_zt='生的'
def cook(self,cook_time):
self.cooke_time = cook_time
if cook_time in range(0,4):
self.cooke_zt='生的'
elif cook_time in range(4,7):
self.cooke_zt='半生不熟'
elif cook_time in range(7,10):
self.cooke_zt='烤熟了'
else:
self.cooke_zt='烤焦了'
def __str__(self):
msg='烤的时间为{}分钟,状态为{}'.format(self.cooke_time,self.cooke_zt)
return msg
while True:
a=int(input('请输入烤羊肉串的时间:'))
chuan=KYRC()
chuan.cook(a)
print(chuan)
运行结果·:
请输入烤羊肉串的时间:3
烤的时间为3分钟,状态为生的
请输入烤羊肉串的时间:5
烤的时间为5分钟,状态为半生不熟
请输入烤羊肉串的时间:8
烤的时间为8分钟,状态为烤熟了
请输入烤羊肉串的时间:12
烤的时间为12分钟,状态为烤焦了
请输入烤羊肉串的时间:
累计时间烤羊肉串和加调味料
class KYRC():
def __init__(self):
self.cooke_time = 0 # 初始化烤的时间为0
self.cooke_zt = '生的' # 初始化烤的状态为生的
self.cooke_zl = [] # 初始化添加的佐料为空
def cook(self, cooke_time):
self.cooke_time += cooke_time
if self.cooke_time in range(0, 4):
self.cooke_zt = '生的'
elif self.cooke_time in range(4, 7):
self.cooke_zt = '半生不熟'
elif self.cooke_time in range(7, 10):
self.cooke_zt = '烤熟了'
else:
self.cooke_zt = '烤焦了'
def __str__(self):
msg = '烤的时间为{}分钟,状态为{},添加的佐料为{}'.format(self.cooke_time, self.cooke_zt, self.cooke_zl)
return msg
def add_zl(self, zl):
self.cooke_zl.append(zl)
chuan = KYRC()
chuan.cook(2)
chuan.add_zl('孜然')
print(chuan)
chuan.cook(5)
chuan.add_zl('盐')
print(chuan)
chuan.cook(3)
chuan.add_zl('辣椒')
print(chuan)
运行结果:
烤的时间为2分钟,状态为生的,添加的佐料为['孜然']
烤的时间为7分钟,状态为烤熟了,添加的佐料为['孜然', '盐']
烤的时间为10分钟,状态为烤焦了,添加的佐料为['孜然', '盐', '辣椒']
累计时间烤羊肉串和加调味料使用循环方式添加
class KYRC():
def __init__(self):
self.cooke_time = 0 # 初始化烤的时间为0
self.cooke_zt = '生的' # 初始化烤的状态为生的
self.cooke_zl = [] # 初始化添加的佐料为空
def cook(self, cooke_time):
self.cooke_time += cooke_time
if self.cooke_time in range(0, 4):
self.cooke_zt = '生的'
elif self.cooke_time in range(4, 7):
self.cooke_zt = '半生不熟'
elif self.cooke_time in range(7, 10):
self.cooke_zt = '烤熟了'
else:
self.cooke_zt = '烤焦了'
def __str__(self):
msg = '烤的时间为{}分钟,状态为{},添加的佐料为{}'.format(self.cooke_time, self.cooke_zt, self.cooke_zl)
return msg
def add_zl(self, zl):
self.cooke_zl.append(zl)
chuan=KYRC() #注意不要把赋值对象放到循环内,否则会格式化数据,无法实现添加的效果
while True:
a = int(input('请输入烤羊肉串的时间:'))
b = input('请输入添加的佐料:')
chuan.cook(a)
chuan.add_zl(b)
print(chuan)
运行结果:
请输入烤羊肉串的时间:3
请输入添加的佐料:孜然
烤的时间为3分钟,状态为生的,添加的佐料为['孜然']
请输入烤羊肉串的时间:5
请输入添加的佐料:辣椒
烤的时间为8分钟,状态为烤熟了,添加的佐料为['孜然', '辣椒']
请输入烤羊肉串的时间:4
请输入添加的佐料:盐
烤的时间为12分钟,状态为烤焦了,添加的佐料为['孜然', '辣椒', '盐']
请输入烤羊肉串的时间: