Python Day04习题

函数习题

01

在这里插入图片描述

def getPentagonalNumber(n):
    count = 0
    for i in range(1,n + 1):
        num = i * (3 * i-1)/2
        #数字间以空格隔开
        print("%d"%num,end = ' ')
        count += 1
        #每行显示10个
        if count % 10 ==0:
            print('\n')


getPentagonalNumber(100)    
"""
运行结果:
1 5 12 22 35 51 70 92 117 145

176 210 247 287 330 376 425 477 532 590

651 715 782 852 925 1001 1080 1162 1247 1335

1426 1520 1617 1717 1820 1926 2035 2147 2262 2380

2501 2625 2752 2882 3015 3151 3290 3432 3577 3725

3876 4030 4187 4347 4510 4676 4845 5017 5192 5370

5551 5735 5922 6112 6305 6501 6700 6902 7107 7315

7526 7740 7957 8177 8400 8626 8855 9087 9322 9560

9801 10045 10292 10542 10795 11051 11310 11572 11837 12105

12376 12650 12927 13207 13490 13776 14065 14357 14652 14950
"""



02

在这里插入图片描述

def sumDigits(n):
    ge = int(n) % 10
    c = 0
    for i in range(len(str(n))):
        bai = int(n) // (10 * (10 ** i)) % 10
        c += bai
    sum = c + ge
    print("这个整数之和是:%d"%sum)
sumDigits(12345)
"""
运行结果:
这个整数之和是:15
"""

"""

03

在这里插入图片描述

def display(num1,num2,num3):
    list = [num1,num2,num3]
    s = sorted(list)
    print("给三位数字排序得{}".format(s))
if __name__ == "__main__":
    a,b,c = map(int,input("请输入三个数字:"))
    display(a,b,c)

"""
运行结果:
请输入三个数字:654
给三位数字排序得[4, 5, 6]
"""

04

在这里插入图片描述

from prettytable import PrettyTable
list = []
def futureInvestmentValue(inAmount,rate,years):
    for i in range(1,years + 1):
        futureInvestment = inAmount + ((1 +rate) ** (12 * i))
        list.append([i,futureInvestment])
    table = PrettyTable(['year','Future Value'])
    for row in list:
        table.add_row(row)
    print(table)
if __name__ == "__main__":
    inAmount = int(input("请输入投资额:"))
    rate = float(input("请输入百分比格式的年利率:")) / 12
    futureInvestmentValue(inAmount,rate,years = 30)
"""
运行结果:
请输入投资额:10000
请输入百分比格式的年利率:0.05
+------+--------------------+
| year |    Future Value    |
+------+--------------------+
|  1   | 10001.051161897882 |
|  2   | 10001.104941335558 |
|  3   | 10001.161472231333 |
|  4   | 10001.220895355025 |
|  5   | 10001.283358678504 |
|  6   | 10001.349017744158 |
|  7   | 10001.418036052226 |
|  8   | 10001.490585467922 |
|  9   | 10001.566846649417 |
|  10  | 10001.64700949769  |
|  11  | 10001.73127362942  |
|  12  | 10001.819848874055 |
|  13  | 10001.91295579631  |
|  14  | 10002.010826245412 |
|  15  | 10002.113703932439 |
|  16  | 10002.221845037182 |
|  17  | 10002.335518846083 |
|  18  | 10002.455008422789 |
|  19  | 10002.580611313013 |
|  20  | 10002.712640285483 |
|  21  | 10002.851424110757 |
|  22  | 10002.99730837993  |
|  23  | 10003.150656365184 |
|  24  |  10003.3118499244  |
|  25  | 10003.481290452031 |
|  26  | 10003.659399878636 |
|  27  | 10003.846621721534 |
|  28  | 10004.043422189241 |
|  29  | 10004.25029134238  |
|  30  | 10004.467744314006 |
+------+--------------------+
"""
    

05

在这里插入图片描述

def printChars():
    for i in range(73,91):
        print(chr(i),end=" ")
        if i% 10 == 0:
            print("\n")
printChars()

"""
运行结果:
I J K L M N O P

