Nested if Statements

An if statement’s block can contain any type of Python statement, which implies that it can include other if statements. An if statement inside another is called a nested if statement.

 value = input(​'Enter the pH level: '​)
 if​ len(value) > 0:
  ph = float(value)
 if​ ph < 7.0:
 print​(ph, ​"is acidic."​)
 elif​ ph > 7.0:
 print​(ph, ​"is basic."​)
 else​:
 print​(ph, ​"is neutral."​)
 else​:
 print​(​"No pH value was given!"​)

In this case, we ask the user to provide a pH value, which we’ll initially receive as a string. The first, or outer, if statement checks whether the user typed something, which determines whether we examine the value of pH with the inner if statement. (If the user didn’t enter a number, then function call float(value) will produce a ValueError.)

Nested if statements are sometimes necessary, but they can get complicated and difficult to understand. To describe when a statement is executed, we have to mentally combine conditions; for example, the statement print(ph, "is acidic.") is executed only if the length of the string that value refers to is greater than 0 and pH < 7.0 also evaluates to True (assuming the user entered a number).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.24.180