程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

4-Branch judgment of Python basic programming

編輯:Python

Python分支判斷

  • 執行順序
  • 單分支判斷
  • 雙分支判斷
  • if嵌套
  • 多分支判斷
  • 小節練習

執行順序

Roughly from top to bottom,If a branch is encountered, enter a different branch,If there is a loop, the same code will be executed multiple times,There are similarities in some languagesgoto的語句,then it can jump to the specified label.

單分支判斷

age = 17
if age >= 18:
print("已經成年")

雙分支判斷

age = 17
# 滿足條件執行if
if age >= 18:
print("已經成年")
# 不滿足條件執行else
else:
print("未成年")

if嵌套

score = 90
# 滿足條件執行if
if score >= 90:
print("A")
else:
if 80<=score<90:
print("B")
else:
if 70<=score<80:
print("C")

多分支判斷

score = 90
if score >= 90:
print("A")
elif 80<=score<90:
print("B")
elif 70<=score<80:
print("C")

小節練習

對3The body fat percentage calculation in :
It is necessary to judge whether the input is within the normal range,如0-3m之間.包括體重、年齡、性別.
對於數據處理,The classification calculation is based on the distinction between men and women.
對於輸出,more humane language.

# 輸入設置
Pheight = eval(input("請輸入身高(m):"))
Pweight = eval(input("請輸入體重(kg):"))
Page = eval(input("請輸入年齡:"))
Psex = eval(input("請輸入性別(男:1 女:0):"))
# Data valid row validation
if not(0<Pheight<3 and 0<Pweight<300 and 0<Page<150 and (Psex == 1 or Psex == 0)):
print("數據錯誤,請檢查重新輸入")
exit()
# 數據處理
BMI = Pweight/(Pheight**2)
TZL = 1.2 * BMI + 0.23 * Page - 5.4 - 10.8 * Psex
# Distinguish between men and women
if Psex==1:
result = 15<TZL<18
elif Psex==0:
result = 25<TZL<28
#輸出設置
if Psex==1:
wenhao = "先生你好,"
minNum = 15
maxNum = 18
elif Psex==0:
wenhao = "hello madam,"
minNum = 25
maxNum = 28
if result:
notice = "Your body fat percentage is normal"
else:
if TZL > maxNum:
notice = "Your body fat percentage is abnormal,偏胖"
else:
notice = "Your body fat percentage is abnormal,偏瘦"
print(wenhao,notice,sep="")

輸出:


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved