If-Else Statements - Coding Chaser

Latest

Let the Journey To Programming begin...

Saturday, January 4, 2020

If-Else Statements


Python Conditions:

Python supports the usual logical conditions from mathematics:
  • Equals:  a==b
  • Not Equals:  a!=b
  • Less than:  a
  • Less than or equal to:  a<=b
  • Greater than:  a>b
  • Greater than or equal to:  a>=b
These conditions can be used in several ways, most commonly in "if statements" and loops.
if  Statements:

You can use if statements to run code if a certain condition holds.If an expression evaluates to True, some statements are carried out. Otherwise, they aren't carried out.An if statement looks like this: 

if expression:
    statements              //Indentation

Here is an example if statement:


If 10>5:

     print(“10 greater than 5”)

print(“Program ended”)

Result:

>>>  
10 greater than 5

Program ended 
>> 

The expression determines whether 10 is greater than five. Since it is, the indented statement runs, and "10 greater than 5" is output. Then, the unindented statement, which is not part of the if statement, is run, and "Program ended" is displayed.

                                                                            
************************************************************************************
else Statements:


An else statement follows an if statement, and contains code that is called when the if statement evaluates to False.
As with if statements, the code inside the block should be indented.


x=4
if x==5:
      print("Yes")
else:
      print("No")


You can chain if and else statements to determine which option in a series of possibilities is true.


if num == 5:
print("Number is 5")
else
if num == 11:
print("Number is 11")
else:
if num == 7:
print("Number is 7")
else
print("Number isn't 5, 11 or 7")

Result:
>>
Number is 7
>>


************************************************************************************
elif  Statements:

The elif (short for else if) statement is a shortcut to use when chaining if and else statements.
A series of if elif statements can have a final else block, which is called if none of the if or elif expressions is True.

For example:

num = 7
if num == 5:
print("Number is 5")
elif num == 11:
print("Number is 11")
elif num == 7:
print("Number is 7")
else:
print("Number isn't 5, 11 or 7")

Result:
>>>
Number is 7

>>> 

No comments:

Post a Comment

Text