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 .
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 .
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
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