五月天青色头像情侣网名,国产亚洲av片在线观看18女人,黑人巨茎大战俄罗斯美女,扒下她的小内裤打屁股

歡迎光臨散文網(wǎng) 會員登陸 & 注冊

三月十一日

2023-03-11 13:23 作者:最近的愿望是潮石  | 我要投稿

1.3

print('《涼州詞》'.center(20))
print('{:>20s}'.format('王之渙'))
print('黃河遠上白云間,一片孤城萬仞山。')
print('羌笛何須怨楊柳,春風不度玉門關(guān)。')
print('單于北望拂云堆,殺馬登壇祭幾回。')
print('漢家天子今神武,不肯和親歸去來。')

2.1

# 實戰(zhàn)1 輸出人生四大喜事
print("? ?人生四大喜事?")
print("久旱逢甘雨---第一喜")
print("他鄉(xiāng)遇故知---第二喜")
print("洞房花燭夜---第三喜")
print("金榜題名時---第四喜")

2.2

# 模擬成語填空游戲
print("? 拒")
print("? 人")
print("? 千")
print("忙? 偷閑")
blank=input("請輸入所缺字:")
print("? 拒")
print("? 人")
print("? 千")
print(f"忙{blank}偷閑")

2.3

# 實戰(zhàn)2-3 輸入體重,身高和年齡,根據(jù)公式計算正常女性一天的基礎(chǔ)代謝。(計算公式為:女性的基礎(chǔ)代謝=655+(9.6×體重kg)+(1.7×身高cm)-(4.7×年齡))。
weight = float(input("請輸入體重(kg):"))
height = float(input("請輸入身高(cm):"))
age = int(input("請輸入年齡:"))
result = 655 + (9.6 * weight) + (1.7 * height) - (4.7 * age)
print("基礎(chǔ)代謝為:" + str(result) + "大卡.")

# 實戰(zhàn)2-4 模擬打印超市購物小票。輸入商品名稱、單價、數(shù)量,計算總價。用戶輸入整錢,實現(xiàn)找零和抹零的功能,最后打印購物小票。(假設(shè)只購買一件物品)
print("Python超市收銀系統(tǒng)")
product_name = input("商品名稱:")
price = float(input("商品單價:"))
number = float(input("數(shù)量:"))
pay_user = round(price * number, 2)
print("應(yīng)付金額:" + str(pay_user))
pay = float(input("實收:"))
print("Python超市購物小票")
print("商品名稱\t單價\t\t數(shù)量")
print(str(product_name) + "\t\t" + str(price) + "\t" + str(number))
print("應(yīng)付:" + str(pay_user))
print("實收:" + str(pay))
print("找零" + str(round(pay - pay_user, 1)))

# 實戰(zhàn)2-5 輸入《中國必勝》藏頭詩,打印藏頭詩句。輸入和輸出效果如下:
# 中庭寒月白如霜,
# 國門卿相舊山莊。
# 必擬一身生羽翼,
# 勝景飽于閑采拾。
print("請輸入《中國必勝》藏頭詩:")
Line1 = input( )
Line2 = input( )
Line3 = input( )
Line4 = input( )
print("《中國必勝》藏頭句為:")
print(Line1[0])
print(Line2[0])
print(Line3[0])
print(Line4[0])

# 實戰(zhàn)2-6 輸入直角三角形的底和高,用勾股定理計算斜邊長,并打印輸出該三角形的三條邊的長。(提示:需要用到math模塊中的sqrt()函數(shù)求平方根)
import math

bottom = float(input("底邊:"))
height = float(input("高:"))
hypotenuse = math.sqrt(bottom ** 2 + height ** 2)
print("斜邊:", end='')
print("%.2f" % hypotenuse)

3.1

# 實戰(zhàn)2 判斷閏年
year = int(input("請輸入年份:"))
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
??? print(str(year) + "是閏年!")
else:
??? print(str(year) + "不是閏年!")

3.2

import math
a=int(input("請輸入三角形的第一條邊長:"))
b=int(input("請輸入三角形的第二條邊長:"))
c=int(input("請輸入三角形的第三條邊長:"))

if a+b > c and a+c>b and b+c >a :
??? print("三角形的周長:{}".format(a+b+c))

??? #三角形面積,已知三邊利用海倫公式(p=(a+b+c)/2)
??? #S=sqrt[p(p-a)(p-b)(p-c)]
??? p=(a+b+c)/2
??? area=math.sqrt(p*(p-a)*(p-b)*(p-c))

??? print("三角形的面積:{}".format(area))

else:
??? print("輸入的邊長不能構(gòu)成三角形,請重新輸入")

3.3

