第1章Python编程基础
习题答案
1-1将一条消息赋给变量,并将其打印出来;再将变量的值修改为一条新信息,并将其打印出来。
#将一条消息赋给变量
message=Hello,World!
#打印变量的值
print(message)#输出:Hello,World!
#将变量的值修改为一条新信息
message=WelcometoPythonprogramming!
#打印修改后的变量的值
print(message)#输出:WelcometoPythonprogramming!
1-2求整数1-100的累加值,但要求跳过所有个位为3的数。
#初始化总和变量
total_sum=0
#遍历1到100(包括100)
foriinrange(1,101):
#检查i的个位是否为3
ifi%10!=3:
#如果不是,则加到总和中
total_sum+=i
#打印最终结果
print(total_sum)
1-3请定义一个count()函数,用来统计字符串“Hello,Pythonworld.”中字母l出现的次数。
defcount(s,char):
统计字符串s中字符char出现的次数。
参数:
s(str):要统计的字符串。
char(str):要统计的字符。
返回:
int:字符char在字符串s中出现的次数。
count=0
forcins:
ifc==char:
count+=1
returncount
#使用该函数统计l在字符串Hello,Pythonworld.中出现的次数
s=Hello,Pythonworld.
result=count(s,l)
print(fl出现的次数是:{result})
1-4定义一个“圆”Cirlcle类,圆心为“点”Point类。构造一个圆,求出圆的周长和面积,再随意构造三点并判断点与该圆的关系。
importmath
classPoint:
def__init__(self,x,y):
self.x=x
self.y=y
def__str__(self):
returnfPoint({self.x},{self.y})
classCircle:
def__init__(self,center,radius):
self.center=center
self.radius=radius
defcircumference(self):
return2*math.pi*self.radius
defarea(self):
returnmath.pi*(self.radius**2)
defrelationship(self,point):
distance=math.sqrt((point.x-self.center.x)**2+(point.y-self.center.y)**2)
ifdistanceself.radius:
returnInsidethecircle
elifdistance==self.radius:
returnOnthecircle
else:
returnOutsidethecircle
#构造圆
center=Point(0,0)#圆心在原点
radius=5#半径为5
circle=Circle(center,radius)
#计算周长和面积
print(fCircumference:{circle.circumference()})
print(fArea:{circle.area()})
#构