作业四按要求编写程序(任选三题)
1.编写一个从 1 加到 end 的当型循环。变量 end 的值由键盘输入。假如输入end
的值为6,则代码输出的结果应该是21,也就是1+2+3+4+5+6 的结果(不要用
sum作为变量,因为它是内置函数)。
1. a = input()
2. b=int(a)
3. total = 0
4. for i in range(b+1):
5. total = i+total
6. print(total)
2、从键盘输入一个整数,判断该数字能否被 2 和 3 同时整除,能否被 2 整除,能否被 3 整除,不能被 2 和 3 整除。输出相应信息。
a = input()
b=int(a)
if b%2==0 and b%3==0:
print('该数字能被 2 和 3 同时整除')
elif b%2==0:
print('该数字能被 2 整除')
elif b%3==0:
print('该数字能被 3 整除')
else :
print('该数字不能被 2 和 3 整除')
3、 一个数如果恰好等于它的因子之和,这个数就称为“完数”,例如, 6 的因子为1、2、3,而6=1+2+3,因此6 是“完数”。编程序找出 1000 之内的所有完数,并按下面的格式输出其因子:6its factors are 1, 2, 3
for iin range(1001): if i==0: continue s = 0 for j in range(i): if j==0: continue ifi%j==0: s=s+j if s==i: print('{} its factors are '.format(i),end='') for j inrange(i): if j == 0: continue if i % j == 0: print(j,end=' ') print('\n')
4、打印出所有的“水仙花数”,所谓“水仙花数”是指一个 3 位数,其各位数字立方和等于该数本身。例如, 153 是一个水仙花数,因为 153=13+53+33。
for i in range(1000):
if i<100:
continue
s = 0
a = int(i//100)
b = int(i//10%10)
c = int(i%10)
s = a**3+b**3+c**3
if s == i:
print("{}是水仙花数".format(i))
5.假设x,y是(-1,1)中的两个随机数字(服从正态分布):
(1)当x²+y²>1时,返回x,y的值
(2)创建一个列表,其中每个元素对应为的值, 且 a=x²+y².
import random
import math
def randomXY():
x= random.uniform(-1,1)
y= random.uniform(-1,1)
if(x*x+y*y>1):
return randomXY()
else:
return (x,y)
def ans():
list = []
for i in range(0,100):
xy = randomXY()
x = xy[0]
y = xy[1]
a = x*x+y*y
temp = math.sqtr(x*math.log(a,math.e))
list.append(temp)
return list
# print(ans())
for x in ans():
print(x)
作业五
第四题选作
一、 输出 1~100 之间不能被 7 整除的数,每行输出 10 个数字,要求应用字符串格式化方法(任何一种均可) 美化输出格式。 输出效果为:
j=0
for i in range(101): #循环
if i>0 and i % 7 == 0: #如果能整除7,则再执行循环
continue
elif i>0: #如果大于0并且不能被7整除,输出;
print("{:3d}".format(i),end=' ')
j += 1 #j用来控制每行输出是否是10个
if j % 10 == 0:
print('\n')
j = 0
else:
continue;
二、创建文本文件FarewellCambridge.txt。内容为:
Very quietly I take my leave
As quietly as I came here;
Quietly I wave good-bye
To the rosy clouds in the western sky.
The golden willows by the riverside
Are young brides in the setting sun;
Their reflections on the shimmering waves
Always linger in the depth of my heart.
The floating heart growing in the sludge
Sways leisurely under the water;
In the gentle waves of Cambridge
I would be a water plant!
That pool under the shade of elm trees
Holds not water but the rainbow from thesky;
Shattered to pieces among the duckweeds
Is the sediment of a rainbow-like dream?
To seek a dream? Just to pole a boatupstream
To where the green grass is more verdant;
Or to have the boat fully loaded withstarlight
And sing aloud in the splendor ofstarlight.
But I cannot sing aloud
Quietness is my farewell music;
Even summer insects heap silence for me
Silent is Cambridge tonight!
并用写字板查看(注意:直接将上述诗句拷贝到程序中,不需要自己再次录入)。
file =open('C:/Users/uestc/Desktop/hanzhengqiang.txt','w')
#在桌面新建一个韩正强.txt文本文档,并且是写的模式
#在文本中写入文字:
file.write('''Very quietly I take my leave
As quietly as I came here;
Quietly I wave good-bye
To the rosy clouds in the western sky.
The golden willows by the riverside
Are young brides in the setting sun;
Their reflections on the shimmering waves
Always linger in the depth of my heart.
The floating heart growing in the sludge
Sways leisurely under the water;
In the gentle waves of Cambridge
I would be a water plant!
That pool under the shade of elm trees
Holds not water but the rainbow from the sky;
Shattered to pieces among the duckweeds
Is the sediment of a rainbow-like dream?
To seek a dream? Just to pole a boat upstream
To where the green grass is more verdant;
Or to have the boat fully loaded with starlight
And sing aloud in the splendor of starlight.
But I cannot sing aloud
Quietness is my farewell music;
Even summer insects heap silence for me
Silent is Cambridge tonight!''')
对于上一题建立的文本文件,使用read()读文件,并在屏幕上显示。
1. file = open('C:/Users/uestc/Desktop/hanzhengqiang.txt','r')
2. #在桌面打开一个韩正强.txt文本文档,并且是读的模式
3. #读取文件,并且输出:
4. s=file.read()
5. print(s)
根据给定的文本文件words.txt(可将该文件存放在任意目录,注意打开文件时要加入正确的路径)编写函数loadWords(),words.txt包含若干小写英文单词。要求:
1) 读入该文件,统计并输出单词的个数
2) 返回单词列表(注意:指返回单词列表即可,不要在屏幕上显示)
import re
#统计单词个数:
def count_words(file_path):
with open(file_path) as file:
text = file.read()
words = re.findall(r'[a-zA-Z]+', text)
count = len(words)
return count
print(count_words('C:/Users/uestc/Desktop/words.txt'))
作业七
一、编写函数devide(x, y),x为被除数,y为除数。要求考虑异常情况的处理。
1、被零除时,输出"division by zero! ";
2、类型不一致时,强制转换为整数再调用本函数;
3、 若没有上述异常则输出计算结果。
def test(password, earning, age):
#assert 1<0
assert password[0] not in ['0','1','2','3','4','5','6','7','8','9']
assert int(earning)>=0 and int(earning)<=20000
assert int(age)>=18 and int(age)<=70
return True
print(test('as','11','30'))
二、 编写函数test(password,earning, age)用于检测输入错误。要求输入密码password第一个符号不能是数字,工资earnings的范围是0—20000,工作年龄的范围是18—70。使用断言来实现检查,若三项检查都通过则返回True。
def test(password, earning, age):
#assert 1<0
assert password[0] not in['0','1','2','3','4','5','6','7','8','9']
assert int(earning)>=0 andint(earning)<=20000
assert int(age)>=18 and int(age)<=70
return True
三、使用tkinter库完成下列程序
1、编程实现如下GUI(只显示,没有回调函数)
import tkinter
root =tkinter.Tk()
root.title('tk')
theLabel=tkinter.Label(root,text='Welcome to Python Tkinter')
theLabel.pack()
root.geometry('500x300+300+300')
button = tkinter.Button(root,text='Click Me')
button.pack()
root.mainloop()
2、 编程响应用户事件。“OK”按钮前景为红色,按下“OK”按钮显示"OK button is clicked",”Cancel“按钮背景为黄色,按下”Cancel“按钮显示"Cancel button is clicked"。
import tkinter
def ok_on_click():
print('OK button is clicked')
def cancel_on_click():
print('Cancel button is clicked')
root = tkinter.Tk()
root.title('zy')
label = tkinter.Label(root)
buttonok = tkinter.Button(root,text='OK',fg='red')
buttonok['command']=ok_on_click
label.pack()
buttonok.pack()
root.geometry('500x300+300+300')
buttoncancel =tkinter.Button(root,text='Cancel',bg='yellow')
buttoncancel['command']=cancel_on_click
label.pack()
buttoncancel.pack()
root.mainloop()
四、 使用Turtle库完成下列程序
1、绘制一个红色的五角星图形,如图所示。
import turtle as tk
tk.fillcolor("red")
tk.begin_fill()
while True:
tk.forward(200)
tk.right(144)
if abs(tk.pos()) < 1:
break
tk.end_fill()
input()
2、螺旋线绘制(每一圈是四个线段组成,一共绘制100个线段)。绘制一个螺旋线的图形,如图所示。
1. importturtle
2. importtime
3.turtle.pensize(1)
4. for x in range(100):
5. turtle.forward(x)
6. turtle.left(90)
7. time.sleep(100)
作业十
一、编写一个程序,以2位数字,X,Y作为输入,生成一个二维数组。数组的第i行和第j列中的元素值应该是i*j。
注意:i= 0,1 . .,X - 1; j = 0,1,-Y-1。
例子假设程序有以下输入:3、5
则程序输出为:[[0,0,0,0,0],[0,1,2,3,4],[0,2,4,6,8]]
提示:注意:如果要为问题提供输入数据,应该假设它是一个控制台输入,以逗号分隔。
print('请输入两个数字:')
input_str =input()
dimensions=[int(x) for x in input_str.split(',')]
rowNum=dimensions[0]
colNum=dimensions[1]
multilist = [[0 for col in range(colNum)] for row in range(rowNum)]
for row in range(rowNum):
for col in range(colNum):
multilist[row][col]= row*col
print (multilist)