# 某小學的學優(yōu)生評定標準:語文、數(shù)學、英語和科學四門課程的總分不低于380分,且每科成績不低于95分,編程判斷某位同學是否為學優(yōu)生。
language, math, english, science = input("請輸入語文,數(shù)學,英語和科學百分制成績:").split(" ")
if int(
??????? language + math + english + science) >= 380 and int(language) >= 95 and int(math) >= 95 and int(
??? english) >= 95 and int(science) >= 95:
??? print("該生是學優(yōu)生.")
else:
??? print("該生不是學優(yōu)生.")

3.4

'''(簡易版?zhèn)€稅計算器)某公司員工小王每月稅前工資為salary,五險一金等扣除為insurance,其他專項扣除為other,請編程計算小王每月應(yīng)繳納稅額和實發(fā)工資。
注:應(yīng)繳納稅額=稅前收入-5000(起征點)-五險一金扣除-其他扣除
個人所得稅=應(yīng)繳納稅額?適用稅率-速算扣除數(shù)
實發(fā)工資=稅前工資-個人所得稅-五險一金
'''
salary = float(input('本月收入:'))
insurance = float(input('五險一金扣除:'))
other = float(input('其他專項扣除:'))
diff = salary - insurance - other - 5000

if diff <= 0:
??? rate, deduction = 0, 0? # 分別表示稅率和速算扣除
elif diff < 3000:
??? rate, deduction = 0.03, 0
elif diff < 12000:
??? rate, deduction = 0.1, 210
elif diff < 25000:
??? rate, deduction = 0.2, 1410
elif diff < 35000:
??? rate, deduction = 0.25, 2660
elif diff < 55000:
??? rate, deduction = 0.3, 4410
elif diff < 80000:
??? rate, deduction = 0.35, 7160
else:
??? rate, deduction = 0.45, 15160

tax = abs(diff * rate - deduction)
print('個人所得稅: ¥%.2f元' % tax)
print('實際到手收入:¥%.2f元' % (salary - tax - insurance))

3.5

'''幸運52猜數(shù)游戲(模仿幸運52中猜價錢游戲,編寫程序,計算機隨機產(chǎn)生一個1~100正整數(shù),讓用戶猜,
并提醒用戶猜大了還是猜小了,直到用戶猜對為止,計算用戶猜對一個數(shù)所用的秒數(shù)。)
'''
import random
import time

n = random.randint(1, 100)
begin_time = time.time( )
x = int(input("請輸入一個1~100的整數(shù):"))
while x != n:
??? if x > n:
??????? print("大了!")
??? else:
??????? print("小了!")
??? x = int(input("請輸入一個1~100的整數(shù):"))
end_time = time.time( )
print("用時為" + str(end_time - begin_time))

3.6

# 實戰(zhàn)3-6:求出所有的水仙花數(shù)。
for i in range(100, 1000):
??? x1 = i // 100
??? x2 = (i % 100) // 10
??? x3 = i % 10
??? if (x1 ** 3 + x2 ** 3 + x3 ** 3 == i):
??????? print(i, end="\t")

3.7

# 模擬打印超市購物小票升級版。輸入商品名稱、價格、數(shù)量,算出應(yīng)付金額。用戶輸入整錢,實現(xiàn)找零和抹零的功能,最后打印購物小票。
print("Python超市收銀系統(tǒng)")
num = int(input("商品個數(shù):"))
sum, product_name, product_price, product_number = 0.0, [], [], []
print("商品名稱\t單價\t\t數(shù)量")
for i in range(0, num):
??? name,price,number=input().split(" ")
??? product_name.append(name)
??? product_price.append(float(price))
??? product_number.append(float(number))
??? #price+=input().split(" ")
??? #number+=input()
??? sum += round(float(product_price[i]) * float(product_number[i]), 2)
print("應(yīng)付金額:" + str(sum))
pay = float(input("實收:"))
print("Python超市購物小票\n共購買%d件商品" % num)
print("商品名稱\t單價\t\t數(shù)量")
for i in range(0, num):
??? print(product_name[i] + "\t\t" + str(product_price[i]) + "\t" + str(product_number[i]))
print("應(yīng)付:" + str(sum))
print("實收:" + str(pay))
print("找零" + str(round(pay - sum, 1)))

3.8

# 有一個分數(shù)數(shù)列 ,編程計算這個數(shù)列的前20項之和。
nume, deno, sum = 2, 1, 0.0? # 分子,分母,和
for i in range(1, 21):
??? sum = sum + nume / deno? # 和
??? t = deno? # 暫存前一項的分母
??? deno = nume? # 后一項的分母為前一項的分子
??? nume = t + nume? # 后一項的分子為前一項的分母+分子
print("sum=%.2f" % sum)

3.9

