




版權(quán)說(shuō)明:本文檔由用戶(hù)提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
第一章Python語(yǔ)言及其編程環(huán)境1.下載并安裝Python3.版,檢查系統(tǒng)變量Path中的安裝路徑,體驗(yàn)并編寫(xiě)一個(gè)簡(jiǎn)單的Python程序。答案:要檢查系統(tǒng)變量Path中的安裝路徑,你可以使用以下Python代碼:```pythonimportospath_str=os.environ.get('Path')install_dirs=path_str.split(';')fordirininstall_dirs:print(dir)```這段代碼首先導(dǎo)入了`os`模塊,然后使用`os.environ.get('Path')`獲取系統(tǒng)變量Path的值。接下來(lái),它將路徑字符串分割成一個(gè)列表,并使用循環(huán)遍歷打印每個(gè)安裝路徑。你可以將以上代碼保存為一個(gè).py文件,然后在命令行或終端中運(yùn)行它,即可查看系統(tǒng)變量Path中的安裝路徑。2.下載并安裝一種第三方E,并逐漸熟悉使用它。答案:略。第二章Python的基本語(yǔ)法一、選擇題1-5B、B、B、BD、BD6-10C、BA、C、D、AC11.D二、填空題1.#。2.\。3.整數(shù)(int)、浮點(diǎn)數(shù)(float)、布爾值(bool)、復(fù)數(shù)(complex)。4.n/2==0.第三章Python程序的基本流程控制1.編寫(xiě)程序,從鍵盤(pán)輸入兩點(diǎn)的坐標(biāo)(xl,y1)和(x2,y2),計(jì)算并輸出兩點(diǎn)之間的距離。答案:importmathdefcalculate_distance(x1,y1,x2,y2):distance=math.sqrt((x2-x1)**2+(y2-y1)**2)returndistancedefmain():try:x1=float(input("Enterthex-coordinateofthefirstpoint(x1):"))y1=float(input("Enterthey-coordinateofthefirstpoint(y1):"))x2=float(input("Enterthex-coordinateofthesecondpoint(x2):"))y2=float(input("Enterthey-coordinateofthesecondpoint(y2):"))distance=calculate_distance(x1,y1,x2,y2)print("Thedistancebetweenthetwopointsis:",distance)exceptValueError:print("Invalidinput.Pleaseentervalidnumericalvaluesforcoordinates.")if__name__=="__main__":main()2.編寫(xiě)程序,從鍵盤(pán)輸入年份值和月份值,輸出該年當(dāng)月的日歷(調(diào)用calendar模塊中的month()函數(shù))。答案:importcalendardefmain():try:year=int(input("Entertheyear:"))month=int(input("Enterthemonth(1-12):"))ifmonth<1ormonth>12:print("Invalidmonth.Pleaseenteravaluebetween1and12.")returncal=calendar.month(year,month)print("\nCalendarfortheyear{}andmonth{}:".format(year,month))print(cal)exceptValueError:print("Invalidinput.Pleaseentervalidnumericalvaluesforyearandmonth.")if__name__=="__main__":main()3.編寫(xiě)程序,產(chǎn)生兩個(gè)10以?xún)?nèi)的隨機(jī)整數(shù),以第1個(gè)隨機(jī)整數(shù)為半徑、第2個(gè)隨機(jī)整數(shù)為高,計(jì)算并輸出圓錐體的體積。答案:importrandomimportmathdefcalculate_cone_volume(radius,height):volume=(1/3)*math.pi*radius**2*heightreturnvolumedefmain():try:radius=random.randint(1,10)height=random.randint(1,10)print("Randomlygeneratedradius:",radius)print("Randomlygeneratedheight:",height)volume=calculate_cone_volume(radius,height)print("Thevolumeoftheconeis:",volume)exceptValueError:print("Anerroroccurredwhilegeneratingrandomnumbers.")if__name__=="__main__":main()4.編寫(xiě)程序,從鍵盤(pán)輸入一個(gè)年份值,判斷該年是否為國(guó)年并輸出判斷結(jié)果。(提示:若該年份值能被4整除且不能被100整除或者該份值能被400整除,則該是年,否則不是。)答案:defis_leap_year(year):if(year%4==0andyear%100!=0)or(year%400==0):returnTrueelse:returnFalsedefmain():try:year=int(input("Enterayear:"))ifis_leap_year(year):print(f"{year}isaleapyear.")else:print(f"{year}isnotaleapyear.")exceptValueError:print("Invalidinput.Pleaseenteravalidyear.")if__name__=="__main__":main()5.編寫(xiě)程序,從鍵盤(pán)輸入三個(gè)數(shù),計(jì)算并輸出三個(gè)數(shù)中最大的數(shù)。答案:deffind_max(a,b,c):returnmax(a,b,c)defmain():try:num1=float(input("Enterthefirstnumber:"))num2=float(input("Enterthesecondnumber:"))num3=float(input("Enterthethirdnumber:"))max_num=find_max(num1,num2,num3)print("Themaximumnumberis:",max_num)exceptValueError:print("Invalidinput.Pleaseentervalidnumericalvalues.")if__name__=="__main__":main()6.編寫(xiě)程序,從鍵盤(pán)輸入三個(gè)數(shù),實(shí)現(xiàn)三個(gè)數(shù)從小到大排序并輸出結(jié)果。答案:defsort_numbers(num1,num2,num3):#使用列表的sort()方法對(duì)三個(gè)數(shù)進(jìn)行排序sorted_numbers=[num1,num2,num3]sorted_numbers.sort()returnsorted_numbersdefmain():try:num1=float(input("Enterthefirstnumber:"))num2=float(input("Enterthesecondnumber:"))num3=float(input("Enterthethirdnumber:"))sorted_numbers=sort_numbers(num1,num2,num3)print("Numberssortedinascendingorder:",sorted_numbers)exceptValueError:print("Invalidinput.Pleaseentervalidnumericalvalues.")if__name__=="__main__":main()7.編寫(xiě)程序,從鍵盤(pán)輸入a、b、c的值,計(jì)算一元二次方程x+bx+c-0的根,并根據(jù)62-4ac的值大于0等于0及小于0三種情分別進(jìn)行討論。答案:importmathdefquadratic_equation_roots(a,b,c):D=b**2-4*a*cifD>0:x1=(-b+math.sqrt(D))/(2*a)x2=(-b-math.sqrt(D))/(2*a)return"Twodistinctrealroots:x1={:.2f},x2={:.2f}".format(x1,x2)elifD==0:x=-b/(2*a)return"Twoequalrealroots:x={:.2f}".format(x)else:real_part=-b/(2*a)imaginary_part=math.sqrt(abs(D))/(2*a)return"Twocomplexroots:x1={:.2f}+{:.2f}i,x2={:.2f}-{:.2f}i".format(real_part,imaginary_part,real_part,imaginary_part)defmain():try:a=float(input("Enterthevalueofa:"))b=float(input("Enterthevalueofb:"))c=float(input("Enterthevalueofc:"))result=quadratic_equation_roots(a,b,c)print("Rootsofthequadraticequation:")print(result)exceptValueError:print("Invalidinput.Pleaseentervalidnumericalvalues.")if__name__=="__main__":main()8.編寫(xiě)程序,從鍵盤(pán)輸入一個(gè)字符,如果是大寫(xiě)英文字母則將其轉(zhuǎn)換為小寫(xiě)英文字母,如果是小寫(xiě)英文字母則將其轉(zhuǎn)換為大寫(xiě)英文字母,其他字符原樣輸出。答案:defmain():try:char=input("Enteracharacter:")ifchar.isupper():converted_char=char.lower()elifchar.islower():converted_char=char.upper()else:converted_char=charprint("Convertedcharacter:",converted_char)exceptKeyboardInterrupt:print("\nProgramterminatedbytheuser.")if__name__=="__main__":main()9.編寫(xiě)程序,從鍵盤(pán)輸入數(shù)字n,通過(guò)循環(huán)結(jié)構(gòu)計(jì)算從1到n的乘積。答案:defcalculate_factorial_with_for(n):factorial=1foriinrange(1,n+1):factorial*=ireturnfactorialdefmain():try:n=int(input("Enteranumber(n):"))ifn<0:print("Pleaseenteranon-negativeinteger.")returnresult=calculate_factorial_with_for(n)print(f"Thefactorialof{n}is:{result}")exceptValueError:print("Invalidinput.Pleaseenteravalidinteger.")if__name__=="__main__":main()10.編寫(xiě)程序,通過(guò)循環(huán)結(jié)構(gòu)計(jì)算全部的水仙花數(shù)。水仙花數(shù)是一個(gè)三位數(shù),該數(shù)正好等于組成該二位數(shù)的各位數(shù)字的立方和。例如,13+5+33-153。答案:defis_armstrong_number(num):num_str=str(num)num_digits=len(num_str)total=0fordigit_charinnum_str:digit=int(digit_char)total+=digit**num_digitsreturntotal==numdefmain():armstrong_numbers=[]fornuminrange(100,1000):ifis_armstrong_number(num):armstrong_numbers.append(num)print("AllArmstrongnumbersbetween100and999are:")print(armstrong_numbers)if__name__=="__main__":main()11.編寫(xiě)程序,通過(guò)循環(huán)結(jié)構(gòu)計(jì)算并輸出滿(mǎn)足條件的正方體的體積:正方體棱長(zhǎng)從1到10,依次計(jì)算體積,當(dāng)體積大于100時(shí)停止輸出。答案:defcalculate_cube_volume(side_length):volume=side_length**3returnvolumedefmain():max_volume=100forside_lengthinrange(1,11):volume=calculate_cube_volume(side_length)ifvolume>max_volume:breakprint(f"Cubewithsidelength{side_length}:Volume={volume}")if__name__=="__main__":main()12.編寫(xiě)程序,從鍵盤(pán)輸入一個(gè)整數(shù)并判斷該數(shù)的類(lèi)別:其因數(shù)之和等于數(shù)字本身的數(shù)稱(chēng)為完全數(shù),比數(shù)字本身大的數(shù)稱(chēng)為豐沛數(shù),比數(shù)字本身小的數(shù)稱(chēng)為不足數(shù)。答案:defget_factors_sum(num):factors_sum=0foriinrange(1,num):ifnum%i==0:factors_sum+=ireturnfactors_sumdefmain():try:num=int(input("Enteraninteger:"))ifnum<=0:print("Pleaseenterapositiveinteger.")returnfactors_sum=get_factors_sum(num)iffactors_sum==num:print(f"{num}isaperfectnumber.")eliffactors_sum>num:print(f"{num}isanabundantnumber.")else:print(f"{num}isadeficientnumber.")exceptValueError:print("Invalidinput.Pleaseenteravalidinteger.")if__name__=="__main__":main()13.編寫(xiě)程序,使用雙重循環(huán)結(jié)構(gòu)輸出如圖3-18所示的運(yùn)行結(jié)果。defprint_diamond(rows):foriinrange(1,rows//2+2):spaces=rows//2+1-istars=2*i-1print(""*spaces+"*"*stars)foriinrange(rows//2,0,-1):spaces=rows//2+1-istars=2*i-1print(""*spaces+"*"*stars)defmain():rows=7print_diamond(rows)if__name__=="__main__":main()14.編寫(xiě)程序,生成一個(gè)0~100之間的隨機(jī)數(shù),然后讓用戶(hù)嘗試猜測(cè)這個(gè)數(shù)字。程序給出猜測(cè)方向(更大或更小)的提示,用戶(hù)繼續(xù)進(jìn)行猜測(cè),直到用戶(hù)猜測(cè)成功或輸入一個(gè)0~100以外的數(shù)字后退出游戲。答案:importrandomdefmain():secret_number=random.randint(0,100)whileTrue:try:guess=int(input("Guessthenumber(0-100):"))ifguess<0orguess>100:print("Invalidinput.Pleaseenteranumberbetween0and100.")elifguess<secret_number:print("Toolow.Tryagain.")elifguess>secret_number:print("Toohigh.Tryagain.")else:print("Congratulations!Youguessedthecorrectnumber:",secret_number)breakexceptValueError:print("Invalidinput.Pleaseenteravalidinteger.")if__name__=="__main__":main()15.編寫(xiě)程序,計(jì)算Fibonacci數(shù)列的前20項(xiàng)(Fibonacci數(shù)列的特點(diǎn)是,第1、2項(xiàng)的值都為1,從第3項(xiàng)開(kāi)始,每項(xiàng)都是前兩項(xiàng)之和)。答案:deffibonacci_sequence(n):sequence=[1,1]#初始的前兩項(xiàng)為1foriinrange(2,n):next_number=sequence[i-1]+sequence[i-2]sequence.append(next_number)returnsequencedefmain():n=20fibonacci_seq=fibonacci_sequence(n)print("Fibonaccisequence(first20terms):",fibonacci_seq)if__name__=="__main__":main()16.編寫(xiě)程序,從鍵盤(pán)輸入兩個(gè)正整數(shù),計(jì)算兩個(gè)數(shù)的最大圖3-18第13題的運(yùn)行結(jié)果公約數(shù)和最小公倍數(shù)。答案:defcalculate_gcd(a,b):whileb!=0:a,b=b,a%breturnadefcalculate_lcm(a,b):return(a*b)//calculate_gcd(a,b)defmain():try:num1=int(input("Enterthefirstpositiveinteger:"))num2=int(input("Enterthesecondpositiveinteger:"))ifnum1<=0ornum2<=0:print("Pleaseenterpositiveintegers.")returngcd=calculate_gcd(num1,num2)lcm=calculate_lcm(num1,num2)print("GreatestCommonDivisor(GCD):",gcd)print("LeastCommonMultiple(LCM):",lcm)exceptValueError:print("Invalidinput.Pleaseentervalidpositiveintegers.")if__name__=="__main__":main()17.編寫(xiě)程序,判斷一個(gè)整數(shù)是否為素?cái)?shù)(判斷整數(shù)x是否為素?cái)?shù),最簡(jiǎn)單的方法就是用2~x-1之間的所有整數(shù)逐一去除x,若x能被其中任意一個(gè)數(shù)整除,則x就不是素?cái)?shù),否則為素?cái)?shù))。答案:defis_prime(number):ifnumber<=1:returnFalseforiinrange(2,number):ifnumber%i==0:returnFalsereturnTruedefmain():try:num=int(input("Enteraninteger:"))ifis_prime(num):print(f"{num}isaprimenumber.")else:print(f"{num}isnotaprimenumber.")exceptValueError:print("Invalidinput.Pleaseenteravalidinteger.")if__name__=="__main__":main()18.編寫(xiě)程序,實(shí)現(xiàn)一個(gè)循環(huán)5次的計(jì)算小游戲,每次隨機(jī)產(chǎn)生兩個(gè)100以?xún)?nèi)的數(shù)字,讓用戶(hù)計(jì)算兩個(gè)數(shù)字之和并輸入結(jié)果,如果計(jì)算結(jié)果正確則加一分,如果計(jì)算結(jié)果錯(cuò)誤則不加分。如果正確率大于或等于80%,則闖關(guān)成功。答案:importrandomdefgenerate_random_numbers():num1=random.randint(1,100)num2=random.randint(1,100)returnnum1,num2defmain():correct_count=0total_attempts=5for_inrange(total_attempts):num1,num2=generate_random_numbers()correct_answer=num1+num2try:user_answer=int(input(f"Whatisthesumof{num1}and{num2}?"))ifuser_answer==correct_answer:print("Correct!")correct_count+=1else:print(f"Wrong!Thecorrectansweris{correct_answer}.")exceptValueError:print("Invalidinput.Pleaseenteravalidinteger.")accuracy=(correct_count/total_attempts)*100print(f"\nYougot{correct_count}outof{total_attempts}correctanswers.")print(f"Youraccuracyis{accuracy:.2f}%.")ifaccuracy>=80:print("Congratulations!Youpassedthechallenge.")else:print("Sorry,youneedahigheraccuracytopassthechallenge.")if__name__=="__main__":main()19.編寫(xiě)程序,從鍵盤(pán)輸入一個(gè)姓名(可能為2個(gè)字、3個(gè)字或4個(gè)字),將該姓名的第2個(gè)漢字修改為*號(hào)。如果索引出錯(cuò),則進(jìn)行異常處理并提示索引錯(cuò)誤。答案:defmodify_second_character(name):try:iflen(name)<2orlen(name)>4:raiseIndexError("Nameshouldhave2,3,or4characters.")modified_name=name[:1]+"*"+name[2:]returnmodified_nameexceptIndexErrorase:print("Error:",e)returnNonedefmain():name=input("Enteraname(2,3,or4characters):")modified_name=modify_second_character(name)ifmodified_nameisnotNone:print("Modifiedname:",modified_name)if__name__=="__main__":main()20.編寫(xiě)程序,從鍵盤(pán)輸入用戶(hù)名和密碼,判斷該用戶(hù)名和密碼是否均在文件information.txt中。若在,則提示用戶(hù)名和密碼正確,否則提示用戶(hù)名和密碼錯(cuò)誤。如果文件打開(kāi)失敗,則進(jìn)行異常處理并提示文件打開(kāi)失敗,否則關(guān)閉文件。無(wú)論文件打開(kāi)成功與否,最后均會(huì)打印出輸入的用戶(hù)名和密碼。答案:首先,確保在運(yùn)行程序之前,創(chuàng)建一個(gè)名為"information.txt"的文本文件,并在其中按照以下格式存儲(chǔ)用戶(hù)名和密碼,每行一個(gè)記錄:username1password1username2password2...defcheck_credentials(username,password,file_path):try:withopen(file_path,"r")asfile:forlineinfile:stored_username,stored_password=line.strip().split()ifusername==stored_usernameandpassword==stored_password:returnTrueexceptFileNotFoundError:print("Filenotfound.Unabletocheckcredentials.")exceptExceptionase:print("Anerroroccurred:",e)returnFalsedefmain():file_path="information.txt"username=input("Enteryourusername:")password=input("Enteryourpassword:")ifcheck_credentials(username,password,file_path):print("Usernameandpasswordarecorrect.")else:print("Usernameand/orpasswordareincorrect.")print("Inputusername:",username)print("Inputpassword:",password)if__name__=="__main__":main()第四章Python的組合數(shù)據(jù)類(lèi)型一、單選題1-5 D、B、B、B、A6-10 B、C、A、D、B11-15 B、A、B、D、C二、程序填空題(1)range(len(s))(2)in(3)d+chr(p+ord('a'))(4)print三、程序設(shè)計(jì)題答案:defcalculate_luhn_checksum(card_number):digits=[int(digit)fordigitinstr(card_number)][::-1]doubled_digits=[2*digitifindex%2==1elsedigitforindex,digitinenumerate(digits)]summed_digits=[digitifdigit<10elsedigit-9fordigitindoubled_digits]total_sum=sum(summed_digits)checksum=(10-(total_sum%10))%10returnchecksumdefis_valid_card_number(card_number):try:card_number=int(card_number)checksum=calculate_luhn_checksum(card_number//10)returnchecksum==card_number%10exceptValueError:returnFalsedefmain():card_number=input("Enterthecreditcardnumber:")ifis_valid_card_number(card_number):print("Thecreditcardnumberisvalid.")else:print("Thecreditcardnumberisinvalid.")if__name__=="__main__":main()第五章文件與基于文本文件的數(shù)據(jù)分析一、選擇題1-4 ABDA二、程序設(shè)計(jì)題1.統(tǒng)計(jì)flel.txt文件中包含的字符個(gè)數(shù)和行數(shù)。答案:defcount_characters_and_lines(filename):character_count=0line_count=0try:withopen(filename,'r')asfile:forlineinfile:character_count+=len(line)line_count+=1exceptFileNotFoundError:print(f"File'{filename}'notfound.")exceptExceptionase:print("Anerroroccurred:",str(e))returncharacter_count,line_countdefmain():filename="file.txt"#替換成實(shí)際的文件名character_count,line_count=count_characters_and_lines(filename)print(f"Charactercount:{character_count}")print(f"Linecount:{line_count}")if__name__=="__main__":main()2.將flel.txt文件中的每行按降序方式輸出到fle2.txt文件中。答案:defwrite_lines_in_desc_order(input_file,output_file):try:withopen(input_file,'r')asf:lines=f.readlines()#對(duì)每行進(jìn)行降序排序sorted_lines=sorted(lines,reverse=True)withopen(output_file,'w')asf:f.writelines(sorted_lines)print("Lineswrittentofle2.txtindescendingorder.")exceptFileNotFoundError:print(f"File'{input_file}'notfound.")exceptExceptionase:print("Anerroroccurred:",str(e))defmain():input_file="flel.txt"#輸入文件名output_file="fle2.txt"#輸出文件名write_lines_in_desc_order(input_file,output_file)if__name__=="__main__":main()3.scorestxt文件中存放著某班學(xué)生的計(jì)算機(jī)課成績(jī),包含學(xué)號(hào)、平時(shí)成績(jī)、期末成績(jī)二列。請(qǐng)根據(jù)平時(shí)成績(jī)占40%、期末成績(jī)占60%的比例計(jì)算總評(píng)成績(jī),并按學(xué)號(hào)、總評(píng)成績(jī)兩列寫(xiě)入另一個(gè)文件scoredtxt中。同時(shí)在屏幕上輸出學(xué)生總?cè)藬?shù),按總評(píng)成績(jī)計(jì)算90分以上、80~89分、70~79分、6069分、60分以下各成績(jī)區(qū)間的人數(shù)和班級(jí)總平均分取兩位小數(shù))。答案:defcalculate_final_score(hw_score,final_score):return0.4*hw_score+0.6*final_scoredefmain():scores_file="scorestxt"#輸入文件名output_file="scoredtxt"#輸出文件名total_students=0total_score=0count_90_above=0count_80_89=0count_70_79=0count_60_69=0count_below_60=0withopen(scores_file,'r')asf:lines=f.readlines()withopen(output_file,'w')asf_out:f_out.write("學(xué)號(hào)總評(píng)成績(jī)\n")forlineinlines:student_data=line.strip().split()iflen(student_data)==3:student_id=student_data[0]hw_score=float(student_data[1])final_score=float(student_data[2])final_score=calculate_final_score(hw_score,final_score)f_out.write(f"{student_id}{final_score:.2f}\n")total_students+=1total_score+=final_scoreiffinal_score>=90:count_90_above+=1elif80<=final_score<90:count_80_89+=1elif70<=final_score<80:count_70_79+=1elif60<=final_score<70:count_60_69+=1else:count_below_60+=1class_average=total_score/total_studentsprint("學(xué)生總?cè)藬?shù):",total_students)print("90分以上的人數(shù):",count_90_above)print("80-89分的人數(shù):",count_80_89)print("70-79分的人數(shù):",count_70_79)print("60-69分的人數(shù):",count_60_69)print("60分以下的人數(shù):",count_below_60)print("班級(jí)總平均分:",f"{class_average:.2f}")if__name__=="__main__":main()4.從網(wǎng)上獲取黨的二十大報(bào)告,并利用第三方庫(kù)ieba進(jìn)行分詞,統(tǒng)計(jì)詞頻,將出現(xiàn)100次以上的詞用第三方庫(kù)wordcloud可視化為詞云,如圖5-11所示。答案:略。第六章函數(shù)一、選擇題1—5 DCDAD6.A二、程序設(shè)計(jì)題1.略2.(1)random.uniform(0.01,rest/2)(2)total(3)i+1(4)money3.(1)len(passwd)(2)return(3)break(4)st第七章面向?qū)ο蟮某绦蛟O(shè)計(jì)與Python生態(tài)選擇題1-5 CCBBB6-8 CDC第八章圖形華界面設(shè)計(jì)一、選擇題1-5 DDAAB6-8 AAA二、程序設(shè)計(jì)題1.加法計(jì)算程序。將操作數(shù)填入輸入框后,單擊“加法”按鈕將算式和結(jié)果填入下方的結(jié)果文本框中。單擊“清空”按鈕將清空輸入框和結(jié)果文本框。效果如圖8-25所示。答:略。2.四則運(yùn)算程序。將操作數(shù)填入輸入框后,單擊單選按鈕選擇運(yùn)算方式,并將算式和結(jié)果顯示在下方標(biāo)簽上。效果如圖8-26所示。答:略。3.參照例46設(shè)計(jì)圖形化用戶(hù)界面,實(shí)現(xiàn)輸入18位身份證號(hào)碼,能夠辨別其是否為合法號(hào)碼。若為合法號(hào)碼,則進(jìn)一步判斷性別。效果如圖8-27所示。答:略。4.售票程序。在窗體上放置提示標(biāo)簽、單選按鈕組、輸入框、命令按鈕和多行文本框根據(jù)所選不同景點(diǎn)的名稱(chēng)、門(mén)票價(jià)格和購(gòu)票張數(shù)計(jì)算總票價(jià)。景點(diǎn)“東方明珠”、“野生動(dòng)物園”和“科技館”的門(mén)票價(jià)格分別為160元、130元和60元。在輸入框中輸入購(gòu)票張數(shù),單擊“計(jì)算”按鈕,將在多行文本框中顯示景點(diǎn)名稱(chēng)、購(gòu)票張數(shù)及票價(jià)。計(jì)算票價(jià)的標(biāo)準(zhǔn):?若購(gòu)票張數(shù)大于或等于50張,則票價(jià)為原價(jià)的80%;?若購(gòu)票張數(shù)大于或等于20張,則票價(jià)為原價(jià)的95%;?其他情況維持原價(jià)。效果如圖8-28所示。答:略。第九章圖形繪制與數(shù)據(jù)可視化1.答:importnumpyasnpimportmatplotlib.pyplotasplt#創(chuàng)建400x400像素的畫(huà)布fig,ax=plt.subplots(figsize=(4,4))#設(shè)置坐標(biāo)軸放大倍數(shù)x_scale=80y_scale=35#繪制坐標(biāo)軸ax.axhline(y=0,color='red',linestyle='-',linewidth=1)ax.axvline(x=0,color='red',linestyle='-',linewidth=1)#設(shè)置坐標(biāo)軸范圍ax.set_xlim(-x_scale*1.7,x_scale*1.7)ax.set_ylim(-y_scale,y_scale)#在區(qū)間[-1.7,1.7]上生成步長(zhǎng)為0.02的x值x_values=np.arange(-1.7,1.7,0.02)#定義函數(shù)f(x)deff(x):return3*x-3*x+4*np.sin(x)#繪制放射線ax.plot(x_values,f(x_values),color='black',label='QuadrantI')ax.plot(x_values,-f(x_values),color='red',label='QuadrantII')ax.plot(x_values,-f(x_values)+4,color='green',label='QuadrantIV')ax.plot(x_values,f(x_values)-4,color='blue',label='QuadrantIII')#添加圖例ax.legend()#顯示圖形plt.show()2.答:importnumpyasnpimportmatplotlib.pyplotasplt#創(chuàng)建400x400像素的畫(huà)布fig,ax=plt.subplots(figsize=(4,4))#設(shè)置坐標(biāo)軸放大倍數(shù)x_scale=80y_scale=35#繪制坐標(biāo)軸ax.axhline(y=0,color='red',linestyle='-',linewidth=1)ax.axvline(x=0,color='red',linestyle='-',linewidth=1)#設(shè)置坐標(biāo)軸范圍ax.set_xlim(-x_scale*1.7,x_scale*1.7)ax.set_ylim(-y_scale,y_scale)#在區(qū)間[-1.7,1.7]上生成步長(zhǎng)為0.02的x值x_values=np.arange(-1.7,1.7,0.02)#定義函數(shù)f(x)deff(x):return3*x-3*x+4*np.sin(x)#繪制函數(shù)圖形ax.plot(x_values,f(x_values),color='red')ax.plot(x_values,-f(x_values)+20,color='blue')#顯示圖形plt.show()3.答:importnumpyasnpimportmatplotlib.pyplotasplt#創(chuàng)建600x600像素的畫(huà)布fig,ax=plt.subplots(figsize=(6,6))#繪制坐標(biāo)軸ax.axhline(y=0,color='red',linestyle='-',linewidth=1)ax.axvline(x=0,color='red',linestyle='-',linewidth=1)#參數(shù)aa=80#定義函數(shù)x(t)和y(t)defx(t):returna*(2*np.sin(t)-np.sin(2*t))defy(t):returna*(2*np.cos(t)-np.cos(2*t))#在區(qū)間[-2*pi,2*pi]上生成步長(zhǎng)為0.01的t值t_values=np.arange(-2*np.pi,2*np.pi,0.01)#繪制函數(shù)圖形ax.plot(x(t_values),y(t_values),color='blue')#設(shè)置坐標(biāo)軸范圍ax.set_xlim(-a*3,a*3)ax.set_ylim(-a*3,a*3)#顯示圖形plt.show()4.答:importnumpyasnpimportmatplotlib.pyplotasplt#創(chuàng)建600x600像素的畫(huà)布fig,ax=plt.subplots(figsize=(6,6))#設(shè)置畫(huà)布半寬和半高w=300h=300#繪制坐標(biāo)軸ax.axhline(y=0,color='red',linestyle='-',linewidth=1)ax.axvline(x=0,color='red',linestyle='-',linewidth=1)#設(shè)置坐標(biāo)軸范圍ax.set_xlim(-w,w)ax.set_ylim(-h,h)#在區(qū)間[0,2π]上生成步長(zhǎng)為0.01的t值t_values=np.arange(0,2*np.pi,0.01)#定義x和y的計(jì)算公式x=(w/4)*np.cos(2*t_values)*np.sin(t_values)y=(h/4)*np.cos(2*t_values)*np.cos(t_values)#繪制花形狀ax.plot(x,y-10,color='red',label='QuadrantII')ax.plot(x,-y+10,color='green',label='QuadrantIIIandIV')#添加圖例ax.legend()#顯示圖形plt.show()5.答:importnumpyasnpimportmatplotlib.pyplotasplt#創(chuàng)建600x600像素的畫(huà)布fig,ax=plt.subplots(figsize=(6,6))#設(shè)置畫(huà)布半寬和半高w=300h=300#繪制坐標(biāo)軸ax.axhline(y=0,color='red',linestyle='-',linewidth=1)ax.axvline(x=0,color='red',linestyle='-',linewidth=1)#設(shè)置坐標(biāo)軸范圍ax.set_xlim(-w,w)ax.set_ylim(-h,h)#在區(qū)間[0,25]上生成步長(zhǎng)為0.01的t值t_values=np.arange(0,25,0.01)#定義x和y的計(jì)算公式x=w/32*(np.cos(t_values)+t_values*np.sin(t_values))y=h/32*(np.sin(t_values)-t_values*np.cos(t_values))#繪制螺線ax.plot(x,y,color='blue')#顯示圖形plt.show()第十章正則表達(dá)式與簡(jiǎn)單爬蟲(chóng)1.根據(jù)下列字符串的構(gòu)成規(guī)律寫(xiě)出正則表達(dá)式,并嘗試?yán)胷e庫(kù)中的有關(guān)方法實(shí)現(xiàn)對(duì)測(cè)試字符串的匹配、搜索、切分、分組和替換操作。(1)E-mail地址。答案:importreemail_pattern=r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"test_string="example@"ifre.match(email_pattern,test_string):print("匹配成功:",test_string)else:print("匹配失?。?,test_string)(2)IPv4地址。答案:importreipv4_pattern=r"^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$"test_string=""ifre.match(ipv4_pattern,test_string):print("匹配成功:",test_string)else:print("匹配失?。?,test_string)(3)國(guó)內(nèi)手機(jī)號(hào)碼。答案:importrephone_pattern=r"^1[3-9]\d{9}$"test_string=ifre.match(phone_pattern,test_string):print("匹配成功:",test_string)else:print("匹配失?。?,test_string)(4)國(guó)內(nèi)電話號(hào)碼(0開(kāi)頭的34位區(qū)號(hào)-5~8位號(hào)碼)。答案:importretelephone_pattern=r"^0\d{2,3}-\d{5,8}$"test_string=ifre.match(telephone_pattern,test_string):print("匹配成功:",test_string)else:print("匹配失?。?,test_string)(5)18位身份證號(hào)碼(不考慮大小月、閏月和校驗(yàn)規(guī)則)。答案:importreid_card_pattern=r"^\d{17}[\dXx]$"test_string=ifre.match(id_card_pattern,test_string):print("匹配成功:",test_string)else:print("匹配失敗:",test_string)2.創(chuàng)建簡(jiǎn)單爬蟲(chóng)程序,實(shí)現(xiàn)對(duì)靜態(tài)網(wǎng)頁(yè)(例如,本校的院系主頁(yè)、昵圖網(wǎng)、知乎日?qǐng)?bào)、淘寶網(wǎng)等)中新聞標(biāo)題、JPG、PNG、GIF圖片或MP3等素材的自動(dòng)下載。簡(jiǎn)單的示例來(lái)實(shí)現(xiàn)對(duì)網(wǎng)頁(yè)中的圖片下載。我們將使用Python的requests庫(kù)進(jìn)行網(wǎng)頁(yè)請(qǐng)求,BeautifulSoup庫(kù)進(jìn)行頁(yè)面解析,并使用urllib庫(kù)進(jìn)行文件下載。首先,確保已安裝所需的庫(kù)。您可以使用以下命令來(lái)安裝它們:pipinstallrequestsbeautifulsoup4接下來(lái),我們將實(shí)現(xiàn)一個(gè)簡(jiǎn)單的圖片下載器。importosimportrequestsfrombs4importBeautifulSoupfromurllib.parseimporturljoindefdownload_images(url,save_folder):response=requests.get(url)soup=BeautifulSoup(response.text,'html.parser')ifnotos.path.exists(save_folder):os.makedirs(save_folder)forimg_taginsoup.find_all('img'):img_url=img_tag.get('src')ifimg_url:img_url=urljoin(url,img_url)filename=os.path.join(save_folder,os.path.basename(img_url))download_file(img_url,filename)defdownload_file(url,save_path):withrequests.get(url,stream=True)asresponse:response.raise_for_status()withopen(save_path,'wb')asf:forchunkinresponse.iter_content(chunk_size=8192):f.write(chunk)if__name__=="__main__":url=""#替換為您要爬取的網(wǎng)頁(yè)URLsave_folder="images"#圖片保存目錄,可以根據(jù)需要修改download_images(url,save_folder)第十一章數(shù)據(jù)庫(kù)操作1.答:importsqlite3#創(chuàng)建數(shù)據(jù)庫(kù)文件Businessdbconn=sqlite3.connect('Businessdb.db')cursor=conn.cursor()#創(chuàng)建Info表cursor.execute('''CREATETABLEIFNOTEXISTSInfo(product_idTEXT,product_nameTEXT,unit_priceINTEGER)''')#創(chuàng)建Customer表cursor.execute('''CREATETABLEIFNOTEXISTSCustomer(customer_idTEXT,customer_nameTEXT,product_idTEXT)''')#輸出Info表的所有內(nèi)容defshow_info_table():cursor.execute('SELECT*FROMInfo')info_records=cursor.fetchall()forrecordininfo_records:print(f'ProductID:{record[0]},ProductName:{record[1]},UnitPrice:{record[2]}')#添加商品購(gòu)買(mǎi)信息到Customer表defadd_customer_record(customer_id,customer_name,product_id):cursor.execute('INSERTINTOCustomerVALUES(?,?,?)',(customer_id,customer_name,product_id))mit()print("Customerrecordaddedsuccessfully.")#查詢(xún)顧客編號(hào)的消費(fèi)金額defshow_customer_total_amount(customer_id):cursor.execute('SELECTcustomer_id,SUM(unit_price)AStotal_amountFROMCustomer''JOINInfoONCduct_id=Iduct_id''WHEREcustomer_id=?GROUPBYcustomer_id',(customer_id,))result=cursor.fetchone()ifresult:print(f'CustomerID:{result[0]},TotalAmount:{result[1]}')else:print("CustomerIDnotfound.")#示例數(shù)據(jù):添加一些商品信息cursor.executemany('INSERTINTOInfoVALUES(?,?,?)',[('130207','ProductA',100),('130208','ProductB',200),('130209','ProductC',150)])mit()#輸出Info表的所有內(nèi)容show_info_table()#添加商品購(gòu)買(mǎi)信息whileTrue:customer_id=input("請(qǐng)輸入顧客編號(hào)(輸入0退出程序):")ifcustomer_id=='0':breakcustomer_name=input("請(qǐng)輸入顧客姓名:")product_id=input("請(qǐng)輸入購(gòu)買(mǎi)商品編號(hào):")add_customer_record(customer_id,customer_name,product_id)#查詢(xún)顧客編號(hào)的消費(fèi)金額customer_id_input=input("請(qǐng)輸入顧客編號(hào)查詢(xún)消費(fèi)金額:")show_customer_total_amount(customer_id_input)#關(guān)閉數(shù)據(jù)庫(kù)連接conn.close()2.答:importsqlite3#創(chuàng)建數(shù)據(jù)庫(kù)文件flmdbconn=sqlite3.connect('flmdb.db')cursor=conn.cursor()#創(chuàng)建“熱映電影”表cursor.execute('''CREATETABLEIFNOTEXISTShot_movies(movie_nameTEXT,movie_typeTEXT,movie_regionTEXT)''')#創(chuàng)建“排片”表cursor.execute('''CREATETABLEIFNOTEXISTSschedules(movie_nameTEXT,theaterTEXT,ticket_priceINTEGER)''')#輸出“熱映電影”表的所有內(nèi)容defshow_hot_movies():cursor.execute('SEL
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶(hù)所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶(hù)上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶(hù)上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶(hù)因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 被告拒絕和解協(xié)議書(shū)
- 門(mén)店管理運(yùn)營(yíng)協(xié)議書(shū)
- 出租車(chē)司機(jī)購(gòu)車(chē)協(xié)議書(shū)
- 鄰居建房占地協(xié)議書(shū)
- 運(yùn)輸月結(jié)合同協(xié)議書(shū)
- 酒吧公司保密協(xié)議書(shū)
- 解除房屋轉(zhuǎn)租協(xié)議書(shū)
- 酒店銷(xiāo)售團(tuán)隊(duì)協(xié)議書(shū)
- 黃金現(xiàn)貨買(mǎi)賣(mài)協(xié)議書(shū)
- 車(chē)載空調(diào)安裝協(xié)議書(shū)
- 2024年江西省中考生物·地理合卷試卷真題(含答案)
- 專(zhuān)題12 電功率圖像的四種類(lèi)型(原卷版)-2023-2024學(xué)年九年級(jí)物理全一冊(cè)學(xué)優(yōu)生期中期末復(fù)習(xí)難點(diǎn)題型專(zhuān)項(xiàng)突破(人教版)
- DZ/T 0462.5-2023 礦產(chǎn)資源“三率”指標(biāo)要求 第5部分:金、銀、鈮、鉭、鋰、鋯、鍶、稀土、鍺(正式版)
- 垃圾分類(lèi)臺(tái)賬制度
- (高清版)JTG 3370.1-2018 公路隧道設(shè)計(jì)規(guī)范 第一冊(cè) 土建工程
- 《產(chǎn)生氣體的變化》小學(xué)科學(xué)六年級(jí)下冊(cè)課件
- 團(tuán)隊(duì)境內(nèi)旅游合同2014版
- 二年級(jí)數(shù)學(xué)三位數(shù)加減三位數(shù)計(jì)算題同步作業(yè)練習(xí)題
- 中國(guó)藝術(shù)史智慧樹(shù)知到期末考試答案2024年
- 2024年天津市專(zhuān)業(yè)技術(shù)人員繼續(xù)教育公需課考試題+答案 (四套全)
- 2024年度山西省教育系統(tǒng)后備干部題庫(kù)及答案
評(píng)論
0/150
提交評(píng)論