Pages

Wednesday, February 24, 2021

While loop in Python

While loop

While loops are used when a block of code needs to be executed as long as the specific condition is True. 

Syntax:

while condition:
    // code to be executed

Before we see the examples of while loop, Below are the couple of points to remember. 
  • If the condition is not satisfied (or False) on the first instance, code inside the loop will not be executed at all. 
  • If the condition is satisfied (or True) for every iteration, Loop will run infinitely. 
Let's have a look at the simple example. 

While loop in Python

In the above example, 
  • Line - 1: Creating or Initializing variable to use in the condition or loop. 
  • Line - 2: while 'condition', We are using condition 'i < 10'. Loop would repeat as long as the value of 'i' is less than 10. 
  • Line - 3: print statement to print the value of 'i'. This is usually replaced with the required action in the program. 
  • Line - 4: Incrementing the value of 'i' by '1'. Incrementing, Decrementing or Amending the value of the variable used in the condition is essential is most of the cases. Otherwise, there is a risk of loop running infinitely. 
We can use either True or False instead of condition. However, mentioning 'True' would cause the loop to run infinitely and 'False' would cause the loop to not run at all. 

while loop in Python

In this example, while loop will run infinitely. 

break statement

In the above example, loop is run infinitely. We can use the break statement to exit from the loop. 

No statement in the while loop is executed after the break statement.

break statement in while loop - Python

In the above example, loop would be repeated until the break statement is executed (i.e., when condition 'i == 10' is satisfied).

continue statement

break statement would terminate the loop execution. But, if we need to skip the processing for that particular iteration and continue with the loop, continue statement can be used. 

None of the following statements would be executed in that iteration and next iteration would continue normally. 

continue statement in while loop - Python

In the above example, 'print' statement would not be executed when value of 'i' becomes '5'. 

pass statement

pass statement works like a place holder if no specific operations is required and is mandatory by syntax. 


In the above example, No action is required when value of 'i' becomes '5'. We can use 'pass' statement.

else statement

Else in while loop isn't exactly same as if-else. Instead this is executed once the while loop is completed. 

else statement in while loop - Python

In the above example, statements in the else block are executed once the while loop is completed. All the numbers from 0 to 9 would be printed followed by "While loop is Completed" in else block.

One thing to remember here is 'else' part would only be executed if the while loop is executed completely and not terminated by using 'break' statement. If break statement is executed, else part wouldn't be executed.

else statement in while loop - Python

In the above example, statement in the else block would not be executed as the break statement is run.

Nested while loops

Like Nested if, while loops can be nested in other while loop. 

Nested while loops in Python

In the above example, 
  • Line - 3: First while loop is repeated as long as 'i < 3' is satisfied and loop will be terminated once i becomes '3'. 
  • Line - 4: Variable 'j' is created with '0'. This is executed for every iteration of the previous loop.
  • Line - 5: Second while loop is repeated as long as 'j < 3' is satisfied and loop will be terminated once j becomes '3'.
    • This loop is run for every iteration in the first loop. 
Result would be printed like below. 

List in Python

One thing to note here is, break and continue statements would only apply to the loop the statement is executed on (i.e., closest loop). 

break statement in Nested while loop - Python

In the above example, break statement would terminate the inner loop and outer loop would still continue normally. 

List in Python

Hope the above was a bit of help to understand the while loops in Python. 


If you have any Suggestions or Feedback, Please leave a comment below or use Contact Form.

Thursday, February 18, 2021

For loop in Python

For loop

For loops are used when a block of code needs be executed over a range or list of values. 

List of values can be a List, Tuple, Set, Dictionary or String. 

Number of times the loop is repeated is based on the number of values present in an iterable. 

Syntax:

for element in iterable

iterable refers to a range, list, tuple, set, dictionary or string. 

element refers to the element from the iterable and can be accessed in the loop using this name. 

Range

Let's have a look at a simple example of for loop over a range of numbers. 

For loop in Python over a range

In the above example, for loop is repeated 10 times (from 0 to 9) and for every occurrence number will hold the corresponding value through out the loop (i.e., on the first iteration 'number' will hold the value of '0', on second iteration 'number' will hold the value of '1'...). 

List

Let's have a look at another simple example of for loop over a list. 