# 求所有的四位“回文數(shù)”。(“回文數(shù)”是一種特殊數(shù)字,就是說一個數(shù)字從左邊讀和從右邊讀的結(jié)果是一模一樣的。)
count = 0
for i in range(1000, 10000):
??? fourth = i // 1000? # 千位
??? third = i % 1000 // 100? # 百位
??? second = i % 100 // 10? # 十位
??? first = i % 10? # 個位
??? if fourth == first and third == second:
??????? count = count + 1
??????? print(i, end="\t")
??????? if count % 10 == 0:
??????????? print( )

3.10

'''
編程實現(xiàn):打印出1~ 1000 之間包含3的數(shù)字。如果3是連在一起的(如233 )則在數(shù)字前加上&;
如果這個數(shù)字是質(zhì)數(shù)則在數(shù)字后加上*,(例 3,13*,23*,&33,43*……&233*…)
'''
#list0=[]
a='33'
for i in range(3,1000,10):
??? if i%3 ==0:
??????? j = str(i)
??????? if a in j:
??????????? print('&', j,'*')
??????? else:
??????????? print(i)
??? else:
??????? print(i, '*')

4.1

list1=[]
tuple1=(0,1,2,3,4,5,6,7,8,9)
set1=set()
for i in range(10):
??? list1.append(i)
??? set1.add(i)
print(list1)
print(tuple1)
print(set1)

4.2

list1=[]
tuple1=(0,1,2,3,4,5,6,7,8,9)
set1=set()
for i in range(10):
??? list1.append(i)
??? set1.add(i)
list2=list1[1,3,5]
tuple2=tuple1[1,3,5]

4.3

#【訓練4.3】已知某數(shù)據(jù)為“abcdedcba”,利用所學的知識輸出該數(shù)據(jù)中的元素(不輸出重復(fù)元素)。
a="abcdedcba"
seta=set(a)
print(seta)

4.4

#【訓練4.4】將自己的學號、姓名、性別信息定義為一個字典,并利用講過的方法添加自己的身高信息到字典中,然后輸出自己的這四個信息。
dict1={"name":"zhangsan","ID":"209003031","sex":"Male"}
dict1["height"]=177
print(dict1)

4.5

#【訓練4.5】定義一個包含10個同學考試成績的元組,然后運用講過的相關(guān)函數(shù)輸出10個同學中的最高分、最低分及平均分。
tuple1=(77,84,67,90,89,56,70,80,93,73)
max_score=max(tuple1)
min_score=min(tuple1)
ave_socre=sum(tuple1)/len(tuple1)
print("最高分:",max_score,"最低分:",min_score,"平均分:",ave_socre)

4.6

#該實例實現(xiàn)功能:根據(jù)詩名猜作者
import random
#首先定義一個字典,字典中的元素以詩名:作者格式存儲
poet_writer={'鋤禾':'李紳','九月九日憶山東兄弟':'王維','詠鵝':'駱賓王','秋浦歌':'李白','竹石':'鄭燮','石灰吟':'于謙','示兒':'陸游',"靜夜思":"李白"}
writers=set(list(poet_writer.values()))
poet=list(poet_writer.keys())
p=random.choice(poet)
print(p,'的作者是誰')
#顯示4個選項
#四個選項中有一個是正確答案,另外三個選項需要從備選集合中任選三個
right_answer=poet_writer[p]
writers.remove(right_answer)
#從中選擇三個
mul=list(writers)
random.shuffle(mul)
items=mul[0:3]
items.append(right_answer)
random.shuffle(items)
head=["A","B","C","D"]
new_dic=dict(zip(head,items))
for key,value in new_dic.items():
??? print(key,value)
answer=input('enter your answer:')
if new_dic[answer]==poet_writer[p]:
??? print("correct!")
else:
??? print("wrong")

5.1

#【訓練5.1】 給定一個正整數(shù),編寫程序計算有多少對質(zhì)數(shù)的和等于輸入的這個正整數(shù),并輸出結(jié)果。輸入值小于1000。
def is_Prime(number):
??? if number == 1:???????????? # 1不是質(zhì)數(shù)
??????? return 0
??? for i in range(2,number):? # 把2到number之間的數(shù)全部做一遍取余,看是否能整除
??????? if number % i == 0:
??????????? return 0
??? return 1???????????????? # 是質(zhì)數(shù)
num=eval(input())
lst = [x for x in range(1,num+1) if is_Prime(x)]
# 計算滿足要求的組的個數(shù)
count = 0
for i in lst:
??? if num - i in lst and num - i <= i:
??????? count += 1
??????? print(i,"+",num-i,"=",num)
print(count)

5.2

#【訓練5.2】 編寫函數(shù)change(str),其功能是對參數(shù)str進行大小寫互換,即將字符串中的大寫字母轉(zhuǎn)為小寫字母,小寫字母轉(zhuǎn)換為大寫字母。
def change(f):
??? f1 = eval(f[:-2])
??? f2=0
??? if 'lb'==f[-2:]:
??????? f2=0.453*f1
??? elif 'kg'==f[-2:]:
??????? f2=2.204*f1
??? return f2
x=input("enter :")
y=change(x)
print(y)

