List and give syntax of all python supported conditional statements
List and give syntax of all python supported conditional statements along with their usage with an example program to check whether a given number is positive or negative or zero.
Python support four types of conditional statements, they are,
Conditional Execution: The simplest form of a conditional statement is if statement. Here if the conditional expression is true the set of statements under the if block is executed. Otherwise, the execution skips the if block and continues with the next statement.
Example: In this example first the conditional expression x>0 is checked. If the value of x is more than 0 then the print statement is executed otherwise the print statement will not be executed.
Alternate Execution: This is the second form of the if statement. Here if the conditional expression is True then the statements under the if block is executed otherwise the statement under the else block are executed.
Example: In this example first the conditional expression x% 2 == 0 is evaluated. If the condition is True the “x is even” is printed otherwise “x is odd” will be printed.
Chained Conditional Statement: Sometimes programmers want to check more than two conditions. In such a case, if-else or alternate execution fails to perform the necessary task. Here comes the chained execution. Here programmer can check multiple conditions in a chained fashion. This statement is also called if-then-else-if logic.
Example: Here the expression x<y is evaluated, it is True then “less” will be printed as output. If the expression is False then x>y is checked if it is True then “greater” is printed. If it is False, then “equal” is printed.
Nested Conditional statement: One conditional statement may be nested under another conditional statement. Such a conditional statement is called a nested conditional statement.
Example: In this case, one conditional statement is nested within another conditional statement.
Develop a python program to check whether a given number is positive or negative or zero.
Here first we rad number from user and store it into variable n. Next, we convert n to an integer using the int() function. Then we use a conditional statement to check whether the number is positive (if n is greater than 0), negative (if n is less than o), zero (otherwise). Finally, we print the respective results using the print() function.
n = input ("Enter a number:") n = int (n) if (n > 0): print ("n is positive") elif (n < 0): print ("n is negative") else: print ("n is zero")
Enter a number: -1
n is negative
Enter a number: 10
n is positive
Enter a number: 0
n is zero
List and give syntax of all python supported conditional statements along with their usage with an example program to check whether a given number is positive or negative or zero. Subscribe to our YouTube channel for more videos and like the Facebook page for regular updates.