For loop in Python over a list

In this example, for loop is repeated for each element in the list (new_list) and corresponding value of the element can be accessed by using 'list_element' through out the loop. 

We are able to access the elements from a list directly. There is one other way of using for loop on a list is by using range.

For loops in Python - List & Range

In the above example, Instead of repeating the for every element in the loop, we are repeating the loop on the index (by calculating the length of a list).
  • 'len' function would return the length of the list. 
  • 'index' represents the index of the list for every iteration. 
  • Elements of a list can be accessed by using index (new_list[index]).
Result of this example is same as the previous. But, this becomes helpful we are to consider index for the operation inside the loop. 

For loop over a tuple is same as list. 

Set

Let's have a look at an example of for loop over a set. Unlike List and Tuple, Set is an unordered collection of data. Data is stored in no specific order and cannot be accessed by index. 

For loop in Python over a Set

Just like for loop over a range and list, for loop is repeated for all the elements in a set. Because of the way data is stored in a set, Data returned could be in any order and the result could vary every time the program is run. 

Dictionary

Dictionary is different from other iterables due to the way data is stored (key and value combination). 

For loop on a dictionary would only return it's key. 

For loop in Python over dictionary

In the above example, for loop is repeated for every key in the dictionary and data in the dictionary can be accessed by using corresponding key. 

for loop in Python over a dictionary

String

Just like other lists, Strings are also iterable objects in Python and for loop can be used in the same way on strings as well. 

For loop in Python over a string

For strings, each character would be considered as a separate element and for loop is repeated for all the characters in the string passed. 

Nested For loops

Nested for loops can be used if we have an iterable inside another iterable. E.g.: List inside a list or String inside a List.

Let's have a look at an example using the List. 

Nested For loops in Python

In the above example,
  • Line - 2: 'new_list' is created with list of strings.
  • Line - 5: for loop is repeated for every string in the list. 
  • Line - 7: for loop is repeated for every character for every list element (string).

break statement

In all the examples we have seen, for loop is executed for all the elements in the iterable. This doesn't necessarily needed always, we can use break statement. 

Whenever break statement is executed, loop will be terminated and no further statements would be executed.

break statement in Python

In the above example, for loop is repeater over a range of 10, once the number is '5', loop will be terminated. 

continue statement

break statement would terminate the entire loop. Where as continue statement would only terminate the current iteration and continues the loop from the next iteration.

continue statement in Python

In the above example, print statement won't be executed for number '5'.

pass statement

pass statement works like a place holder if no specific operations is required and is mandatory by syntax. 

pass statement in Python

In the above example, 'pass' statement would work as a place holder to avoid any error. 

Else 

Else in for loop isn't exactly same as if-else. Instead this is executed once the for loop is completed. 

One thing to remember here is 'else' part would only be executed if the for loop is executed completely and not terminated by using 'break' statement. If break statement is executed, else part wouldn't be executed as well.

Else in for loop in Python

In the above example, else is executed once for loop is completed (after all the elements in the list).

Hope the above was a bit of help to understand the for loops in Python. 


If you have any Suggestions or Feedback, Please leave a comment below or use Contact Form.

Thursday, February 11, 2021

List Comprehension in Python

List Comprehension

List comprehension is one of the ways of creating list. List would be created as a result of some operation on a range, set or list based on some condition (optional). 

This makes the list creation easier to code and easy to understand. 

Let's have a look at an example to understand this better. 

E.g.: 

Create a list with the list of odd numbers less than 10. 

We will first see how to create a list with out list comprehension. 

Create a list with odd numbers

In the above example we are doing in four steps. 
  • Line - 1: Create an empty list by using square brackets. 
  • Line - 2: for loop on a range of numbers till 10. 
  • Line - 3: if condition to check if the number is an odd number. 
  • Line - 4: add the odd number to the list using append() method. 
Same can be done in a single statement with list comprehension. 

List comprehension in Python

We have embedded for loop and if condition inside the square brackets directly to create a list with odd numbers. 

let's break this statement and see in detail. 