5.3

#【訓練5.3】編寫函數(shù)digit(num,k),其功能是:求整數(shù)num的第k位的值。
def digit(num,k):
??? for i in range(k):
??????? knum=num%10
??????? num=int(num/10)
??? return knum
print(digit(598234,4))

5.4

#【訓練5.4】編寫遞歸函數(shù)fibo(n),其功能是:求第n個斐波那契數(shù)列的值,進而實現(xiàn)將前20個斐波那契數(shù)列輸出。
def fibo(n):
??? if n <= 2:
??????? ''' 數(shù)列前兩個數(shù)都是1 '''
??????? v = 1
??????? return v? # 返回結(jié)果,并結(jié)束函數(shù)
??? v = fibo(n - 1) + fibo(n - 2)? # 由數(shù)據(jù)的規(guī)律可知,第三個數(shù)的結(jié)果都是前兩個數(shù)之和,所以進行遞歸疊加
??? return v? # 返回結(jié)果,并結(jié)束函數(shù)
for i in range(1,21):
??? print(i,":",fibo(i))

5.5

#【訓練5.5】編寫一個函數(shù)cacluate, 可以接收任意多個數(shù), 返回的是一個元組。元組的第一個值為所有參數(shù)的平均值, 第二個值是小于平均值的個數(shù)。
def calculate(*args):
??? sum=0
??? for i in args:
??????? sum=sum+i
??? ave=sum/len(args)
??? counts=0
??? for i in args:
??????? if i<ave:
??????????? counts=counts+1
??? return ave,counts
ave,counts=calculate(89,20,80,54,67,90,77)
print(ave,counts)

5.6

# 【訓練5.6】模擬輪盤抽獎游戲.輪盤分為三部分: 一等獎, 二等獎和三等獎;輪盤轉(zhuǎn)的時候是隨機的,
# 如果范圍在[0,0.08)之間,代表一等獎,如果范圍在[0.08,0.3)之間,代表2等獎,如果范圍在[0, 1.0)之間,代表3等獎.
import random
rewardDict = {
??? '一等獎': (0, 0.08),
??? '二等獎': (0.08, 0.3),
??? '三等獎': (0.3, 1)
}

def rewardFun():? # 用戶的得獎等級
??? # 生成0~1之間的隨機數(shù)
??? number = random.random()
??? # 該循環(huán)用來判斷隨機轉(zhuǎn)盤是幾等獎
??? for k, v in rewardDict.items():
??????? if v[0] <= number < v[1]:
??????????? return k

res = rewardFun()
print(res)

5.7

# 【訓練5.7】有一段英文: What is a function in Python? In Python, function is a group of related statements that perform
# a specific task. Functions help break our program into smaller and modular chunks. As our program grows larger and
# larger, functions make it more organized and manageable. Furthermore, it avoids repetition and makes code reusable.
# A function definition consists of following components. Keyword def marks the start of function header.
# A function name to uniquely identify it. Function naming follows the same rules of writing identifiers in Python.
# Parameters (arguments) through which we pass values to a function. They are optional. A colon (:) to mark the end of
# function header. Optional documentation string (docstring) to describe what the function does. One or more valid Python
# statements that make up the function body. Statements must have same indentation level (usually 4 spaces). An optional
# return statement to return a value from the function.
# 任務(wù): 1.請統(tǒng)計出該段英文有多少個單詞,每個單詞出現(xiàn)的次數(shù)。
# 2.如果不算of、a 、the這三個單詞,給出出現(xiàn)頻率最高的10個單詞,并給出他們出現(xiàn)的次數(shù)。
def getText(text):
??? text=text.lower()
??? for ch in ",.;?-:\'":
??????? text=text.replace(ch," ")
??? return text
def wordCount(text,topn):
??? words=text.split()
??? counts={}
??? for word in words:
??????? counts[word]=counts.get(word,0)+1
??? excludes={"of","a","the"}
??? for word in excludes:
??????? del(counts[word])
??? items=list(counts.items())
??? items.sort(key=lambda x:x[1],reverse=True)
??? return items[:topn]
text='''What is a function in Python? In Python, function is a group of related statements that perform
a specific task. Functions help break our program into smaller and modular chunks. As our program grows larger and
larger, functions make it more organized and manageable. Furthermore, it avoids repetition and makes code reusable.
A function definition consists of following components. Keyword def marks the start of function header.
A function name to uniquely identify it. Function naming follows the same rules of writing identifiers in Python.
Parameters (arguments) through which we pass values to a function. They are optional. A colon (:) to mark the end of
function header. Optional documentation string (docstring) to describe what the function does. One or more valid Python
statements that make up the function body. Statements must have same indentation level (usually 4 spaces). An optional
return statement to return a value from the function.'''
text=getText(text)
for word,count in wordCount(text,20):
??? print(word,"?????? ",count)

