if if 和 if elif 的區別

2022-08-24 16:03:11 字數 1202 閱讀 5536

再一次程式設計中意外使用了if if 也實現了 if elif的功能,所以搜尋了下其中的區別:

1、if if 和 if elif 是有區別的,只是在某些情況下才會一樣的效果;

2、隨意使用會導致意外的錯誤。

現在舉幾個例子區別:

程式一

defanalyzeage(age ):ifage <21:print"you are a child"ifage >21:print"you are an adult"else:#handle all cases were 'age' is negative print"the age must be a positive integer!"analyzeage(18)#calling the function>youare a child

>theage must be a positive integer!

程式二

defanalyzeage(age ):ifage <21:print"you are a child"elifage >21:print"you are an adult"else:#handle all cases were 'age' is negative print"the age must be a positive integer!"analyzeage(18)#calling the function>youare a child

上面的例子結果出錯,表明 所有的if 後的命令都會執行,而elif後面的命令是根據上乙個if是否執行,如果執行了,elif則略過,否則才執行

另外時間也有區別,再舉個例子:

defmultipleif(text):iftext =='sometext':print(text)iftext =='nottext':print("notanytext")defeliftest(text):iftext =='sometext':print(text)eliftext =='nottext':print("notanytext")text ="sometext"timeit multipleif(text)100000loops,best of 3:5.22us per loop

timeit elif(text)100000loops,best of 3:5.13us per loop

if if 和if else if的區別是什麼?

if 條件1 if 條件2 這種格式中,程式會依次判斷條件1和條件2是否成立並根據結果決定是否執行語句1和語句2,也就是說,第乙個 if 塊和第二個 if 塊 沒有影響 除非在執行第乙個 if 塊的時候就 地 return 了 而下面這種格式 if 條件1 else if 條件2 if 塊和 els...

Python 關於if elif 的實用例子

設計乙個計算器 print 歡迎使用大大牛計算器 print 請輸入第乙個數字 num1 eval input 請輸入第乙個數字 print 請輸入運算子 operator input 請輸入運算子 num2 eval input 請輸入第二個數字 if operator result num1 n...

mysql的 和 的區別 和 的區別

他們之間的區別用最直接的話來說就是 相當於對資料 加上 雙引號,相當於直接顯示資料。1 對傳入的引數視為字串,也就是它會預編譯select from user where name 比如我傳乙個csdn,那麼傳過來就是select from user where name csdn 2 將不會將傳入...