odd_numbers = [number for number in range(10) if number % 2 != 0]
  • square brackets [] to create the list. Similarly {} and () can be used as well to create dictionary, set or generator. We will see more about set and dictionary comprehensions towards the end.
  • number highlighted in green indicate the value to be added to the list. This can include some arithmetic operation as well, we will see an example by using some operation.
  • for number in range(10) to loop through the range from 0 to 9. Any iterable can be used in place of range). 
  • if number % 2 != 0 condition to identify the odd number. 

Let's have a look at another example to create a list with squares of odd numbers less than 10. 

List comprehension in Python

We have replaced number with 'number * number' to calculate the square of an odd number and add to the list. This can be any expression based on the requirement. 

We have looked at creating a list by using one iterable. We can use multiple iterables at the same time to create a list (or nested lists). 

Let's have a look at the example by using two lists. 

E.g.: 

Create a list with the product of each element in a list with the elements of another list. 

List comprehension with two lists in Python

In the above example, 
  • We are using one list (even_numbers) and one tuple (odd_numbers). 
  • Two for loops to fetch each element in the list.
    • 'for even in even_numbers' would be considered as the first for loop and for every even number in the list second loop would be repeated. 
    • 'for odd in odd_numbers' would loop through odd_numbers for every element from the first loop.
  • For each combination operation 'even * odd' is calculated and added to the list. 
This is same as using nested for loops with out using list comprehension. 

Nested for loops in Python

Both these examples would return the same list [2, 6, 10, 4, 12, 20, 6, 18, 30]. 

Similarly, we can create nested list (or matrices) using the same instead of creating product. 

Nested lists using List comprehension in Python

We can also use the list comprehension to convert nested lists to a single list (matrix flattening). 

Matrix flattening in Python

In the above example, 
  • First for loop is repeated on the matrix.
  • For every list from the matrix, second for loop is repeated and returns the element.
  • element returned is added to the list created. 

List comprehension is very useful to create the lists, at the same time we need to be aware of not over using it (like using it on more number of lists). This would make this difficult to understand and maintain the code. 

One thing to remember is it becomes extremely difficult to debug when they are not working as expected, specially when we are using multiple lists.

So, it is best to decide whether to use list comprehension or not based on the functionality rather than to using it all the time.

Let's have a look at Set comprehension and Dictionary comprehension with simple examples. 

Set comprehension

Set comprehension is same as list comprehension, only difference is we use curly brackets {} instead of square brackets. Using round brackets () would create a generator not tuple, we will see more about generators in different post. 

Set comprehension in Python

Dictionary comprehension

Dictionary comprehensions are also similar to set comprehensions. Only difference is it requires the key to be added. 

Let's have a look at an example. 

Dictionary comprehension in Python

In the above example, we are considering the number in the range as a key and square of the number as corresponding value. 

We can also use dictionary with the list of keys supplied from a list. 

Dictionary comprehension in Python

In the above example, 
  • We are creating a list with the keys required to be in the dictionary. 
  • Using List comprehension to get the squares of odd numbers in the range of 10. 
  • Dictionary comprehension to loop through the list of keys and assign the output of list comprehension as a value to the key. 

Hope the above was a bit of help to understand the List comprehension in Python. 


If you have any Suggestions or Feedback, Please leave a comment below or use Contact Form.

Thursday, February 4, 2021

Case conversion in Python - Upper case, Lower case and Capitalization

Case conversion in Python

While working with strings Case conversions become essential for different reasons. Specially when we need to compare two different strings. 

There are different methods in Python to do case conversion or to check whether the string is in upper case or lower case etc. 

Let's have a look at these methods in detail.

Convert a string to upper case

Converting a string to upper case can be done by using method upper(). There is another useful method isupper() to check if a string is already in upper case or not. 

upper() method returns a string in upper case. Original string will not be changed to upper case by using this method.

Syntax: str.upper()

isupper() method returns True if a string is in upper case and False if not. 

Syntax: str.isupper()

Let's have a look at a simple example with the use of both upper() and isupper(). 

Convert a string to upper case in Python

In the above example, 
  • Line - 4: isupper() is used in if condition. If the string is in upper case it returns True. In this case, string is not in upper case so returns False. 
  • Line - 6: upper() is used in print statement. This method converts the string and returns the same and is printed by print statement. 

Converting a string to lower case

Similar to converting a string to upper case, string can be converted to lower case using the method lower() and islower() can be used to check if a string is in lower case.

