Page 192 - AI_Ver_3.0_class_11
P. 192

Program 15: To demonstrate the use of the if-else statement

                   # Asking the user for input
                   temperature = float(input("Please enter the temperature in Celsius: "))
                   # Checking if the temperature is above or below freezing point
                   if temperature <= 0:
                       print("It's freezing!")
                   else:
                       print("It's not freezing.")
              Output:

                  Please enter the temperature in Celsius: 35
                  It's not freezing.

              The if-elif-else Statement
              The  if…elif…else  statement helps us to test
              multiple  conditions  and follows  a top-down
              approach.  The if statement is used to  check  a   Test Expression 1  True  Statement Block 1
              single  condition,  while  the  elif  (short  for  "else
              if")  statement  allows  you  to  check  additional
              conditions if the previous conditions are not            False
              met. If none of the conditions evaluates to True,
              then the final else statement gets executed. The     Test Expression 2  True  Statement Block 2
              if…elif…else statement provides a way to handle
              multiple decision branches in your code.
                                                                      False
              The syntax of the if...elif...else statement is as follows:

                   if (Test Expressions_1):                                     True
                                                              Test Expression 3       Statement Block 3
                        Statement block 1
                   elif (Test Expression_2):
                                                                       False          Statement Block 4
                        Statement block 2

                   elif (Test Expression_3):
                                                                                                   Execute statement
                        Statement block 3
                                                                                                outside if...elif...else block
                   else:
                        Statement block 4

                Program 16: To demonstrate the use of the if-elif-else statement
                   # Asking the user for input

                   score = int( input("Please enter your exam score: "))
                   # Grading the score
                   if score >= 90:

                       print("Your grade is A.")
                   elif score >= 80:
                       print("Your grade is B.")
                   elif score >= 70:

                       print("Your grade is C.")

                    190     Touchpad Artificial Intelligence (Ver. 3.0)-XI
   187   188   189   190   191   192   193   194   195   196   197