小栗子1:寻找GPA最高的学生
#coding=gbk
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("Enter name the grade file: ")
infile = open(filename, 'r')
# 设置文件中第一个学生的记录为best
best = makeStudent(infile.readline())
# 处理文件剩余行数据
for line in infile:
# 将每一行数据转换为一个记录
s = makeStudent(line)
# 如果该学生是目前GPA最高的,则记录下来
if s.gpa() > best.gpa():
best = s
infile.close()
# 打印GPA成绩最高的学生信息
print("The best student is:", best.getName())
print("hours:", best.getHours())
print("GPA:", best.gpa())
main()
小栗子2:铅球轨迹计算
Projectile.py
from math import sin,cos,radians
class Projectile:
def __init__(self,angle,velocity,height):
#根据给定的发射角度、初始速度和位置创建一个投射体对象
self.xpos=0.0
self.ypos=height
theta = radians(angle)
self.xvel = velocity * cos(theta)
self.yvel = velocity * sin(theta)
def update(self,time):
#更新投射体的状态
self.xpos = self.xpos + time * self.xvel
yvel1 = self.yvel - 9.8 * time
self.ypos = self.ypos + time * (self.yvel + yvel1) / 2.0
self.yvel = yvel1
def getY(self):
return self.ypos
def getX(self):
return self.xpos
shot2.py
注意:这个import得改下才能运行,这两个文件是放在一起的。(tt是包名)
from tt.Projectile import Projectile
def getInputs():
a = eval(input("Enter the launch angle (in degrees):"))
h = eval(input("Enter the initial velocity (in meters/sec):"))
v = eval(input("Enter the initial height (in meters):"))
t = eval(input("Enter the time interval:"))
return a,v,h,t
def main():
angle,vel,h0,time = getInputs()
shot = Projectile(angle,vel,h0)
while shot.getY()>=0:
shot.update(time)
print("\nDistance traveled:{0:0.1f}meters.".format(shot.getX()))
main()