1. 程式人生 > >python的while迴圈和for迴圈的練習

python的while迴圈和for迴圈的練習

練習結果:

說明:python divmod() 函式把除數和餘數運算結果結合起來,返回一個包含商和餘數的元組(a // b, a % b)。

具體程式碼:

# 計算1~100之間所有整數的和
num = 0
i = 1
while i < 101:
    num += i
    i += 1
print(num)

# 列印字元A~Z
'''
n = 65
while n <= 90:
    l = chr(n)
    n += 1
    print(l, end=' ')

'''
# 迴圈輸入10個字元,
# 大寫轉小寫,小寫轉大寫,其它字元不變,然後輸出
'''
i = 1
while i <= 10:
    n = input("請輸入一個字元:")
    if 65 <= ord(n) <97:
        print(chr(ord(n) + 32))
    elif 97 <= ord(n) <= 122:
        print(chr(ord(n)-32))
    else:
        print(n)
    i += 1

'''
# 將12345轉換為54321
'''
m = int(input("請輸入整數:"))
n = 0
while m:
    m, last = divmod(m, 10)
    n = n * 10 + last
print(n,type(n))

'''
# 將12345轉換為'12345',不要使用str
'''
n = int(input("請輸入:"))
m = ''
while n:
    n, last = divmod(n, 10)
    l = chr(last+ord('0'))
    m = l + m
print(m,end='')
'''
# 將'12345'轉換為12345,不要使用int
'''
n = str(input("請輸入:"))
m = 0
for i in n:
    l = ord(i)-ord('0')
    m = m*10+l
print(m,type(m))
'''
遍歷列表,列印:我叫name,今年age歲,家住dizhi,電話phone
lt = [
   {'name':'小王', 'age':18, 'info':[('phone', '123'), ('dizhi', '廣州')]},
    {'name':'小芳', 'age':19, 'info':[('phone', '789'), ('dizhi', '深圳')]},
    {'name':'小杜', 'age':22, 'info':[('phone', '567'), ('dizhi', '北京')]},
    {'name':'小孟', 'age':28, 'info':[('phone', '000'), ('dizhi', '上海')]},
    {'name':'小喬', 'age':26, 'info':[('phone', '111'), ('dizhi', '河南')]},
]
'''
'''
lt = [
   {'name':'小王', 'age':18, 'info':[('phone', '123'), ('dizhi', '廣州')]},
    {'name':'小芳', 'age':19, 'info':[('phone', '789'), ('dizhi', '深圳')]},
    {'name':'小杜', 'age':22, 'info':[('phone', '567'), ('dizhi', '北京')]},
    {'name':'小孟', 'age':28, 'info':[('phone', '000'), ('dizhi', '上海')]},
    {'name':'小喬', 'age':26, 'info':[('phone', '111'), ('dizhi', '河南')]},
]
for k in lt:
    print('我叫{},今年{}歲,家住{},電話{}\n'.format
    (k['name'],k['age'],k['info'][1][1],k['info'][0][1]),end='')

'''
# 列印九九乘法表
for i in range(1,10):
    for j in range(1,i+1):
        print('{}*{}={}\t'.format(i,j,i*j),end='')
    print()
'''
# 從終端輸入兩個整數m和n,列印m*n的表格,
# 如:2,5,列印如下圖形:
# 1 2 3 4 5
# 6 7 8 9 10
m = int(input("請輸入一個整數:"))
n = int(input("請再輸入一個整數:"))
for i in range(m):
    for j in range(n):
        print(i * n +(j+1), end=' ')
    print()