Python 100天-從新手到大師學習筆記Day03:分支結構

Yanwei Liu
4 min readMay 20, 2019

範例

身分驗證

username = input('請輸入用戶名: ')
password = input('請輸入口令: ')
# 如果希望输入口令时 终端中没有回显 可以使用getpass模块的getpass函数
# import getpass
# password = getpass.getpass('請輸入口令: ')
if username == 'admin' and password == '123456':
print('身分驗證成功!')
else:
print('身分驗證失败!')

求分段函數

x = float(input('x = '))
if x > 1:
y = 3 * x - 5
elif x >= -1:
y = x + 2
else:
y = 5 * x + 3
print('f(%.2f) = %.2f' % (x, y))
--------------------------------x = float(input('x = '))
if x > 1:
y = 3 * x - 5
else:
if x >= -1:
y = x + 2
else:
y = 5 * x + 3
print('f(%.2f) = %.2f' % (x, y))

公制英制轉換

value = float(input('請輸入長度: '))
unit = input('請輸入單位: ')
if unit == 'in' or unit == '英寸':
print('%f英寸 = %f厘米' % (value, value * 2.54))
elif unit == 'cm' or unit == '厘米':
print('%f厘米 = %f英寸' % (value, value / 2.54))
else:
print('請輸入有效的单位')

擲骰子決定做什麼

from random import randintface = randint(1, 6)         #face資料型態為int
if face == 1:
result = '唱首歌'
elif face == 2:
result = '跳个舞'
elif face == 3:
result = '学狗叫'
elif face == 4:
result = '做俯卧撑'
elif face == 5:
result = '念绕口令'
else:
result = '讲冷笑话'
print(result)

百分等級成績轉換

score = float(input('請輸入成績: '))
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
elif score >= 60:
grade = 'D'
else:
grade = 'E'
print('對應的等級是:', grade)

輸入三邊長計算周長和面積

import matha = float(input('a = '))
b = float(input('b = '))
c = float(input('c = '))
if a + b > c and a + c > b and b + c > a:
print('周長: %f' % (a + b + c))
p = (a + b + c) / 2
area = math.sqrt(p * (p - a) * (p - b) * (p - c)) #海龍公式
print('面積: %f' % (area))
else:
print('不能構成三角形')

所得稅計算器

salary = float(input('本月收入: '))
insurance = float(input('五險一金: '))
diff = salary - insurance - 3500
if diff <= 0:
rate = 0
deduction = 0
elif diff < 1500:
rate = 0.03
deduction = 0
elif diff < 4500:
rate = 0.1
deduction = 105
elif diff < 9000:
rate = 0.2
deduction = 555
elif diff < 35000:
rate = 0.25
deduction = 1005
elif diff < 55000:
rate = 0.3
deduction = 2755
elif diff < 80000:
rate = 0.35
deduction = 5505
else:
rate = 0.45
deduction = 13505
tax = abs(diff * rate - deduction) #abs為絕對值函式
print('個人所得稅: ¥%.2f元' % tax)
print('實際到手收入: ¥%.2f元' % (diff + 3500 - tax))

--

--