1. 程式人生 > >Python 從入門到入門基礎練習十五題

Python 從入門到入門基礎練習十五題

1、永遠的 HelloWorld

print("Hello World")

2、M與N的數學運算:使用者輸入兩個數 M 和 N,其中 N 是整數,計算M 和 N 的5種數學運算結果,並依次輸出,結果間用空格分隔。

5種數學運算分別是:M 與 N 的和、M 與 N 的乘積、M 的 N 次冪、M除 N 的餘數、M 和 N 中較大的值。

m = eval(input())
n = eval(input())

list = []
list.append(str(m+n))
list.append(str(m*n))
list.append(str(m**n))
list.append(str(m%n))
if
m > n: list.append(str(m)) else: list.append(str(n)) print(" ".join(tuple(list)))

3、將輸入的字串垂直輸出

def Output(string):
    for char in string:
        print(char)

s = input()
Output(s)

4、計算矩形面積:使用者輸入矩形的長和寬,計算其面積並輸出,結果四捨五入,保留2位小數。

a = eval(input("請輸入矩形長度:"))
b = eval(input("請輸入矩形寬度:"))

print("面積是:%.2f"
%(a*b))

5、計算2的n次方,n由使用者輸入

a = eval(input())

print(2**a)

6、成績轉換:編寫一個學生成績轉換程式,使用者輸入百分制的學生成績,成績大於或等於60的輸出“pass”,否則輸出“fail”,成績不四捨五入。

a = eval(input())

if 100 >= a >= 60:
    print("pass")
else:
    print("fail")

7、完美立方:找到大於1的4個整數滿足完美立方等式:a3=b3+c3+d3(例如123=63+83+103)。編寫一個程式,對於任意給定的正整數N(N ≤100),尋找所有的四元組(a,b,c,d),滿足a3=b3+c3+d3,其中1<a,b,c,d≤N。

n = int(input())  # n範圍內的立方數

list_cube = [0]  # 用於儲存立方數的列表
for i in range(1, n + 1):
    list_cube.append(i * i * i)

for a in range(6, n + 1):
    for b in range(2, a - 1):
        if list_cube[a] < (list_cube[b] + list_cube[b + 1] + list_cube[b + 2]):
            break
        for c in range(b + 1, a):
            if list_cube[a] < (list_cube[b] + list_cube[c] + list_cube[c + 1]):
                break
            for d in range(c + 1, a):
                if list_cube[a] == (list_cube[b] + list_cube[c] + list_cube[d]):
                    print("Cube=%d,Tripe=(%d,%d,%d)" % (a, b, c, d))

8、貨幣轉換:寫一個程式進行貨幣間幣值轉換,其中:人民幣和美元間匯率固定為:1美元 = 6.78人民幣。

程式可以接受人民幣或美元輸入,轉換為美元或人民幣輸出。人民幣採用RMB表示,美元USD表示,符號和數值之間沒有空格。

import re
money = input().lower()
tmp=re.findall('usd|rmb',money)
if len(tmp)==0 or len(tmp)>1:
    print('wrong')
money=re.sub(tmp[0],'',money)
try:
    num=float(money)
    if 'usd' in tmp:
        print('RMB%.2f'%(num*6.78))
    else:
        print('USD%.2f'%(num/6.78))
except:
    print('wrong')

9、月份縮寫:如果有 months = "Jan.Feb.Mar.Apr.May.Jun.Jul.Aug.Sep.Oct.Nov.Dec.",編寫一個程式,使用者輸入一個月份的數字,輸出月份的縮寫。

months = "Jan.Feb.Mar.Apr.May.Jun.Jul.Aug.Sep.Oct.Nov.Dec."
n = input()

#(每個月份的數字-1)*4就是這個月份簡寫的開始索引,擷取4個字元
index = (int(n)-1)*4
month = months[index: index + 4]
print(month)

10、溫度轉換:編寫程式將使用者輸入華氏度轉換為攝氏度,或將輸入的攝氏度轉換為華氏度。

轉換演算法如下:(C表示攝氏度、F表示華氏度)

     C = ( F - 32 ) / 1.8
     F = C * 1.8 + 32

要求如下:

(1) 輸入輸出的攝氏度採用大寫字母C開頭,溫度可以是整數或小數,如:C12.34指攝氏度12.34度;

(2) 輸入輸出的華氏度採用大寫字母F開頭,溫度可以是整數或小數,如:F87.65指攝氏度87.65度;

(3) 不考慮異常輸入的問題,輸出保留小數點後兩位;

Temperature = input()
if Temperature[0] in ['F']:
    C = (eval(Temperature[1:])-32)/1.8
    print("C{:.2f}".format(C))
else:
    F = 1.8*eval(Temperature[1:])+32
    print("F{:.2f}".format(F))