5.8

# 【訓練5.8】英鎊(lb)和千克(kg)的轉(zhuǎn)換。利用函數(shù)實現(xiàn)英鎊(lb)和千克(kg)的轉(zhuǎn)換。用戶可以輸入千克,也可以輸入英鎊,
# 函數(shù)將根據(jù)用戶的輸入轉(zhuǎn)換成英鎊或者千克。
def change(f):
??? f1 = eval(f[:-2])
??? f2=0
??? if 'lb'==f[-2:-1]:
??????? f2=0.453*f1
??? elif 'kg'==f[-2:-1]:
??????? f2=2.204*f1
??? return f2
x=input("enter :")
y=change(x)
print(y)

5.9

#【訓練5.9】一個數(shù)如果恰好等于它的真因子之和,這個數(shù)就稱為“完數(shù)”。例如6=1+2+3.編程找出1000以內(nèi)的所有完數(shù)。
def allFactor(n):
??? if n == 0: return [0]
??? if n == 1: return [1]
??? rlist = []
??? for i in range(1,n+1):
??????? if n%i == 0:
??????????? rlist.append(i)
??? rlist=rlist[:-1]
??? return rlist
def display(n,s_list):
??? print(n,"=",end='')
??? for i in range(len(s_list)-1):
??????? print(s_list[i],"+",end='')
??? print(s_list[i])
for n in range(2,1000):
??? rlist=allFactor(n)
??? if(n==sum(rlist)):
??????? display(n,rlist)

5.10

#【訓練5.10】利用遞歸函數(shù)調(diào)用方式,將用戶所輸入的字符串,以相反順序打印出來。
string = input("請輸入一個字符串 :")
def f(x):
??? if x == -1: #當變量的長度是-1時,返回
??????? return ''
??? else:?????? #否則返回字符串的位置向后移1位,直到變量的長度為-1
??????? return string[x] + f(x-1)
print (f(len(string)- 1))

test.

def func1(x,y):
??? x1=x
??? y1=y
??? print("in func1, x1:{},y1:{},x:{},y:{}".format(x1,y1,x,y))
??? func2()#在函數(shù)func1中調(diào)用函數(shù)func2
def func2():
??? # x1=10
??? # y1=20
??? print("in func2, x1:{},y1:{}".format(x1,y1))
func1(2,3)

6.1

?class Date(object):
??? def __init__(self,year,month,day):
??????? self.__year=year
??????? self.__month=month
??????? self.__day=day
??? def getYear(self):
??????? return self.__year
??? def getMonth(self):
??????? return self.__month
??? def getDay(self):
??????? return self.__day
??? def setYear(self,year):
??????? self.__year=year
??? def setMonth(self, month):
??????? self.__month = month
??? def setDay(self, day):
??????? self.__day = day
??? def show(self):
??????? print(self.__year,"/",self.__month,"/",self.__day)

#測試代碼
if __name__ == '__main__':
??? d=Date(2020,12,18)
??? d.show()
??? d.setYear(2021)
??? d.setMonth(1)
??? d.setDay(1)
??? d.show()

6.2

?#導入訓練6-1中定義的Date類
import sys
import os
sys.path.append(os.getcwd())
from Date import Date
#定義CCPM類
class CCPM(object):
??? def __init__(self,name,sex,id,joinday,partyfund):
??????? self.__name=name
??????? self.__sex=sex
??????? self.__joinday=joinday
??????? self.__id=id
??????? self.__partyfund=partyfund
??? def getName(self):
??????? return self.__name
??? def getSex(self):
??????? return self.__sex
??? def getId(self):
??????? return self.__id
??? def getJoinday(self):
??????? return self.__joinday
??? def getPartyFund(self):
??????? return self.__partyfund
??? def setName(self,name):
??????? self.__name=name
??? def setSex(self,sex):
??????? self.__sex=sex
??? def setId(self,id):
??????? self.__id=id
??? def setJoinday(self,day):
??????? self.joinday=day
??? def setPartyfund(self,partyfund):
??????? self.__partyfund=partyfund
??? def show(self):
??????? print("姓名:"+self.__name)
??????? print("性別:"+self.__sex)
??????? print("身份證號:"+self.__id)
??????? print("入黨時間:",end=" ")
??????? self.__joinday.show()
??????? print("黨費/月:",self.__partyfund,"元")



#測試代碼
if __name__ == '__main__':
??? joinday=Date(2020,12,18)
??? ccpm=CCPM("zhang","男","320311199001011111",joinday,100)
??? ccpm.show()

6.3