lower() method returns a string in lower case. Original string will not be changed to lower case by using this method.

Syntax: str.lower()

islower() method returns True if a string is in lower case and False if not. 

Syntax: str.islower()

Let's have a look at a simple example with the use of both lower() and islower().

Converting a string to lower case in Python

In the above example, 
  • Line - 4: islower() is used in if condition. If the string is in lower case it returns True. In this case, string is not in lower case so returns False. 
  • Line - 6: lower() is used in print statement. This method converts the string and returns the same and is printed by print statement. 
Other than converting the string to upper case or lower case, there are few more conversions that can be done on Python. 
  • Capitalizing a string. 
  • Making a string as title.
  • Reversing (swap) the case of a string.
  • Case fold for case less comparison.

Capitalizing a string

What is capitalizing a string and what is the difference between converting a string to upper case and capitalizing? 

Capitalizing a string would mean, only the first letter of a string would be converted to upper case (CAPITAL) and convert the remaining letters to lower case (SMALL) irrespective of the current case of the letter. 

capitalize() method is used to capitalize a string. This method accepts no arguments and returns the capitalized form of a string. This doesn't update the original string.

Syntax:

str.capitalize()

Capitalizing a string in Python

In the above example, 
  • string_one holds a string with mixed case letters. First letter of the string would be converted to upper case and the remaining letters to lower case. 
  • string_two holds a string with all upper case letters. First letter of the string would be converted to upper case (i.e., will stay as upper case) and remaining letters would be converted to lower case.
  • string_three holds a string with all lower case letters. First letter of the string would be converted to upper case and remaining letters would be converted to lower case (i.e., will stay as lower case).

Making a string as Title

String capitalization would only make the first letter of a string as capital (or upper case) and convert the remaining letters to small (or lower case). But, Every word in a title starts with capital letter and the remaining letters in that word would be small letters. 

This can be done by using title() method. This method accepts no arguments and returns the string in Title format. 

Syntax:

str.title()

There is one important point to note here is any special character, number or blank space would be considered as separator and next letter would be converted to capital. 

This can be easily understood with below example. 

Convert a string as  Title in Python

In the above example, we are using five different scenarios. 
  • string_one holds a string with mixed case letters each word is separated by spaces. Every letter after a space would be considered as new word and first letter would be converted to upper case and the following letters to lower case. 
  • string_two and string_three hold all upper case and lower case letters accordingly with each word separated by space. Conversion of a string would be similar to string_one
  • string_four holds all lower case letters with each letter is separated by a space. In this scenario Python would consider each letter as a separate word and converts them to upper case. Result would be all upper case letters separated by a space.
  • string_five holds all upper case letters separated by a space and a number '1'. Even though there is no space in 'A1BC', Python would consider '1' as separator and leave both A and B in upper case and converts 'C' to lower case. 
Case conversion in Python

Reverse the case of a string

Reversing the case would mean converting every letter into the opposite case.
  • Upper case letter to lower case letter.
  • Lower case letter to upper case letter.
Any special characters would stay as is. 

This can be done by using the method swapcase(). This method doesn't accept any arguments and returns a string with the case reversed for each letter. This doesn't update the original string. 

Syntax:

str.swapcase()

This is a straight forward example. And, personally I haven't used this much. 

Swap case of a string in Python

Case fold for case less comparison

Case less comparison is very useful when comparing two different strings. This helps compare the two string in different cases without affecting the original strings. 

casefold() method can be used to do this. Primary purpose of this is for comparison. This method doesn't accept any arguments and returns the string in lower case. 

Syntax:

str.casefold()

Below is a simple example to show how the data is returned and comparison is done. 

case fold in Python

In the above example, 
  • string_one and string_two holds the strings with mixed case letters. casefold() returns the strings converted to lower case (all letters). 
  • Line - 7: comparing these two string by using casefold() method would convert both the string to lower case and compare. In this example, it returns True. 
Using upper() and lower() methods also would produce the same result in terms of comparison. 

Hope the above was a bit of help to understand the case conversion in Python. 


If you have any Suggestions or Feedback, Please leave a comment below or use Contact Form.

Exception Handling in Python (try - except-else-finally)

Exception Handling in Python Exception handling is key for any programming language. When an exception occurs Python interpreter stops execu...