Q R S T U V W X Y Z
"""

06

在这里插入图片描述

def numberOfDaysInAYear(year):
    for count in range(year,year+11):
        if count % 4 == 0 and count % 100 != 0 or count % 400 == 0:
            print("{}年有366天".format(count))
        else:
            print("{}年有365天".format(count))
numberOfDaysInAYear(2010)

"""
运行结果:
2010年有365天
2011年有365天
2012年有366天
2013年有365天
2014年有365天
2015年有365天
2016年有366天
2017年有365天
2018年有365天
2019年有365天
2020年有366天
"""

07

在这里插入图片描述

def distance(x1,x2,y1,y2):
    dis = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
    print("这两个点的距离是:%f"%dis)
distance(1,4,4,2)
"""
运行结果:
这两个点的距离是:3.605551
"""

08

在这里插入图片描述

from prettytable import PrettyTable
def mei(p):
    c = []
    b = []
    for p in range(2,32):
        if p>1:
            for i in range(2,p):
                if (p % i) == 0:
    #print(p,"不是质数")
    #print(i,"乘于",p//i,"是",p)
                    break
                else:
                    #print(p,"是质数")
                    d = 2**(p-1)
                    c.append([p,d])
    for x in c:
        if x not in b:
            b.append(x)
            table = PrettyTable(['p','2**(p-1)'])
    for row in b:
        table.add_row(row)
    print(table)
mei(5)

"""
运行结果:
+----+------------+
| p  |  2**(p-1)  |
+----+------------+
| 3  |     4      |
| 5  |     16     |
| 7  |     64     |
| 9  |    256     |
| 11 |    1024    |
| 13 |    4096    |
| 15 |   16384    |
| 17 |   65536    |
| 19 |   262144   |
| 21 |  1048576   |
| 23 |  4194304   |
| 25 |  16777216  |
| 27 |  67108864  |
| 29 | 268435456  |
| 31 | 1073741824 |
+----+------------+
"""

09

在这里插入图片描述

import time
def main():
    localtime = time.asctime(time.localtime(time.time()))
    print("本地时间为 :", localtime)
main()

"""
运行结果:
本地时间为 : Mon Aug 19 22:43:14 2019
"""

10

在这里插入图片描述

import random
def shaizi():
    a=random.choice([1,2,3,4,5,6])
    b=random.choice([1,2,3,4,5,6])
    if a+b==2 or  a+b==3 or a+b==12:
        print('%d + %d = %d' %(a,b,a+b))
        print('你输了')
    elif a+b==7 or a+b==11:
        print('%d + %d = %d' %(a,b,a+b))
        print('你赢了')
    else:
        print('%d + %d = %d' %(a,b,a+b))
        c=random.choice([1,2,3,4,5,6])
        d=random.choice([1,2,3,4,5,6])
        if c+d==7:
            print('%d + %d = %d' %(c,d,c+d))
            print('你输了')
        elif c+d==a+b:
            print('%d + %d = %d' %(c,d,c+d))
            print('你赢了')
shaizi()
"""
运行结果1:
6 + 3 = 9
3 + 6 = 9
你赢了
运行结果2:
5 + 3 = 8
4 + 3 = 7
你输了
运行结果3:
5 + 6 = 11
你赢了
"""

类习题

01

在这里插入图片描述

class Rectangle(object):
    def __init__(self,width=1,height=2):
        self.width = width
        self.height = height
    #定义面积
    def getArea(self):
        return self.width*self.height

    #定义周长
    def getPerimeter(self):
        return (self.width+self.height)*2

def main():
    rectangle = Rectangle(5)
    print('宽是>>',rectangle.width)
    print('高是>>',rectangle.height)
    print('面积是>>',rectangle.getArea())
    print('周长是>>',rectangle.getPerimeter())
    print('---------------------------------')
    tom = Rectangle(8,4)
    print('宽是>>',tom.width)
    print('高是>>',tom.height)
    print('面积是>>',tom.getArea())
    print('周长是>>',tom.getPerimeter())
if __name__ == "__main__":
    main()
""" 
运行结果:
宽是>> 5
高是>> 2
面积是>> 10
周长是>> 14
---------------------------------
宽是>> 8
高是>> 4
面积是>> 32
"""

02

在这里插入图片描述

class Account(object):
    def __init__(self,id=0,balance=100,annuallnteresterRate=0):
        self._id = id
        self._balance = balance
        self._annuallnteresterRate = annuallnteresterRate
    @property
    def id(self):
        return self._id
    @id.setter
    def id(self,new_id):
        self._id = new_id
    @property
    def balance(self):
        return self._balance

    @balance.setter
    def balance(self,new_balance):
        self._balance = new_balance

    @property
    def annuallnteresterRate(self):
        return self._annuallnteresterRate

    @annuallnteresterRate.setter
    def annuallnteresterRate(self,new_annuallnteresterRate):
        self._annuallnteresterRate = new_annuallnteresterRate

    def MonthlyIInterestRate(self,new_id,new_balance,new_annuallnteresterRate):
        return new_annuallnteresterRate /12

    def MonthlyInterest(self,new_id,new_balance,new_annuallnteresterRate):
        return new_balance*new_annuallnteresterRate/12

    def withdraw(self,new_id,new_balance,new_annuallnteresterRate):
        print('取出金额为:')

    def deposit(self,new_id,new_balance,new_annuallnteresterRate):
        print('充进金额为:')
def main():
    tom = Account()
    tom.id = 1122
    tom.balance = 20000
    tom.annuallnteresterRate = 0.45
    tom.withdraw = 2500
    tom.deposit = 3000
    print('此账号id是>>',tom.id)
    a = tom.balance -tom.withdraw+tom.deposit
    print('余额是>>',a)
    tom.MonthlyIInterestRate = tom.annuallnteresterRate/12
    print('月利率是>>',tom.MonthlyIInterestRate)
    tom.MonthlyInterest = a*tom.MonthlyIInterestRate
    print('月利息是>>',tom.MonthlyInterest)
if __name__ == "__main__":
    main()

"""
运行结果:
此账号id是>> 1122
余额是>> 20500
月利率是>> 0.0375
月利息是>> 768.75
"""

03

在这里插入图片描述

class Fan(object):
	    def __init__(self,speed=1,on=False,radius=5.0,color="blue"):
	        self.__speed = int(speed)
	        self.__on = bool(on)
	        self.__radius = float(radius)
	        self.__color = str(color)
	    @property
	    def speed(self):
	       return self.__speed
	    @speed.setter
	    def speed(self,new_speed):
	       if self.__speed == 1:
	            self.__speed=new_speed = "SLOW"
	       elif self.__speed == 2:
	            self.__speed=new_speed = "MEDIUM"
	       elif self.__speed == 3:
	            self.__speed=new_speed = "FAST"
	    @property
	    def on(self):
	        return self.__on
	    @on.setter
	    def on(self,new_on):
	        self.__on==new_on
	
	    @property
	    def radius(self):
	        return self.__radius
	    @radius.setter
	    def radius(self,new_radius):
	        self.__radius==new_radius
	
	    @property
	    def color(self):
	        return self.__color
	    @color.setter
	    def color(self,new_color):
	        self.__color==new_color
	
	    def fans(self):
	        print("{}颜色的风扇半径为{},速度{},打开状态{}".format(self.__color,self.__radius,self.__speed,self.__on))
	
	if __name__ == '__main__':
	    lulu = Fan()
	    lulu.fans()
	    lulu1 = Fan(3,on=True,radius=10.0,color="yellow")
	    lulu1.fans()
	    lulu1 = Fan(2,on=False,radius=5.0,color="blue")
	    lulu1.fans()

04

在这里插入图片描述

	import math
	class RegularPolygon(object):
	    def __init__(self,n=3,length=1,x = 0,y = 0):
	        self.__n = n
	        self.__length = length
	        self.__x = x
	        self.__y = y
	    def N(self):
	        return self.__n
	    def side(self):
	        return self.__length
	    def getPerimeter(self):
	        perimeter = self.__n * self.__length
	        return perimeter
	    def getArea(self):
	        area = round((self.__n * self.getPerimeter() * self.getPerimeter()) /( 4 * math.tan(math.pi/4)),2)
	        return area
	def main():
	    Re = RegularPolygon(4,1,8,0) 
	    a = Re.getPerimeter()
	    b = Re.getArea()
	    n = Re.N()
	    length = Re.side()
	    print("这是一个",n,"边形","边长是",length,"周长为",a,"面积为",b)
	main()

05

在这里插入图片描述

	class LinearEquation(object):
	    def __init__(self):
	        pass
	    def main(self):
	        a = float(input('a= '))
	        b = float(input('b= '))
	        c = float(input('c= '))
	        d = float(input('d= '))
	        e = float(input('e= '))
	        f = float(input('f= '))
	        self.isSolvable(a,b,c,d,e,f)
	    def isSolvable(self,a,b,c,d,e,f):
	        if a*d-b*c ==0:
	            print('此方程无解')
	        else:
	            x = (e*d-b*f)/(a*d-b*c)
	            y = (a*f-e*c)/(a*d-b*c)
	            print('x为:',x)
	            print('y为:',y)
	if __name__ == "__main__":
	    linearequation = LinearEquation()
	    linearequation.main()

06

在这里插入图片描述

	class LinearEquation(object):
	    def __init__(self):
	        pass
	    def main(self):
	        x1,y1=eval(input('请输入第一条直线的一个端点'))
	        x2,y2=eval(input('请输入第一条直线的二个端点'))
	        x3,y3=eval(input('请输入第二条直线的一个端点'))
	        x4,y4=eval(input('请输入第二条直线的二个端点'))
	        self.jisuan(x1,y1,x2,y2,x3,y3,x4,y4)
	    def jishuan(self,x1,y1,x2,y2,x3,y3,x4,y4):
	        a = y2-y1
	        b = x2*y1-x1*y2
	        c = x2-x1
	        d = y4-y3
	        e = x4*y3-x3*y4
	        f = x4-x3
	        self.gongshi(a,b,c,d,e,f)
	    def gongshi(self,a,b,c,d,e,f):
	        y = float(a*e-b*d)/(a*f-c*d)
	        x = float(y*c-b)/a
	        print('交点的坐标为:',(x,y))
	if __name__ == "__main__":
	    linearequation = LinearEquation()
	    linearequation.main()

07

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值