Python if...else

Python Conditions and If statements

Python supports the usual logical conditions from mathematics:

These conditions can be used in several ways, most commonly in "if statements" and loops.

An "if statement" is written by using the if keyword.

Example

If statement:

 
a = 33

b = 200

if b > a:
  print("b is greater than a")

In this example we use two variables, a and b, which are used as part of the if statement to test whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than 33, and so we print to screen that "b is greater than a".

Indentation

Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other programming languages often use curly-brackets for this purpose.

Example

If statement, without indentation (will raise an error):

 
a = 33

b = 200

if b > a:

print("b is greater than a")
# you will get an error

Elif

The elif keyword is pythons way of saying "if the previous conditions were not true, then try this condition".

Example

 
a = 33

b = 33

if b > a:

	 
	print("b is greater than a")

elif a == b:

	 
	print("a and b are equal")

Python if else

There comes situations in real life when we need to make some decisions and based on these decisions, we decide what should we do next. Similar situations arise in programming also where we need to make some decisions and based on these decisions we will execute the next block of code.Decision-making statements in programming languages decide the direction of the flow of program execution. Decision-making statements available in python are: 

if statementif statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.Syntax:  

 if condition:           
   # Statements to execute if
   # condition is true

Here, the condition after evaluation will be either true or false. if statement accepts boolean values – if the value is true then it will execute the block of statements below it otherwise not. We can use condition with bracket ‘(‘ ‘)’ also.As we know, python uses indentation to identify a block. So the block under an if statement will be identified as shown in the below example:  

 if condition:
   statement1
statement2

# Here if the condition is true, if block 
# will consider only statement1 to be inside 
# its block.

For more, checkout W3Schools and Geeks For Geeks.