11、匯率兌換:按照1美元=6人民幣的匯率來編寫一個美元與人民幣的雙向兌換程式

money = input()

if money[-1] in ['$']:
    m = 6*eval(money[:-1])
    print("{:.2f}R".format(m))

else:
    if money[-1] in ['R']:
        m = eval(money[:-1])/6
        print("{:.2f}$".format(m))
    else:
        print("輸入錯誤!")

12、愷撒密碼:凱撒密碼是古羅馬凱撒大帝用來對軍事情報進行加解密的演算法,它採用了替換方法對資訊中的每一個英文字元迴圈替換為字母表序列中該字元後面的第三個字元,即,字母表的對應關係如下:

原文:A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
密文:D E F G H I J K L M N O P Q R S T U V W X Y Z A B C

對於原文字元P,其密文字元C滿足如下條件:C=(P+3) mod 26

上述是凱撒密碼的加密方法,解密方法反之,即:P=(C-3) mod 26

假設使用者可能使用的輸入僅包含小寫字母a~z和空格,請編寫一個程式,對輸入字串進行凱撒密碼加密,直接輸出結果,其中空格不用進行加密處理。

sr1 = "abcdefghijklmnopqrstuvwxyz"
sr2 = sr1.upper()
sr = sr1 + sr1 + sr2 + sr2
in_str = input("")
out_str = ""
for j in in_str:
    if j == " ":
        out_str = out_str + " "
        continue
    i = sr.find(j)
    if(i > -1):
        out_str = out_str + sr[i+3]
print(out_str)

13、個人所得稅計算:個人所得稅採用“超額累進稅率”計算方法,簡化公式如下:

   繳稅 = (個人薪金扣險所得 – 個稅免徵額)* 稅率

其中,個稅免徵額為3500元,稅率根據應納稅額數量而不同,如下圖所示:


注意:“應納稅額”為:個人薪金扣險所得 – 個稅免徵額

請編寫一個程式根據使用者輸入計算個人所得稅,使用者輸入是個人薪金扣險所得。

約定使用者輸入為以人民幣元為單位的整數。

m = int(input())
ans = 0
if m > 3500:
    m1 = m - 3500
    if m1 < 1500:
        ans = 0.03 * m1
    elif m1 < 4500:
        ans = 0.1 * m1
    elif m1 < 9000:
        ans = 0.2 * m1
    elif m1 < 35000:
        ans = 0.25 * m1
    elif m1 < 55000:
        ans = 0.3 * m1
    elif m1 < 80000:
        ans = 0.35 * m1
    else:
        ans = 0.45 * m1
else:
    ans = 0
print("%.0f"%ans)

14、3位水仙花數計算:“3位水仙花數”是指一個三位整數,其各位數字的3次方和等於該數本身。例如:ABC是一個“3位水仙花數”,則:A的3次方+B的3次方+C的3次方 = ABC。

請按照從小到大的順序輸出所有的3位水仙花數,請用一個“逗號+空格”分隔輸出結果。

import math
list = []

for i in range(100, 1000):
    x = math.floor(i / 100)
    y = math.floor((i - x * 100) / 10)
    z = i - math.floor(i / 10) * 10
    if i == x ** 3 + y ** 3 + z ** 3:
        list.append(str(i))
print(", ".join(tuple(list)))

15、統計下列英文詩歌:

All that doth flow we cannot liquid name
Or else would fire and water be the same;
But that is liquid which is moist and wet
Fire that property can never get.
Then 'tis not cold that doth the fire put out
But 'tis the wet that makes it die, no doubt.

程式設計實現對紐卡斯伯爵的不朽名篇What Is Liquid的統計工作。這首詩(1)有多少個字元?(計入空格和換行符)(2)判斷是否以All開頭?(3)判斷是否以That's all, folks!結尾?(4)第一次和最後一次出現單詞the的位置(偏移量)。(5)the出現的總次數?(6)判斷詩中出現的所有字元是否都是字母和數字?

s = "All that doth flow we cannot liquid name Or else would fire and water be the same;But that is liquid which is moist and wet Fire that property can never get. Then 'tis not cold that doth the fire put out But 'tis the wet that makes it die, no doubt. "
print("這首詞總共有:" + str(len(s)) + "個字串")
print("這首詩是否以All開頭:",s.startswith('All'))
print("這首詩是否以That\'s all, folks!結尾:",s.endswith('That\'s all, folks!'))
print("第一次出現單詞the的位置:",s.find(' the '))
print("最後一次出現單詞the的位置:",s.rfind(' the '))
print("the在詩中出現的總次數:",s.count(' the '))
print("是否詩中出現的所有字元都是字母和數字:",s.isalnum())

掃描關注微信公眾號,瞭解更多