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

How to use if statements in Python

編輯:Python

if Statement is used to express a possible situation , And how to deal with the situation .if Statements can be used to express a possibility 、 Two or more possibilities .

1 One possibility

A single if The statement represents a possibility ,if Keyword followed by expression , When the expression is True when , This situation has happened , Execute the specified statement , Handle the situation immediately , Pictured 1 Shown .

chart 1 Single if Use of statements

  among , chart 1① Use input() Function to receive the value entered by the user , Convert it to int Type is not saved in the variable ; chart 1② adopt if Statement pair variable x Judge , If x The value is greater than 0, The output “ What you entered is a non negative number ” This information ( chart 1③). It should be noted that ,if The statement is followed by an expression , The expression is followed by a colon , The statement to be executed is preceded by an indent .

The effect of running the code is shown in the figure 2 Shown .

chart 2 Code running effect

  From the picture 2 It can be seen that , When the input integer is 10 when , Will be output “ What you entered is a non negative number ” This information .

2 Two possibilities

If it is necessary to judge the value entered by the user as non negative or negative , There are two possibilities , You can use if...else sentence , Pictured 3 Shown .

chart 3 if...else Use of statements

  among , When if Statements and “1 One possibility ” Use the same in , When if The expression of False when , It will call else Statement corresponding to the processing statement . When you enter a negative number , Will be displayed “ You entered a negative number ”, Pictured 4 Shown .

chart 4 Code running effect

 3 There are many possibilities

If you need to positive the value entered by the user 、 When judging zero and negative numbers , There are three possibilities , You can use if...elif...else sentence , Pictured 5 Shown .

chart 5 if...elif...else Usage of sentences

  among ,elif yes else if Abbreviation , in other words , When if The expression of False when , Will then judge elif Is the expression of True, If it is True, execute elif Corresponding processing code ; If it is False execute else Corresponding processing code . The effect of the code execution is shown in the figure 6 Shown .

chart 6 Code running effect

 


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