作業(yè)四按要求編寫程序(任選三題)
1.編寫一個(gè)從 1 加到 end 的當(dāng)型循環(huán)擅编。變量 end 的值由鍵盤輸入。假如輸入end
的值為6硼补,則代碼輸出的結(jié)果應(yīng)該是21奋刽,也就是1+2+3+4+5+6 的結(jié)果(不要用
sum作為變量,因?yàn)樗莾?nèi)置函數(shù))。
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、從鍵盤輸入一個(gè)整數(shù),判斷該數(shù)字能否被 2 和 3 同時(shí)整除沮趣,能否被 2 整除,能否被 3 整除坷随,不能被 2 和 3 整除房铭。輸出相應(yīng)信息。
a = input()
b=int(a)
if b%2==0 and b%3==0:
??? print('該數(shù)字能被 2 和 3 同時(shí)整除')
elif b%2==0:
??? print('該數(shù)字能被 2 整除')
elif b%3==0:
??? print('該數(shù)字能被 3 整除')
else :
? ? ?print('該數(shù)字不能被 2 和 3 整除')
3温眉、 一個(gè)數(shù)如果恰好等于它的因子之和缸匪,這個(gè)數(shù)就稱為“完數(shù)”,例如类溢, 6 的因子為1凌蔬、2、3闯冷,而6=1+2+3砂心,因此6 是“完數(shù)”。編程序找出 1000 之內(nèi)的所有完數(shù)蛇耀,并按下面的格式輸出其因子: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辩诞、打印出所有的“水仙花數(shù)”,所謂“水仙花數(shù)”是指一個(gè)?3?位數(shù)蒂窒,其各位數(shù)字立方和等于該數(shù)本身躁倒。例如,?153?是一個(gè)水仙花數(shù)洒琢,因?yàn)?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("{}是水仙花數(shù)".format(i))
5.假設(shè)x褐桌,y是(-1,1)中的兩個(gè)隨機(jī)數(shù)字(服從正態(tài)分布):
(1)當(dāng)x2+y2>1時(shí)衰抑,返回x,y的值
(2)創(chuàng)建一個(gè)列表荧嵌,其中每個(gè)元素對(duì)應(yīng)為的值,?且 a=x2+y2.
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)
作業(yè)五
第四題選作
一呛踊、 輸出 1~100 之間不能被 7 整除的數(shù),每行輸出 10 個(gè)數(shù)字啦撮,要求應(yīng)用字符串格式化方法(任何一種均可) 美化輸出格式谭网。 輸出效果為:
j=0
for i in range(101):? #循環(huán)
??? if i>0 and i % 7 == 0: #如果能整除7,則再執(zhí)行循環(huán)
??????? continue
??? elif i>0:??? #如果大于0并且不能被7整除赃春,輸出愉择;
??????? print("{:3d}".format(i),end=' ')
??????? j += 1??#j用來控制每行輸出是否是10個(gè)
??????? if j % 10 == 0:
??????????? print('\n')
??????????? j = 0
? ??else:
? ? ? ? continue;
二、創(chuàng)建文本文件FarewellCambridge.txt。內(nèi)容為:
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')
#在桌面新建一個(gè)韓正強(qiáng).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!''')
?對(duì)于上一題建立的文本文件层坠,使用read()讀文件殖妇,并在屏幕上顯示。
1.? file = open('C:/Users/uestc/Desktop/hanzhengqiang.txt','r')
2.? #在桌面打開一個(gè)韓正強(qiáng).txt文本文檔破花,并且是讀的模式
3.?#讀取文件谦趣,并且輸出:
4.? s=file.read()
5.? print(s)
根據(jù)給定的文本文件words.txt(可將該文件存放在任意目錄,注意打開文件時(shí)要加入正確的路徑)編寫函數(shù)loadWords()座每,words.txt包含若干小寫英文單詞前鹅。要求:
1) 讀入該文件,統(tǒng)計(jì)并輸出單詞的個(gè)數(shù)
2) 返回單詞列表(注意:指返回單詞列表即可尺栖,不要在屏幕上顯示)
import re
#統(tǒng)計(jì)單詞個(gè)數(shù):
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'))
作業(yè)七
一嫡纠、編寫函數(shù)devide(x, y),x為被除數(shù)延赌,y為除數(shù)除盏。要求考慮異常情況的處理。
1挫以、被零除時(shí)者蠕,輸出"division by zero! ";
2掐松、類型不一致時(shí)踱侣,強(qiáng)制轉(zhuǎn)換為整數(shù)再調(diào)用本函數(shù);
3大磺、 若沒有上述異常則輸出計(jì)算結(jié)果抡句。
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'))
二、?編寫函數(shù)test(password,earning, age)用于檢測輸入錯(cuò)誤杠愧。要求輸入密碼password第一個(gè)符號(hào)不能是數(shù)字待榔,工資earnings的范圍是0—20000,工作年齡的范圍是18—70流济。使用斷言來實(shí)現(xiàn)檢查锐锣,若三項(xiàng)檢查都通過則返回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雕憔、編程實(shí)現(xiàn)如下GUI(只顯示,沒有回調(diào)函數(shù))
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糖声、?編程響應(yīng)用戶事件斤彼》质荩“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趁冈、繪制一個(gè)紅色的五角星圖形,如圖所示拜马。
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渗勘、螺旋線繪制(每一圈是四個(gè)線段組成,一共繪制100個(gè)線段)俩莽。繪制一個(gè)螺旋線的圖形旺坠,如圖所示。
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)
作業(yè)十
一扮超、編寫一個(gè)程序取刃,以2位數(shù)字,X,Y作為輸入出刷,生成一個(gè)二維數(shù)組璧疗。數(shù)組的第i行和第j列中的元素值應(yīng)該是i*j。
注意:i= 0,1 . .,X - 1; ? ?j = 0,1,--Y-1馁龟。
例子假設(shè)程序有以下輸入:3崩侠、5
則程序輸出為:[[0,0,0,0,0],[0,1,2,3,4],[0,2,4,6,8]]
提示:注意:如果要為問題提供輸入數(shù)據(jù),應(yīng)該假設(shè)它是一個(gè)控制臺(tái)輸入坷檩,以逗號(hào)分隔却音。
print('請(qǐng)輸入兩個(gè)數(shù)字:')
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)