Saturday, June 29, 2019

Python Conditional Expressions

Python supports conditional expressions. Conditional expressions allow you to execute statements only when a specific condition is met. Conditions are mathematical expressions such as:

a == 0         #Is a equal to zero?
a != 0         #Is a equal to zero?
a > 100        #Is a greater than 100
a >= 100       #Is a greater than or equal to 100
a < c          #Is a less than c
a <= c         #Is a less than or equal to c

Conditionals can be used outside of an if, while or other conditional statement. If you set the variable a to a value you can use the above expressions to evaluate the result. The below program sets a to 0 and then evaluates its condition


>>> a = 0
>>> a == 0
True
>>> a < 0
False
>>> a <= 0
True
>>> a > 0
False
>>> a == 10000
False
>>> 

Conditional expressions evaluate to a boolean type. If you pass them to the built-in type function you can see they are boolean objects.

>>> type(a == 0)
<class 'bool'>
>>> 

Because conditional expressions can be evaluated to a variable, really an object, we can store the conditional for later use.

>>> is_a_equal_to_zero = a == 0
>>> is_a_equal_to_zero
True
>>> 

Once the variable is_a_equal_to_zero is assigned it stores the last known evaluation of a == 0 and not what it currently is. If you re-assign a to a new value it will not change is_a_equal_to_zero.


>>> is_a_equal_to_zero = a == 0
>>> is_a_equal_to_zero
True
>>> a = 10000
>>> is_a_equal_to_zero
True
>>> 

Conditional Expressions are fundamental in programming and it is difficult to get any "real work" done without having some kind of conditional logic. You can combine conditional expressions with if statements, while loops and other python structures.

1 comment:

  1. Python is the language of the future, and Gyansetu's Python courses are the perfect gateway to this exciting world. Their expert instructors and practical approach make learning Python a breeze. Whether you're a beginner or looking to level up your skills, Gyansetu has you covered!
    For more info:- https://www.gyansetu.in/blogs/future-scope-of-python-in-india/

    ReplyDelete

nonlocal keyword

The nonlocal keyword is used to allow an inner function to access variables defined in an outer function. Without using the nonlocal keywo...