30 Days Of Python πŸ‘¨β€πŸ’» - Day 5 - Conditions And Loops I

This article is a part of a challenge series on Python. You can find the link to the previous articles in this series here,
It has been an exciting 4 days of experience learning Python. Until now I have been able to cover some of the basic syntaxes of Python along with the data types and how to perform actions on them using built-in functions and methods along with some best practices. This was probably the dull parts and scratching the surface of Python. Today my short goal was to understand logical and conditional programming along with repeating tasks using loops in Python. Very interesting indeed!
 

Conditional Logic

  1. age = input('Please enter your age')  
  2. if(int(age) >= 18):  
  3.   print('You are allowed to enter the club')  
  4. else:  
  5.   print('Sorry! you are not allowed!')  
The above is an example of an if-else conditional statement in Python. It is used to execute logic based on some condition. If the condition is not fulfilled, then the code in the else block is executed. Coming from the JavaScript universe, the differences I noted is there are no curly braces surrounding the if-else blocks and instead of a : is used after the conditional statement. The block inside a conditional statement is also indented. I wired these two things to my Python mental model,
  1. exam_score = input('Enter your exam score')  
  2. if(int(exam_score) > 90):  
  3.   print('You have got grade A+')  
  4. elif(int(exam_score) > 80):  
  5.   print('You have got grade A')  
  6. else:  
  7.   print('You have got grade B')  
If there are multiple conditions that need to be executed, then an elif block is used. In many other programming languages including JavaScript, it is called else if block. There can be any number of else if blocks to check different conditions. Python makes it more compact.
  1. is_adult = True  
  2. is_licensed = True  
  3.   
  4. if(is_adult and is_licensed): ## In JavaScript && is used instead of 'and'  
  5.   print('You are allowed to drive')  
  6. else:  
  7.   print('You are not allowed to drive')  
The above code checks for two conditions in a single expression to execute the block. The and keyword is used to check if both conditions evaluates to True then only the block is executed. This syntax is so easy to read! Python definitely is more readable. Indentation is the way to separate lines of code using spaces/tabs so that the interpreter can distinguish code blocks and execute the code accordingly. Python does not use any braces unlike JavaScript, and instead uses indentation to chunk blocks of code. The code editors make our life easy by automatically doing the indentation. The online editor Repl that I am using as a playground also does that.
  1. if(10 > 8):  
  2.   print('Such a silly logic. I will get printed')  
  3. else:  
  4.   print('I will never get printed')  
  5.   print('I am not get printed coz I am indented')  
  6.   
  7. # Now without indentation  
  8. if(10 > 8):  
  9.   print('Such a silly logic. I will get printed')  
  10. else:  
  11.   print('I will never get printed')  
  12. print('I will be printed anyways coz I am not indented')  
  13. # The above line gets printed always as interpreter treats it as a new line  

Truthy and Falsy

  • Values that evaluate to true are called Truthy
  • Values that evaluate to false are called Falsy
When checking for a condition, the expression inside a condition is evaluated to a boolean value using type conversion. Now all values are considered “truthy” except for the following, which are “falsy”:
  • None
  • False
  • 0
  • 0.0
  • 0j
  • Decimal(0)
  • Fraction(0, 1)
  • [] - an empty list
  • {} - an empty dict
  • () - an empty tuple
  • '' - an empty str
  • b'' - an empty bytes
  • set() - an empty set
  • an empty range, like range(0)
  • objects for which
    • obj.__bool__() returns False
    • obj.__len__() returns 0
  1. username = 'santa' # bool('santa') => True  
  2. password = 'superSecretPassword' # bool('superSecretPassword') => True  
  3. if username and password:  
  4.   print('Details found')  
  5. else:  
  6.   print('Not found')  

Ternary Operator

 
While going through the syntax of the ternary operator in Python, I found it a bit confusing initially but then found it quite easy to read compared to the one I am familiar with in my JavaScript world
  1. is_single = True  
  2. message = 'You can date' if is_single else 'you cannot date'  
  3. # result = (value 1) if (condition is truthy) else (value 2)  
  4. print(message) # You can date  
Ternary operator is also sometimes called a conditional expression. It is a very handy way to check a condition in a single statement. I compared it with the ? operator syntax of JavaScript to solidify my mental model.
 

