python课堂作业
p211-1
f = open('p211-1.txt', 'a+')
for row in range(1, 10):
for col in range(1, row+1):
print(row, "*", col, "=", row*col, end=" ", file=f)
print(" ", file=f)
f.close()
p211-3
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('sheet')
worksheet.write(2, 2, '我喜欢编程')
workbook.save('p211-3.xls')
p242-1
class circle:
def __init__(self, bj):
self.bj = bj
self.pi = 3.14159265
def circumference(self):
return float(self.bj*2*self.pi)
def area(self):
return float(self.bj*self.bj*self.pi)
for i in range(1, 11):
cir = circle(i)
print("半径为%d的圆:面积: %0.2f 周长: %0.2f" % (i, cir.area(), cir.circumference()))
p302-1
import tkinter as tk
import tkinter.messagebox
def bindFun():
tkinter.messagebox.showinfo("测试", "hello!world")
top = tk.Tk()
top.geometry('250x100')
top.title('按钮')
button1 = tk.Button(top, text='测试', command=bindFun)
button1.pack()
top.mainloop()
p302-2
import tkinter as tk
import tkinter.messagebox
def get():
s1 = e1.get()
s2 = e2.get()
if (s1 == 'admin' and s2 == 'admin'):
tk.messagebox.showinfo("登录结果", "登录成功")
else:
tk.messagebox.showinfo("登录结果", "用户名或账号错误")
top = tk.Tk()
top.geometry('200x100')
top.title('登录')
tk.Label(top, text='账号').grid(row=0)
tk.Label(top, text='密码').grid(row=1)
e1 = tk.Entry(top)
e2 = tk.Entry(top, show='*')
s1 = e1.get()
s2 = e2.get()
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
b1 = tk.Button(top, text='登录', command=get)
b1.grid(row=3)
b2 = tk.Button(top, text='退出', command=top.quit)
b2.grid(row=3, column=1)
top.mainloop()
p302-5
import tkinter as tk
def create_btn(text,col,row,cs,rs,px=(1,1),py=(1,1)): #函数生成按钮
t=text
t=t.replace('×','*')
t=t.replace('÷','/')
t=t.replace('x²','**2')
t=t.replace('1/x','**(-1)')
a=tk.Button(root,text=text,width=4,command=lambda:(text_print(t)))
a.grid(column=col,row=row,columnspan=cs,rowspan=rs,padx=px,pady=py,sticky='nswe')
return(a)
def grid_rowconfigure(*rows): #函数填充行
for i in rows:
root.grid_rowconfigure(i,weight=1)
def grid_columnconfigure(*cols): #函数填充列
for i in cols:
root.grid_columnconfigure(i,weight=1)
def bind_print(event): #函数键盘事件输入算式
global textchange,equal_is
if event.keysym!='Return':
if event.keysym=='BackSpace':
a=str(textchange)[0:-1]
textchange=a
elif event.keysym=='Delete':
textchange=''
else:
textchange=str(textchange)+str(event.char)
la.configure(text=textchange)
show_is()
equal_is=False
else:
text_equal()
def text_print(x): #函数按钮输入算式
global textchange,equal_is
if x!='=':
if x=='←':
a=str(textchange)[0:-1]
textchange=a
elif x=='C':
textchange=''
else:
textchange=str(textchange)+str(x)
la.configure(text=textchange)
show_is()
equal_is=False
if x=='=':
text_equal()
def text_equal(event=None): #函数计算结果并上到输入框
global textchange,equal_is
if lab['text']!='错误' and equal_is==False:
textchange=lab['text']
la.configure(text=textchange)
lab.configure(text='')
equal_is=True
def show_is(): #显示框内容
global textchange
if textchange!='':
try:
textshow=eval(textchange)
except (SyntaxError,TypeError,NameError):
lab.configure(text='错误')
else:
lab.configure(text=textshow)
else:
lab.configure(text='')
root=tk.Tk() #创建窗体
root.geometry('250x350')
root.title('计算器')
root.bind('<Key>',bind_print)
equal_is=False #一些变量
textchange=''
la=tk.Label(root,text='',bg='white',fg='black',font=('宋体',24),anchor='w',relief='flat') #生成输入框
la.grid(column=0,row=0,columnspan=5,rowspan=1,sticky='we')
lab=tk.Label(root,bg='white',fg='grey',height=1,font=('宋体',22),anchor='w',relief='flat') #生成显示框
lab.grid(column=0,row=1,columnspan=5,rowspan=1,sticky='we')
btn={} #生成按钮
btn['1']=create_btn('1',0,5,1,1)
btn['2']=create_btn('2',1,5,1,1)
btn['3']=create_btn('3',2,5,1,1)
btn['4']=create_btn('4',0,4,1,1)
btn['5']=create_btn('5',1,4,1,1)
btn['6']=create_btn('6',2,4,1,1)
btn['7']=create_btn('7',0,3,1,1)
btn['8']=create_btn('8',1,3,1,1)
btn['9']=create_btn('9',2,3,1,1)
btn['0']=create_btn('0',0,6,2,1)
btn['.']=create_btn('.',2,6,1,1)
btn['=']=create_btn('=',4,5,1,2)
btn['+']=create_btn('+',3,6,1,1)
btn['-']=create_btn('-',3,5,1,1)
btn['*']=create_btn('×',3,4,1,1)
btn['/']=create_btn('÷',4,4,1,1)
btn['←']=create_btn('←',1,2,1,1)
btn['C']=create_btn('C',2,2,1,1)
btn['(']=create_btn('(',3,2,1,1)
btn[')']=create_btn(')',4,2,1,1)
btn['**2']=create_btn('x²',3,3,1,1)
btn['**(-1)']=create_btn('1/x',4,3,1,1)
grid_rowconfigure(2,3,4,5,6)
grid_columnconfigure(0,1,2,3,4)
root.mainloop()
练习1
输入正整数n,求n的阶乘,并捕获输入数字格式异常。另外,自定义异常类,当用户输入的值小于等于零时,抛出并捕获自定义异常
while 1:
fg = 1
num = 0
sum = 1
try:
num = int(input("输入一个正整数"))
if num <= 0:
raise ValueError
except NameError:
print("输入有误")
fg = 0
except ValueError:
print("输入有误")
fg = 0
if fg == 1:
sum = 1
for i in range(1, num+1, 1):
sum = sum*i
print(sum)
练习2
自行设计一个实例并编写程序实现类的继承与组合。
(1)父类要包含初始化方法、至少三个实例属性、一个类属性和两个普通方法。
(2)子类要能继承两个父类,至少包含两个不同类的对象作为属性,至少重写一个父类方法和一个父类属性。子类应包含初始化方法和至少两个普通方法,其中一个用于打印子类的所有属性取值。
(3)编写主程序,产生子类的实例,并测试子类的功能
class car():
def __init__(self, type, number, people):
self.type = type
self.number = number
self.people = people
def type_in(self):
return self.type
def number_in(self):
return self.number
def people(self):
return self.people
def show(self):
print('车牌号为 %s 的 %s' % (self.number, self.type))
class notion():
def __init__(self, what, where, num):
self.what = what
self.where = where
self.num = num
def what_in(self):
return self.what
def where_in(self):
return self.where
def num_in(self):
return self.num
def show1(self):
print(self.num)
def message(self):
fig = self.num
if (fig == 1):
car1.show()
print('在 %s %s 扣6分' % (self.where, self.what))
else:
car1.show()
print('在 %s %s 扣2分' % (self.where, self.what))
class demo(car, notion):
def __init__(self, type, number, people, what, where, num):
car.__init__(self, type, number, people)
notion.__init__(self, what, where, num)
def showall(self):
self.message()
car2 = demo('汽车', '鲁Q654321', '3', '不礼让行人', '二号街道', '2')
car2.showall()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】