In this Basic Python Tutorials Our Topic of Discussion will be Python Condition & Branching.
First Let us start with
Comparison operations compare some value or operand. Comparison operators compare two values and evaluate down to a single Boolean value. Boolean data type has only two values: True and False. it has same functionality as in other programming languages. If our conditions doesn’t match result is Boolean data type ‘False’ and it it matches it is ‘True’.
When comparing two values We can use these operators:
- not equal:
- greater than:
- less than:
- greater than or equal to:
- less than or equal to:
= is for assignment but not a operator.
x==10 what will be result?
We can use these operators on any data type.
Mixing Boolean and Comparison Operators
Since the comparison operators evaluate to Boolean values, you can use them in expressions with the Boolean operators.
Recall that the and, or, and not operators are called Boolean operators because they always operate on the Boolean values True and False. While expressions like 4 < 5 aren’t Boolean values, they are expressions that evaluate
down to Boolean values. Try entering some Boolean expressions that use comparison operators into the interactive shell.
>>> (10.5 < 11) and (8 < 9)
>>> (4 < 5) and (11 < 112)
>> (1 == 1) or (2 == 3)
For the choice of selection or favorable results or For Putting some restrictions in form of conditions we have Branching in Python.
if i am right you are wrong
else you are right.
if you have 60 dollars you are allowed to come in this market or get lost!
I follow Python for Data Science course at Cognitiveclass.ai. They have neatly covered it-
Branching allows us to run different statements for a different input. It’s helpful to think of an if statement as a locked room, if the statement is true you can enter the room and your program can run some predefined task if the statement is false your program will skip the task.
#expression that can be true or false
#within an indent, we have the expression that is run if the condition is true
print(“you can enter” )
#The statements after the if statement will run regardless if the condition is true or false
The else statement
it will run a different block of code if the same condition is false. Let us use the ACDC concert analogy again, if the user is 17 they can not go to the ACDC consort, but they can go to the Meatloaf concert.
The syntax of the else statement is similar; we simply append the statement else statement at with the new condition. You can try changing the values of age to see what happens.
age=18#age=19if age>18:print("you can enter" )else:print("go see Meat Loaf" )print("move on")
It provides another condition that is checked only if any of the previous conditions were False. In code, an elif statement always consists of the following:-
• A condition (that is, an expression that evaluates to True or False)
• A colon
• Starting on the next line, an indented block of code (called the elif