Short-Circuiting

 
While checking for multiple logical conditions in a single statement, the interpreter is smart enough to to ignore the rest of the condition and check if the first condition fails. This is known as short-circuiting. It can be better explained using an example.
  1. knows_javascript = True  
  2. knows_python = True  
  3.   
  4. if(knows_javascript or knows_python): # doesn't depend on value of knows_python  
  5.   print('Javscript or python developer')  
  6. else:  
  7.   print('Some other developer')  
  8. Copy  
  9. knows_javascript = False  
  10. knows_python = True  
  11.   
  12. if(knows_javascript and knows_python): # doesn't depend on value of knows_python  
  13.   print('Javscript or python developer')  
  14. else:  
  15.   print('Some other developer')  
The or is another conditional operator in python. Check this article on short circuit techniques
 

Logical Operators

 
Apart from and, or, there are few are logical operators in Python such as not, >, <, ==, >=, <=, !=
  1. print(10 > 100# False  
  2. print(10 < 100# True  
  3. print(10 == 10# True  
  4. print(10 != 50# True  
  5. print(2 > 1 and 2 > 0# True  
  6. print(not(True)) # False  
  7. print(not False# True  
Python operatorsSome quirky operations
  1. print(True == True#True  
  2. print('' == 1# False  
  3. print([] == 1# False  
  4. print(10 == 10.0# True  
  5. print([] == []) # True  
Python has a strict checking operator is which checks for the value as well as their memory locations. It is almost similar to the === operator in JavaScript.
  1. print(True is True# True  
  2. print('' is 1# False  
  3. print([] is 1# False  
  4. print(10 is 10.0# False  
  5. print([] is []) # False  

For Loops

 
Loops allow us to run a block of code multiple numbers of times. In Python, the basic form of loop is a for loop which can loop over an iterable.
  1. for item in 'Python'# String is iterable  
  2.   print(item) # prints all characters of the string  
  3.   
  4. for item in [1,2,3,4,5]: # List is iterable  
  5.     print(item) # prints all numbers one at a time  
  6.   
  7. for item in {1,2,3,4,5}: # Set is iterable  
  8.     print(item)  
  9.   
  10. for item in (1,2,3,4,5): # Tuple is iterable  
  11.     print(item)  

Iterable

 
An iterable is a collection of data that can be iterated. It means the items of the collection can be processed one by one. Lists, strings, tuples, sets and dictionaries are all iterables. The action that is performed on an iterable is iteration and the current item that is being processed is called iterator.
  1. player = {  
  2.   'firstname''Virat',  
  3.   'lastname''Kohli',  
  4.   'role''captain'  
  5. }  
  6.   
  7. for item in player: # iterates over the keys of player  
  8.   print(item) # prints all keys  
  9.   
  10. for item in player.keys():   
  11.   print(item) # prints all keys  
  12.   
  13. for item in player.values():  
  14.   print(item) # prints all values  
  15.   
  16. for item in player.items():  
  17.   print(item) # prints key and value as tuple  
  18.   
  19. for key, value in player.items():  
  20.   print(key, value) # prints key and value using unpacking  

range

 
range is an iterable object in Python used to generate a range of numbers. It is commonly used in loops and to generate a list. Range accepts 3 input parameters: start, stop and step over with the 2nd and 3rd optional.
  1. for item in range(10):  
  2.   print('python'# prints python 10 times  
  3.   
  4. for item in range(0,10,1):  
  5.     print('hello'# prints hello 10 times  
  6.   
  7. for item in range(0102):  
  8.     print('hii'# prints hii 5 times   
  9.   
  10. for item in range(100, -1):  
  11.     print(item) # prints in reverse order  
  12.   
  13. print(list(range(10))) # generates a list of 10 items  

enumerate

 
enumerate is useful when we need the index of the iterator while looping.
  1. for key, value in enumerate(range(10)): # using unpacking techique   
  2.   print(f'key is {key} and value is {value}'# prints key and value at the same time  
That’s all for today. I will cover up the remaining parts of loops and functions to finish off with the Python fundamentals. Another day spent well πŸ˜„ Another small step taken towards my goal of learning Python.

Hope you are enjoying this series and extracting some value out of it. I have already received lots of love from the community. Thank for the support. It means a lot.

Have a good one!

The article first appeared here https://tabandspace.com/posts/30-days-of-python-5 


Similar Articles