?#Person類的定義
class Person(object):
??? def __init__(self,name,sex,age):
??????? self.__name=name
??????? self.__sex=sex
??????? self.__age=age
??? def setName(self,name):
??????? self.__name=name
??? def setSex(self,sex):
??????? self.__sex=sex
??? def setAge(self,age):
??????? self.__age=age
??? def getName(self):
??????? return self.__name
??? def getSex(self):
??????? return self.__sex
??? def getAge(self):
??????? return self.__age
??? def display(self):
??????? print("姓名:",self.__name)
??????? print("性別:",self.__sex)
??????? print("年齡:",self.__age)

#Student 類的定義
class Student(Person):
??? def __init__(self,name,sex,age,number,score):
??????? super(Student,self).__init__(name,sex,age)
??????? self.__number=number
??????? self.__score=score
??? def setNumber(self,number):
??????? self.__number=number
??? def setScore(self,score):
??????? self.__score=score
??? def getNumber(self):
??????? return self.__number
??? def getScore(self):
??????? return self.__score
??? def display(self):
??????? super(Student,self).display()
??????? print("學號:",self.__number)
??????? print("成績:",self.__score)
#Teacher類的定義
class? Teacher(Person):
??? def __init__(self,name,sex,age,department,number,salary):
??????? super(Teacher,self).__init__(name,sex,age)
??????? self.__department=department
??????? self.__number=number
??????? self.__salary=salary
??? def setDepartment(self,department):
??????? self.__department=department
??? def setNumber(self,number):
??????? self.__number=number
??? def setSalary(self,salary):
??????? self.__salary=salary
??? def getDepartmen(self):
??????? return self.__department
??? def getNumber(self):
??????? return self.__number
??? def getSalary(self):
??????? return self.__salary
??? def display(self):
??????? super(Teacher,self).display()
??????? print("學院:",self.__department)
??????? print("工號:",self.__number)
??????? print("工資:",self.__salary)

s=Student("張三","男",18,"20900001",90)
s.display()
t=Teacher("周老師","女",45,"計算機學院","199098",8000)
print()
t.display()

6.4

?# 請你建立一個分數(shù)類Rational,
# 使之具有如下功能:
# 能防止分母為“0”,
# 當分數(shù)中不是最簡形式時,進行約分以及避免分母為負數(shù)。
# 用重載運算符完成分數(shù)的加、減、乘、除等四則運算和大小的比較運算。
class Rational(object):
??? def __init__(self,numerator,denominator):
??????? self.num=numerator? #分子
??????? if denominator==0:
??????????? print("分母不能為0")
??????? else:
??????????? self.deno=denominator
??????? self.reduceFraction()

??? def Gcd(self):
??????? a=self.num
??????? b=self.deno
??????? s = a * b
??????? while a % b != 0:
??????????? a, b = b, (a % b)
??????? return b

??? def reduceFraction(self):
??????? gcd=self.Gcd()
??????? self.num //= gcd
??????? self.deno//= gcd
??? #加法運算
??? def __add__(self, other):? # 兩個分數(shù)相加,返回一個新的分數(shù)
??????? return Rational(self.num*other.deno+other.num*self.deno,self.deno*other.deno)
??? #減法運算
??? def __sub__(self,other):
??????? return Rational(self.num * other.deno- other.num * self.deno, self.deno* other.deno)
??? #乘法運算
??? def __mul__(self,other):
??????? return Rational(self.num*other.num,self.deno*other.deno)
??? #除法運算
??? def __truediv__(self,other):
??????? return Rational(self.num * other.deno, self.deno * other.num)
??? #小于運算
??? def __lt__(self,other):
??????? deno=self.deno*other.deno
??????? num1=self.num*other.deno
??????? num2=other.num*self.deno
??????? if num1<num2:
??????????? return True
??????? else:
??????????? return False
??? # 小于等于運算
??? def __l__(self, other):
??????? deno = self.deno * other.deno
??????? num1 = self.num * other.deno
??????? num2 = other.num * self.deno
??????? if num1 <= num2:
??????????? return True
??????? else:
??????????? return False
??? #大于運算
??? def __t__(self,other):
??????? deno=self.deno*other.deno
??????? num1=self.num*other.deno
??????? num2=other.num*self.deno
??????? if num1>num2:
??????????? return True
??????? else:
??????????? return False

??? #大于等于運算
??? def __ge__(self,other):
??????? deno=self.deno*other.deno
??????? num1=self.num*other.deno
??????? num2=other.num*self.deno
??????? if num1>=num2:
??????????? return True
??????? else:
??????????? return False



??? def __str__(self):
??????? if self.deno!=1:
??????????? return "{}/{}".format(self.num, self.deno)
??????? else:
??????????? return "{}".format(self.num)



