Logic Building Keywords In Python, Sprinkle Some Logic In Your Program
Updated: Jul 25
Logic building is the key ingredient while cooking off some codes. Python gives us various helpful logic-building keywords that we can use to implement logic in our program.
In this post, we will discuss the logic-building keywords available in python. The list goes here
IN Keyword In Python
Python introduces this new logical keyword that is very useful while playing with iterable variables and sequences, like string, lists, tuples, dictionaries, and others.
Let's see some use cases of the 'in' keyword in python
>>> s = "soulcodes.org" >>> 'codes' in s True
The above example shows how the 'in' keyword can be used to search a substring within a string.
The use case of the 'in' keyword doesn't end here! The 'in' keyword can also be used to search elements within the lists!
Use Of 'In' Keywords With Lists
>>> brands = ['Nike','Puma','Adidas','New Balance'] >>> 'Nike' in brands True
The 'not in' Keyword In Python
The 'not in' keyword in python is the negation of the work done by the 'in' keyword
>>> 'Nike' not in brands False
These keywords are so useful while playing with strings. They almost solve all your problems of finding solutions with substrings problems.
The 'OR' Keyword In Python
'OR' keyword takes two statements, If any of the two statements results in True, It results in True. Let's look at an example below
>>> brands = ['Nike','Adidas','Puma'] >>> 'Nike' in brands or 'Rebook' in brands True
OR keyword takes two statements, In our case these two statements were
'Nike' in brands
'Rebook' in brands
The first statement is True but the second statement is False, So It breaks Down to
>>>True or Flase True
And Keyword In Python
'And' keywords take two statements, if both of the two statements are true, then and only then it returns True.
>>> brands = ['Nike','Puma','Rebook'] >>> 'Nike' in brands and 'adidas' in brands False
If we breakdown the above example, we got
>>>True and False False
These logical keywords are fundamental and strong foundations for building complex logical programs in python.
You must be wondering, what about the old ways of doing logic? In the old programing language, we have symbols for these logical keywords like
But, they are old, Python still supports them. Python's new way of giving us these keywords, make codes look like more of an English statement.
For now, let's wind up this post here. Will see you people in the next post. Keep Learning!