python練習題--羣組練習題(1)

本羣的作業沒有指定Python方向,而在於提升羣內成員的語言功底,本羣熱烈歡迎任何程度的Python學習者。

羣號:651707058

1.首先自已定義一個變量answer,假如answer = 55,然後提示讓用戶猜數字,如果用戶猜的數字過大,就輸出大了,如果猜的數字過小,就輸出小了,直到用戶猜對了。提示用戶猜對了,並給出用戶一共猜了多少次。

'例如:answer = 55'

'用戶輸入:60'

'輸出:大了'

'用戶輸入:50'

'輸出:小了'

'用戶輸入:55'

'輸出:正確,一共猜了3次'

count=0
while True: 
    answer=55
    count=count+1
    guess=int(input('請輸入你猜的數值:'))
    if guess>answer:
        print('你猜大了!')
        continue
    if guess<answer:
        print('你猜小了!')
        continue
    else:
        print('你猜對了!',end=' ')
        break
print('你猜了{0}次'.format(count))

2.上一題answer是提前設置好的,代碼不修改的話,每次運行正確的數字總是55,現在我們需要將answer設置成隨機的,這一次代碼運行answer是89,下次運行answer就變成另一個數字了,需要在上一題的基礎上,再運用random模塊裏面的函數。

import random
def guess_num(answer):
    count=0
    while True:
        count=count+1
        guess=int(input('請輸入你猜的數值:'))
        if guess>answer:
            print('你猜大了!')
            continue
        if guess<answer:
            print('你猜小了!')
            continue
        else:
            print('你猜對了!',end=' ')
            break
    print('你猜了{0}次'.format(count))
if __name__=='__main__':
    answer=random.randint(0,1000)
    guess_num(answer)

3.輸入一個正整數n,對其進行因式分解並輸出。例如:輸入18,輸出18=2*3*3

try:
    num=int(input('請輸入一個整數:'))
except TypeError as ty:
    print('請輸入數字')
for i in range(1,10):
    for j in range(1,10):
        for k in range(1,num):
            if num==i*j*k:
                print('{0}={1}*{2}*{3}'.format(num,i,j,k))

4.設計一個函數裝飾器,這個裝飾器可以記錄任意函數單次調用的運行時間。如果函數的運行時間小於1秒,就不輸出其運行時間,否則輸出此函數的運行時間。所以我們需要寫運行時間小於1秒的函數和運行時間大於1秒的函數去測試。

import time
def show_time(func):
	def inner():
		start_time =time.time()
		func()
		end_time=time.time()
		my_time=end_time-start_time
                if my_time>=1.0:
		        return my_time
	return inner
@show_time
def more():
    print('大於一秒')
    time.sleep(1)#讓程序休眠一秒
@show_time
def less():
    print('小於一秒')
print(more())
print(less())

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章