#測試代碼
r1=Rational(3,4)
r2=Rational(1,2)
print('{}+{}={}'.format(r1,r2,r1+r2))
print('{}-{}={}'.format(r1,r2,r1-r2))
print('{}*{}={}'.format(r1,r2,r1*r2))
print('{}/{}={}'.format(r1,r2,r1/r2))
print('{}<{}={}'.format(r1,r2,r1<r2))
print('{}<={}={}'.format(r1,r2,r1<=r2))
print('{}>{}={}'.format(r1,r2,r1>r2))
print('{}>={}={}'.format(r1,r2,r1>=r2))

6.5

?from math import sqrt
from math import pi
class Triangle(object):
??? def __init__(self,a,b,c):
??????? if(a+b>c and a+c>b and b+c>a):
??????????? self.a=a
??????????? self.b=b
??????????? self.c=c
??????? else:
??????????? print("{},{},{}不能構(gòu)成三角形!".format(a,b,c))
??? def area(self):
??????? s=(self.a+self.b+self.c)/2
??????? return sqrt(s*(s-self.a)*(s-self.b)*(s-self.c))
??? def circumference(self):
??????? return self.a+self.b+self.c


class Square(object):
??? def __init__(self,side):
??????? self.side=side
??? def area(self):
??????? return self.side*self.side
??? def circumference(self):
??????? return 4*self.side

class Circle(object):
??? def __init__(self, radius):
??????? self.radius= radius

??? def area(self):
??????? return pi*self.radius * self.radius

??? def circumference(self):
??????? return 2*pi*self.radius

#測試代碼
tri=Triangle(1,1,1)
print("%.2f"%tri.area())
print(tri.circumference())
s=Square(1)
print("%.2f"%s.area())
print(s.circumference())
c=Circle(1)
print("%.2f"%c.area())
print("%.2f"%c.circumference())

7.1

?count = 0
for i in range(1000, 10000):
??? fourth = i // 1000? # 千位
??? third = i % 1000 // 100? # 百位
??? second = i % 100 // 10? # 十位
??? first = i % 10? # 個位
??? if fourth == first and third == second:
??????? count = count + 1
??????? with open("palindrome.txt", "a") as f:
??????????? f.write(str(i)+'\t')
??????????? if count % 10 == 0:
??????????????? f.write('\n')

7.1(2)

?count = 0
f=open("palindrome.txt", "a")
for i in range(1000, 10000):
??? fourth = i // 1000? # 千位
??? third = i % 1000 // 100? # 百位
??? second = i % 100 // 10? # 十位
??? first = i % 10? # 個位
??? if fourth == first and third == second:
??????? count = count + 1
??????? f.write(str(i)+'\t')
??????? if count % 10 == 0:
??????????? f.write('\n')
f.close()

7.2

?#從鍵盤輸入n個學生信息,包括學號、姓名、成績。用struct方式保存到文件students.bin中。
#然后再將所有學生信息讀取出來,并按照成績從高到低排序,輸出到屏幕上。
import struct
def writeToBinFile(filename):
??? n=int(input("請輸入學生個數(shù):"))
??? #輸入n個學生的信息,并寫入到二進制文件student.bin
??? f = open(filename, "wb")
??? for i in range(1,n+1):
??????? y=input("請輸入第"+str(i)+"個學生的學號 姓名 成績 (以空格分隔)\n").split()
??????? w=list(map(str,y))
??????? id=w[0]
??????? name = w[1]
??????? score=float(w[2])
??????? #編碼
??????? id=id.encode()
??????? name=name.encode()
??????? student = struct.pack('4s10sf', id, name, score)? # 按格式'4s10sf',將id,name,score打包成字節(jié)串
??????? f.write(student)? # 把字節(jié)串student寫入二進制文件
??? print("學生信息已經(jīng)寫入二進制文件!")
??? f.close()
??? return n

#從二進制文件filename中讀取數(shù)據(jù)n個數(shù)據(jù)
def readFromBinFile(filename,n):
??? #從二進制文件student.bin中讀取出學生信息,并顯示在屏幕上
??? f=open(filename,"rb")
??? list=[]

??? for i in range(0,n):
??????? size=struct.calcsize('4s10sf')
??????? stu=f.read(size)?? #讀取size個字節(jié)
??????? stu=struct.unpack('4s10sf',stu)??? #解析字節(jié)串,解析的結(jié)果是一個元組
??????? #print("從二進制文件讀取的數(shù)據(jù)為:",stu)?? #打印元組,可以看出id,name保持為字節(jié)串
??????? id,name,score=stu????????????????? #對元組進行解包,賦給對應(yīng)的變量id name score
??????? #用decode方法對id、name、score進行解碼,將字節(jié)串轉(zhuǎn)換成字符串
??????? id = id.decode().strip('\x00')
??????? name = name.decode().strip('\x00')
??????? list1=[id,name,score]
??????? list.insert(i,list1)
??? f.close()
??? return list


