Python程序设计基础(李东方第3版) 习题及答案汇总 第1-12章 Python语言及其编程环境- 基于第三方库的应用举例_第1页
Python程序设计基础(李东方第3版) 习题及答案汇总 第1-12章 Python语言及其编程环境- 基于第三方库的应用举例_第2页
Python程序设计基础(李东方第3版) 习题及答案汇总 第1-12章 Python语言及其编程环境- 基于第三方库的应用举例_第3页
Python程序设计基础(李东方第3版) 习题及答案汇总 第1-12章 Python语言及其编程环境- 基于第三方库的应用举例_第4页
Python程序设计基础(李东方第3版) 习题及答案汇总 第1-12章 Python语言及其编程环境- 基于第三方库的应用举例_第5页
已阅读5页,还剩51页未读, 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

第一章Python语言及其编程环境1.下载并安装Python3.版,检查系统变量Path中的安装路径,体验并编写一个简单的Python程序。答案:要检查系统变量Path中的安装路径,你可以使用以下Python代码:```pythonimportospath_str=os.environ.get('Path')install_dirs=path_str.split(';')fordirininstall_dirs:print(dir)```这段代码首先导入了`os`模块,然后使用`os.environ.get('Path')`获取系统变量Path的值。接下来,它将路径字符串分割成一个列表,并使用循环遍历打印每个安装路径。你可以将以上代码保存为一个.py文件,然后在命令行或终端中运行它,即可查看系统变量Path中的安装路径。2.下载并安装一种第三方E,并逐渐熟悉使用它。答案:略。第二章Python的基本语法一、选择题1-5B、B、B、BD、BD6-10C、BA、C、D、AC11.D二、填空题1.#。2.\。3.整数(int)、浮点数(float)、布尔值(bool)、复数(complex)。4.n/2==0.第三章Python程序的基本流程控制1.编写程序,从键盘输入两点的坐标(xl,y1)和(x2,y2),计算并输出两点之间的距离。答案: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.编写程序,从键盘输入年份值和月份值,输出该年当月的日历(调用calendar模块中的month()函数)。答案: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.编写程序,产生两个10以内的随机整数,以第1个随机整数为半径、第2个随机整数为高,计算并输出圆锥体的体积。答案: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.编写程序,从键盘输入一个年份值,判断该年是否为国年并输出判断结果。(提示:若该年份值能被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.编写程序,从键盘输入三个数,计算并输出三个数中最大的数。答案: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.编写程序,从键盘输入三个数,实现三个数从小到大排序并输出结果。答案:defsort_numbers(num1,num2,num3):#使用列表的sort()方法对三个数进行排序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.编写程序,从键盘输入a、b、c的值,计算一元二次方程x+bx+c-0的根,并根据62-4ac的值大于0等于0及小于0三种情分别进行讨论。答案: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.编写程序,从键盘输入一个字符,如果是大写英文字母则将其转换为小写英文字母,如果是小写英文字母则将其转换为大写英文字母,其他字符原样输出。答案: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.编写程序,从键盘输入数字n,通过循环结构计算从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.编写程序,通过循环结构计算全部的水仙花数。水仙花数是一个三位数,该数正好等于组成该二位数的各位数字的立方和。例如,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.编写程序,通过循环结构计算并输出满足条件的正方体的体积:正方体棱长从1到10,依次计算体积,当体积大于100时停止输出。答案: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.编写程序,从键盘输入一个整数并判断该数的类别:其因数之和等于数字本身的数称为完全数,比数字本身大的数称为丰沛数,比数字本身小的数称为不足数。答案: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.编写程序,使用双重循环结构输出如图3-18所示的运行结果。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.编写程序,生成一个0~100之间的随机数,然后让用户尝试猜测这个数字。程序给出猜测方向(更大或更小)的提示,用户继续进行猜测,直到用户猜测成功或输入一个0~100以外的数字后退出游戏。答案: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.编写程序,计算Fibonacci数列的前20项(Fibonacci数列的特点是,第1、2项的值都为1,从第3项开始,每项都是前两项之和)。答案:deffibonacci_sequence(n):sequence=[1,1]#初始的前两项为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.编写程序,从键盘输入两个正整数,计算两个数的最大图3-18第13题的运行结果公约数和最小公倍数。答案: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.编写程序,判断一个整数是否为素数(判断整数x是否为素数,最简单的方法就是用2~x-1之间的所有整数逐一去除x,若x能被其中任意一个数整除,则x就不是素数,否则为素数)。答案: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.编写程序,实现一个循环5次的计算小游戏,每次随机产生两个100以内的数字,让用户计算两个数字之和并输入结果,如果计算结果正确则加一分,如果计算结果错误则不加分。如果正确率大于或等于80%,则闯关成功。答案: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.编写程序,从键盘输入一个姓名(可能为2个字、3个字或4个字),将该姓名的第2个汉字修改为*号。如果索引出错,则进行异常处理并提示索引错误。答案: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.编写程序,从键盘输入用户名和密码,判断该用户名和密码是否均在文件information.txt中。若在,则提示用户名和密码正确,否则提示用户名和密码错误。如果文件打开失败,则进行异常处理并提示文件打开失败,否则关闭文件。无论文件打开成功与否,最后均会打印出输入的用户名和密码。答案:首先,确保在运行程序之前,创建一个名为"information.txt"的文本文件,并在其中按照以下格式存储用户名和密码,每行一个记录: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的组合数据类型一、单选题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三、程序设计题答案: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()第五章文件与基于文本文件的数据分析一、选择题1-4 ABDA二、程序设计题1.统计flel.txt文件中包含的字符个数和行数。答案: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"#替换成实际的文件名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()#对每行进行降序排序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文件中存放着某班学生的计算机课成绩,包含学号、平时成绩、期末成绩二列。请根据平时成绩占40%、期末成绩占60%的比例计算总评成绩,并按学号、总评成绩两列写入另一个文件scoredtxt中。同时在屏幕上输出学生总人数,按总评成绩计算90分以上、80~89分、70~79分、6069分、60分以下各成绩区间的人数和班级总平均分取两位小数)。答案: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("学号总评成绩\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("学生总人数:",total_students)print("90分以上的人数:",count_90_above)print("80-89分的人数:",count_80_89)print("70-79分的人数:",count_70_79)print("60-69分的人数:",count_60_69)print("60分以下的人数:",count_below_60)print("班级总平均分:",f"{class_average:.2f}")if__name__=="__main__":main()4.从网上获取党的二十大报告,并利用第三方库ieba进行分词,统计词频,将出现100次以上的词用第三方库wordcloud可视化为词云,如图5-11所示。答案:略。第六章函数一、选择题1—5 DCDAD6.A二、程序设计题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第七章面向对象的程序设计与Python生态选择题1-5 CCBBB6-8 CDC第八章图形华界面设计一、选择题1-5 DDAAB6-8 AAA二、程序设计题1.加法计算程序。将操作数填入输入框后,单击“加法”按钮将算式和结果填入下方的结果文本框中。单击“清空”按钮将清空输入框和结果文本框。效果如图8-25所示。答:略。2.四则运算程序。将操作数填入输入框后,单击单选按钮选择运算方式,并将算式和结果显示在下方标签上。效果如图8-26所示。答:略。3.参照例46设计图形化用户界面,实现输入18位身份证号码,能够辨别其是否为合法号码。若为合法号码,则进一步判断性别。效果如图8-27所示。答:略。4.售票程序。在窗体上放置提示标签、单选按钮组、输入框、命令按钮和多行文本框根据所选不同景点的名称、门票价格和购票张数计算总票价。景点“东方明珠”、“野生动物园”和“科技馆”的门票价格分别为160元、130元和60元。在输入框中输入购票张数,单击“计算”按钮,将在多行文本框中显示景点名称、购票张数及票价。计算票价的标准:•若购票张数大于或等于50张,则票价为原价的80%;•若购票张数大于或等于20张,则票价为原价的95%;•其他情况维持原价。效果如图8-28所示。答:略。第九章图形绘制与数据可视化1.答:importnumpyasnpimportmatplotlib.pyplotasplt#创建400x400像素的画布fig,ax=plt.subplots(figsize=(4,4))#设置坐标轴放大倍数x_scale=80y_scale=35#绘制坐标轴ax.axhline(y=0,color='red',linestyle='-',linewidth=1)ax.axvline(x=0,color='red',linestyle='-',linewidth=1)#设置坐标轴范围ax.set_xlim(-x_scale*1.7,x_scale*1.7)ax.set_ylim(-y_scale,y_scale)#在区间[-1.7,1.7]上生成步长为0.02的x值x_values=np.arange(-1.7,1.7,0.02)#定义函数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#创建400x400像素的画布fig,ax=plt.subplots(figsize=(4,4))#设置坐标轴放大倍数x_scale=80y_scale=35#绘制坐标轴ax.axhline(y=0,color='red',linestyle='-',linewidth=1)ax.axvline(x=0,color='red',linestyle='-',linewidth=1)#设置坐标轴范围ax.set_xlim(-x_scale*1.7,x_scale*1.7)ax.set_ylim(-y_scale,y_scale)#在区间[-1.7,1.7]上生成步长为0.02的x值x_values=np.arange(-1.7,1.7,0.02)#定义函数f(x)deff(x):return3*x-3*x+4*np.sin(x)#绘制函数图形ax.plot(x_values,f(x_values),color='red')ax.plot(x_values,-f(x_values)+20,color='blue')#显示图形plt.show()3.答:importnumpyasnpimportmatplotlib.pyplotasplt#创建600x600像素的画布fig,ax=plt.subplots(figsize=(6,6))#绘制坐标轴ax.axhline(y=0,color='red',linestyle='-',linewidth=1)ax.axvline(x=0,color='red',linestyle='-',linewidth=1)#参数aa=80#定义函数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))#在区间[-2*pi,2*pi]上生成步长为0.01的t值t_values=np.arange(-2*np.pi,2*np.pi,0.01)#绘制函数图形ax.plot(x(t_values),y(t_values),color='blue')#设置坐标轴范围ax.set_xlim(-a*3,a*3)ax.set_ylim(-a*3,a*3)#显示图形plt.show()4.答:importnumpyasnpimportmatplotlib.pyplotasplt#创建600x600像素的画布fig,ax=plt.subplots(figsize=(6,6))#设置画布半宽和半高w=300h=300#绘制坐标轴ax.axhline(y=0,color='red',linestyle='-',linewidth=1)ax.axvline(x=0,color='red',linestyle='-',linewidth=1)#设置坐标轴范围ax.set_xlim(-w,w)ax.set_ylim(-h,h)#在区间[0,2π]上生成步长为0.01的t值t_values=np.arange(0,2*np.pi,0.01)#定义x和y的计算公式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#创建600x600像素的画布fig,ax=plt.subplots(figsize=(6,6))#设置画布半宽和半高w=300h=300#绘制坐标轴ax.axhline(y=0,color='red',linestyle='-',linewidth=1)ax.axvline(x=0,color='red',linestyle='-',linewidth=1)#设置坐标轴范围ax.set_xlim(-w,w)ax.set_ylim(-h,h)#在区间[0,25]上生成步长为0.01的t值t_values=np.arange(0,25,0.01)#定义x和y的计算公式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()第十章正则表达式与简单爬虫1.根据下列字符串的构成规律写出正则表达式,并尝试利用re库中的有关方法实现对测试字符串的匹配、搜索、切分、分组和替换操作。(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)国内手机号码。答案:importrephone_pattern=r"^1[3-9]\d{9}$"test_string=ifre.match(phone_pattern,test_string):print("匹配成功:",test_string)else:print("匹配失败:",test_string)(4)国内电话号码(0开头的34位区号-5~8位号码)。答案: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位身份证号码(不考虑大小月、闰月和校验规则)。答案:importreid_card_pattern=r"^\d{17}[\dXx]$"test_string=ifre.match(id_card_pattern,test_string):print("匹配成功:",test_string)else:print("匹配失败:",test_string)2.创建简单爬虫程序,实现对静态网页(例如,本校的院系主页、昵图网、知乎日报、淘宝网等)中新闻标题、JPG、PNG、GIF图片或MP3等素材的自动下载。简单的示例来实现对网页中的图片下载。我们将使用Python的requests库进行网页请求,BeautifulSoup库进行页面解析,并使用urllib库进行文件下载。首先,确保已安装所需的库。您可以使用以下命令来安装它们:pipinstallrequestsbeautifulsoup4接下来,我们将实现一个简单的图片下载器。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=""#替换为您要爬取的网页URLsave_folder="images"#图片保存目录,可以根据需要修改download_images(url,save_folder)第十一章数据库操作1.答:importsqlite3#创建数据库文件Businessdbconn=sqlite3.connect('Businessdb.db')cursor=conn.cursor()#创建Info表cursor.execute('''CREATETABLEIFNOTEXISTSInfo(product_idTEXT,product_nameTEXT,unit_priceINTEGER)''')#创建Customer表cursor.execute('''CREATETABLEIFNOTEXISTSCustomer(customer_idTEXT,customer_nameTEXT,product_idTEXT)''')#输出Info表的所有内容defshow_info_table():cursor.execute('SELECT*FROMInfo')info_records=cursor.fetchall()forrecordininfo_records:print(f'ProductID:{record[0]},ProductName:{record[1]},UnitPrice:{record[2]}')#添加商品购买信息到Customer表defadd_customer_record(customer_id,customer_name,product_id):cursor.execute('INSERTINTOCustomerVALUES(?,?,?)',(customer_id,customer_name,product_id))mit()print("Customerrecordaddedsuccessfully.")#查询顾客编号的消费金额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.")#示例数据:添加一些商品信息cursor.executemany('INSERTINTOInfoVALUES(?,?,?)',[('130207','ProductA',100),('130208','ProductB',200),('130209','ProductC',150)])mit()#输出Info表的所有内容show_info_table()#添加商品购买信息whileTrue:customer_id=input("请输入顾客编号(输入0退出程序):")ifcustomer_id=='0':breakcustomer_name=input("请输入顾客姓名:")product_id=input("请输入购买商品编号:")add_customer_record(customer_id,customer_name,product_id)#查询顾客编号的消费金额customer_id_input=input("请输入顾客编号查询消费金额:")show_customer_total_amount(customer_id_input)#关闭数据库连接conn.close()2.答:importsqlite3#创建数据库文件flmdbconn=sqlite3.connect('flmdb.db')cursor=conn.cursor()#创建“热映电影”表cursor.execute('''CREATETABLEIFNOTEXISTShot_movies(movie_nameTEXT,movie_typeTEXT,movie_regionTEXT)''')#创建“排片”表cursor.execute('''CREATETABLEIFNOTEXISTSschedules(movie_nameTEXT,theaterTEXT,ticket_priceINTEGER)''')#输出“热映电影”表的所有内容defshow_hot_movies():cursor.execute('SEL

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论