Conditional programming or branching is something that we use every day or every moment. For example, if it s raining then i need to carry an umbrella. If i am late for work, then i need call my manager.
The main tool in conditional programming is the if statement. This if statement has different form and can be use according to our requirement.
Below is the syntax of if statement
In the above code, if the condition is true then statements under if condition are executed. If not then they are not executed.
color = "Red" if color == "Red": print("Stop the car") In the first line, color variable has been assigned with value "Red". The next line is the if statement which matches value in color variable with "Red". If this is true then print "Stop the car" Example 2 color = "Green" if color == "Green": print("Move the car")
If statement will match value in color variable with “Green”. If this is true then statement under if condition is executed i.e., “Move the car”
The second form is the if else condition. In the above code, we were having one condition and if that is not true, python will not execute the codes inside if. But what if we to print or do something if condition is not true. In this case,we can go with if else. In this, statements under else are executed if the condition is false or do not matches
Below is the syntax for if else
if condition: statement else: statement
Example 3 : Matching the condition
color = "Red" if color == "Red": print("Stop the car") else: print("Move the car")
Stop the car
We have used if and else condition statement. Assigning value “Red” to color variable and now verifying whether value inside color is “Red” or not. Condition matches and it prints “Stop the car”. If the condition does not matches it will priont “Move the car”
Example 4 : Condition not macthing
color = "Green" if color == "Red": print("Stop the car") else: print("Move the car")
Same code has been written above but did some minor changes. Value of color changes to “Green”. This will not match the condition and it will print “Move the car”
Move the car