#測試代碼
if __name__ == '__main__':
??? student=[]
??? n=writeToBinFile("student.bin")
??? student=readFromBinFile("student.bin",n)
??? print("學生的信息為:")
??? for i in student:
??????? print(i)
??? s= sorted(student,key = lambda x:x[2],reverse=True)
??? print("學生信息按成績從高到低排序后的結(jié)果為:")
??? for i in s:
??????? print(i)

7.3

?import csv
#將記錄寫入csv文件
def writeToCsvFile(filename):
??? with open(filename,'w',newline="") as f:
??????? writer=csv.writer(f)
??????? writer.writerow(['黨組織','平均參與度','人均積分'])
??????? n=int(input("要存儲的記錄個數(shù):"))
??????? for i in range(1,n+1):
??????????? y = input("請輸入第" + str(i) + "個記錄的黨組織 平均參與度 人均積分 (以空格分隔)\n").split()
??????????? w = list(map(str, y))
??????????? 黨組織 = w[0]
??????????? 平均參與度 = w[1]
??????????? 人均積分 = int(w[2])
??????????? writer.writerow([黨組織,平均參與度,人均積分])

#從csv文件中讀取數(shù)據(jù)并進行查詢,返回查詢結(jié)果
def? queryFromCsvFile(filename,黨組織):
??? list=[]
??? with open(filename,'r') as f:
??????? reader =csv.reader(f)
??????? for row in reader:
??????????? if row[0]==黨組織:
??????????????? list.append(row[0])
??????????????? list.append(row[1])
??????????????? list.append(row[2])
??? return list

#測試代碼
if __name__ == '__main__':
??? filename="學習強國學習平臺使用情況.csv"
??? 黨組織="商學院黨總支"
??? #writeToCsvFile(filename)
??? list=queryFromCsvFile(filename,黨組織)
??? if len(list):
??????? print(list[0]+"的平均參與度 人均積分")
??????? print(list[1]," ",int(list[2]))
??? else:
??????? print("沒有查詢到"+黨組織+"的數(shù)據(jù)!")

7.4

?#使用tarfile模塊實現(xiàn)將指定目錄下的文件壓縮和解壓縮。
import tarfile
import os
def tar_data(srcpath, targetpath):
??? tfobj = tarfile.TarFile(targetpath, "w")
??? filelist = os.listdir(srcpath)
??? for filename in filelist:
??????? fullpath = os.path.join(srcpath, filename)
??????? tfobj.add(fullpath)
??? tfobj.close()

def untar_data(srcpath, targetpath):
??? if tarfile.is_tarfile(srcpath):
??????? tfobj = tarfile.TarFile(srcpath)
??????? tfobj.extractall(targetpath)
??????? tfobj.close()
??????? print("文件已經(jīng)解壓完畢!")
??? else:
??????? print("不是壓縮文件!")

if __name__ == '__main__':
??? tar_data("f:\\電子發(fā)票","f:\\電子發(fā)票.tar")
??? untar_data("f:\\電子發(fā)票.tar", "d:\\")

8.1

?try:
??? a=int(input("請輸入整數(shù)a:"))
??? b=int(input("請輸入整數(shù)b:"))
??? print(a+b)
except(ValueError) as e:
??? print(e)
else:
??? print("計算正確!")

8.2

?try:
??? a=int(input("請輸入整數(shù)a:"))
??? b=int(input("請輸入整數(shù)b:"))
??? print(a+c)
except(NameError) as e:
??? print(e)

8.3

# 創(chuàng)建一個自定義異常類TriangleError類,
# 如果三角形的三條邊不滿足任意兩邊之和大于第三邊,
# 則拋出TriangleError類的對象。
import math
class TriangleError(Exception):
??? def __init__(self, msg):
??????? self.msg = msg

??? def __str__(self):
??????? return self.msg
print("請輸入三角形的三條邊:")
a = eval(input())
b = eval(input())
c = eval(input())
try:
??? if a + b <= c or a + c <= b or b + c <= a:
??????? raise TriangleError("注意:三角形任意兩邊之和必須大于第三邊")
??? s = (a + b + c) / 2
??? area = math.sqrt(s * (s - a) * (s - b) * (s - c))
??? print(area)
except TriangleError as e:
??? print(e)



over!?。?!



三月十一日的評論 (共 條)

分享到微博請遵守國家法律
红安县| 惠东县| 达日县| 邵武市| 连平县| 甘孜县| 崇义县| 武夷山市| 民县| 昌黎县| 湘西| 昭觉县| 新津县| 临澧县| 婺源县| 承德县| 紫阳县| 湘阴县| 互助| 白水县| 龙川县| 裕民县| 四川省| 晋中市| 罗平县| 新郑市| 吉木乃县| 康定县| 吴堡县| 家居| 富源县| 石河子市| 鄂尔多斯市| 肥东县| 阿拉尔市| 左云县| 资兴市| 融水| 鸡泽县| 平山县| 绩溪县|