veer

Priority Queue: A Beginner’s Guide

Prerequisites

To learn about Priority Queue, you must know:

  1. Python 3
  2. Linear Queue
  3. Basic Python data structure concepts – lists, tuples

What is a priority queue?

Before you go ahead and read this tutorial, I highly recommend you to read the previous tutorial on Queues and Circular Queues as it will give you a better foundation and help you grasp the the content here.

What would you do if you wanted to track the least played songs in your playlist? The easiest solution would be to sort the list but that is time-consuming and wasteful. You only have to keep track of the song with the least hits. A min heap or priority queue helps you do this.

Priority Queues, also known as heap queues, are abstract data structures. Heaps are binary trees where every parent node has a value less than or equal to any of its children. In other words, this type of queue keeps track of the minimum value. Thus it helps retrieve the minimum value at all times. For this reason, it is also referred to as min heap. Thus, position 0 holds the smallest/minimum value. There is also a max heap whose operation is quite similar.

Note: heap queues or priority queues don’t sort lists in ascending order. It just keeps the smallest element in its 0th position. The rest of the elements may or may not be sorted.

How To Implement Priority Queue

To use priority queue, you will have to import the heapq library. This is done as follows:

import heapq

The following heap commands can be performed once the heapq module is imported:

  1. heapify() – this operation enables you to convert a regular list to a heap. On performing this operation, the smallest element gets pushed to position 0.
h = [5,2,6,8,0,1,2,4]
heapq.heapify(h) #returns [0, 2, 1, 4, 5, 6, 2, 8]

Note: Only the first element is in its correct sorted position.

  1. heapq.heappush(heap, item) – this operation pushes an element into a heap. Heap refers to the name of the heap and item refers to the item to be added to the heap. For instance:
heapq.heappush(h,7)
print(h) #[0, 2, 1, 4, 5, 6, 2, 8, 7]

Try adding a negative number and observe what happens.

  1. heapq.heappop(heap) – this operation is used to return the smallest element in the heap. Heap refers to the name of the heap.
heapq.heappop(h) #returns 0
  1. heapq.heappushpop(heap, item) – as the name suggests this command adds an item to the heap and returns the smallest number. This single command is much more efficient than a heappush() command followed by heappop() command.
heapq.heappushpop(h,3) #returns 0
print(h) #prints [1, 2, 2, 4, 5, 6, 3, 8, 7]

If you try the above command with a number smaller than the min value of heap, you will notice that the same element gets popped. For instance:

heapq.heappushpop(h,0) #returns 0 print(h) #prints [1, 2, 2, 4, 5, 6, 3, 8, 7]

  1. heapq.heapreplace(heap, item) -the above issue can be solved by executing this operation as it returns the smallest element and then adds the new element.
heapq.heapreplace(h,0) #returns 1
print(h) #prints [0, 2, 2, 4, 5, 6, 3, 8, 7]

The above-mentioned commands are the main ones you will use when dealing with heaps but there are also other general commands like merge(), nlargest() and nsmallest(). You can explore these on your own!

Applications

Priority Queues are widely used in different fields such as Artificial Intelligence, Statistics, Operating systems and in graphs.

Conclusion

Try solving the music player problem discussed in the introduction. You will need to heapify a list of tuples where each tuple should look like (number of hits, songid, name of the song). The heapify command will track the min according to the first element of the tuple which is why the first element of the tuple is the number of hits. Post your answers below. That’s it for this tutorial. Happy Pythoning!

Python Starter Tips: Beginner’s Guide to Writing Simple and Effective Code

Getting started with Python

If you are new to Python, chances are that you will find this post quite useful. Here you will learn about some common Python starter tips and tricks that will enable you to write simple and efficient code.

Python version 3.5.2 was used to create this tutorial.

List initialization

Lists are one of the most frequently used data structures in Python. If you have declared lists in the past, you would have done something like this:

alist = list()

              (or) 

            alist = []

If you want to initialize alist to five 0s, you would have done this:

alist = [0,0,0,0,0]

The above mentioned way works well enough for short lists, but what if you wanted to initialize a list to twenty 0s? Typing 0 twenty times would not be an efficient way. So instead, you can write something like this:

alist = [0] * 20

print(alist)

Output: [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

Randint Command

Often you will be required to generate random numbers. Python has made this very easy by introducing the randint command. This command selects a number at random from the range you specify, making the process quick and simple. Randint needs to be imported from the ‘random’ library, which can be done like this:

from random import randint

The syntax for using randint is:

randint(<from_range>,<to_range>)

As an example, if you want to print random integers between 0 and 9 (both inclusive), it would be done like this:

from random import randint 

print(randint(0, 9))

Output: prints an integer between 0 and 9

Note that every time you execute the above command, you will get a different integer between 0 and 9.

Type Command

When you receive inputs from users or process inputs from other programs, it’s very useful to know the datatype of the input that you are dealing with. This gives you better control over the operations that you can perform. The type command identifies the datatype of a variable.

The syntax looks like this:

type(<variable_name>)

For instance, if you have a variable named alist which is a list, then executing the below command would return:

alist = list()

type(alist)

Output: <class 'list'>

Strip Command

This is a very useful command that formats inputs that are received in the form of strings. The strip command removes the spaces that are present before and after a string. The syntax is:

<string>.strip()

For example, if you want to strip spaces before and after in a string, it should be done like this:

sample = “   Python “

sample.strip()

Output: Python

Note: only spaces before and after are removed and not the spaces in between two words. For example:

sample = “      I love Python       “

sample.strip()

Output: “I love Python”

There are many more operations that can be performed using lstrip/rstrip commands like stripping on the left/right side of the string respectively. Be sure to explore further on your own!

Counting 

I am sure you will be familiar with counting forward using the for keyword, which looks like this:

for i in range(0,5):

print(i)

Output: prints 0,1,2,3,4

However, there is more to the for keyword. It also enables you to count in steps and even in reverse. The syntax is as follows:

for i in range (<from_value>,<to_value>,<step>):

print(i)

For example, if you want to count every second number between 0 and 10, it should be written as follows:

for i in range(0,10,2):

print(i)

Output: prints 0,2,4,6,8

The above command will print 0,2,4,6,8. Note that if the step is not specified, it is taken to be 1 by default.

To count in reverse, the command is as follows:

for i in range(10,0,-1):

print(i)

Output: prints 10,9,8,7,6,5,4,3,2,1

If the step is specified as -2, then the above command would print 10,8,6,4,2.

General Tips

A few other general tips:

  • Comment – write comments wherever possible as this will help you and others to understand the code better. Single line comments can be written as follows:
#<Single line comment>

Paragraph comments can be written as below:

“”” 

<Paragraph comment>

“””
  • Naming conventions – Take extra care in using relevant names while naming variables. Specifying the datatype in the name will be extra helpful when someone else reads your code. If you are initializing a string called “first name”, be sure to include the data type in the name like “strFirstName”. This way anyone reading your code will immediately understand that the variable “strFirstName” is of the type string.
  • Line number – If you are using Python IDLE, be sure to use the ALT+G command to get to a particular line. This helps in tracking a line based on line number and can be a lifesaver when you have several lines of code and an error is thrown.

Conclusion

These are a few handpicked tips from Python and hopefully these make coding a little easier for you. There is so much more to learn as Python has an ocean of libraries that make coding extremely simple. So keep exploring and happy Pythoning!

List in Python: How To Implement in Place Reversal

Prerequisites

To learn about in place list reversal, you should know the following:

  1. Python 3
  2. Python data structures – Lists
  3. Swapping values

What is in place list reversal?

In the previous posts, you might have learned how to read a list in reverse in Python which is quite fun. You can check this out here. However, the motive of this tutorial is quite different. We are not going to read a list in reverse but we are going to change an existing list to its reversed self. Note that this is a language agnostic approach.

Let’s look at an example:

alist = [1,2,3,4,5,6,7]

print(alist[::-1]) #prints [7,6,5,4,3,2,1]

print(alist) #prints [1,2,3,4,5,6,7]

So you are merely reading alist in the reverse order when you do alist[::-1]. What we want to achieve is to make alist = [7,6,5,4,3,2,1].

How to implement this?

The idea behind this is to use two pointers, left and right. The left pointer points to the first index of the list and the right pointer points to the last index of the list. Now we swap the elements pointed to by these pointers. Then, we move the pointer to the next indices. The terminating condition of this would be when the left pointer equals or crosses over the right pointer. Let us see this using an example:

Round alist left right alist after swapping
1 [1,2,3,4,5,6,7] 1 [0] 7 [6] [7,2,3,4,5,6,1]
2 [7,2,3,4,5,6,1] 2[1] 6[5] [7,6,3,4,5,2,1]
3 [7,2,3,4,5,6,1] 3[2] 5[4] [7,6,5,4,3,2,1]
4 [7,6,5,4,3,2,1] 4[3] 4[3] Stop since left == right

As you can see, now the list is reversed.

Algorithm

  1. left pointer points to the first index and right pointer points to the last index
  2. Swap elements pointed by the left and right pointers respectively
  3. Increment the left pointer by 1 and decrement the right pointer by 1
  4. Check if left>= right:
    1. If no, repeat steps 2-4
    2. If yes, stop. The list reversal is complete

Note: Although this algorithm is explained for lists, you can use this on strings as well. In that case, you might have to convert the string to a list by typecasting it. Do not forget to reconstruct the string back from the list format. This can be done by using some of the formatting commands like replace().

Code

def reverse(alist):

   #intializing pointers
   left = 0
   right = len(alist)-1

   #condition for termination
   while left<right:

       #swapping
       temp = alist[left]
       alist[left] = alist[right]
       alist[right] = temp

       #updating pointers
       left += 1
       right -= 1

   return alist

print(reverse([1,2,3,4,5]))

Efficiency

You might think that instead of going through all this trouble, you can create a new list with reversed contents. Something like this:

alist = [1,2,3,4,5,6,7]
blist = list()
for item in alist[::-1]:
blist.append(item)
print(blist) #prints [7,6,5,4,3,2,1]

Although the above approach works, you are using additional memory (blist) to store the reversed list. This might be a serious concern if the number of elements in the list is large. That is when the in place reversal will come in handy. The efficiency of in place reversal is O(n) since we visit all the elements of the list at least once.

Conclusion

This is a very commonly asked interview question. Try using the same approach to solve these puzzles and comment below:

  1. Reverse the string “hello”. Output should be “olleh”
  2. Reverse the sentence “I love Python Central”. Output should be “Central Python love I”
  3. Check if “madam” is a palindrome or not

We will use this concept in future tutorials like linked list reversal. That’s it for this tutorial. Happy Pythoning!

Singly Linked List: How To Find and Remove a Node

Prerequisites

To learn about singly linked lists, you should know:

  1. Python 3
  2. OOP concepts
  3. Singly linked list – inserting a node and printing the nodes

What will we learn?

In the last tutorial, we discussed what singly linked lists are, how to add a node and how to print all the nodes. We strongly recommend you to read that first if you haven’t as we will be building off of those concepts.

This tutorial is about how to remove a node and how to know if a particular element exists in the linked list or not. Both these methods belong to the LinkedList class. Let us see these one by one.

How to find an element?

Like in most data structures, the only way to find if an element exists is by traversing the entire linked list. Note that if the linked list is sorted, we can use binary search. But here we are going to consider an unsorted linked list. The way this works is that the user will give us an element and we return True if we find the element else we return False. You can also use a counter and return the index of the element if it exists.

Algorithm

  1. Set a pointer curr to the head
  2. Compare curr.data to the input value:
    1. If equal, return True
    2. Else, move to the next pointer
  3. Repeat steps 1-2 until the element is found or the end of the linked list is met

Code

def findNode(self,value):

       curr = self.head
       while curr:
           if curr.getData() == value:
               return True
           curr = curr.getNextNode()
       return False

How to remove nodes from singly linked lists?

Now that you know how to find a node, we can use this to remove a node. Again, there are several approaches to do this. You can remove the first node or you can remove the last node by maintaining a tail pointer that points to the last node of the linked list. The approach we are discussing here is that we get a value from the user, find the element in the linked list and remove it if it exists. It is very important to let the user know if the element was successfully removed. For this purpose, we return True for success and False otherwise. Remember to decrement the size attribute by 1.

Let us call the node to be deleted as the current node. The idea is to link the previous node’s next to point to the current node’s next node. For example, let us say we want to delete 4 from the given linked list:

Linked list: H-->3-->4-->5 

Remove 4: H-->3-->5

We made the 3’s next node point to 4’s next node which is 5.

Let us say we want to delete 3

Remove 3: H-->5

We made the head pointer to point to 3’s next which is 5.

Note: To do make a connection between the previous node and the current node’s next node, it is important to keep track of the previous node.

Algorithm

  1. Have two pointers:
    1. curr – Initially points to head
    2. prev – initially points to None
  1. If inputted value matches the data of curr:
    1. Check prev exists:
      1. If yes, set next node of prev to next node of curr
      2. If no, simply point the head to next node of curr (this happens when you want to delete the first node)
      3. Decrement size by 1
      4. Return True
  2. If inputted value doesn’t match the data of curr:
    1. Proceed to next node by:
      1. Pointing prev to curr
      2. Pointing curr to next node of curr
  3. Repeat steps 1-3 till the end of the linked list
  4. If the end of the linked list is reached, return False indicating no element in the linked list matches the inputted value

Code

def removeNode(self,value):

        prev = None
        curr = self.head
        while curr:
            if curr.getData() == value:
                if prev:
                    prev.setNextNode(curr.getNextNode())
                else:
                    self.head = curr.getNextNode()
                return True
                    
            prev = curr
            curr = curr.getNextNode()
            
        return False

Conclusion

That’s it for this tutorial. In the future tutorials, we will see how to reverse a singly linked list. Happy Pythoning!

How To Reverse a Singly Linked List

Prerequisites

To learn how to reverse singly linked lists, you should know:

  1. Python 3
  2. Python data structures – List
  3. In place list reversal
  4. OOP concepts
  5. Part 1  and Part 2 singly linked list

What will we learn?

In the last tutorials, we discussed what singly linked lists are, how to add a node, how to print all the nodes and how to remove a node. We strongly recommend you to read these first if you haven’t yet as we will be building off of those concepts.

This tutorial covers how to reverse a linked list. As discussed in the previous tutorial, you can perform an in place reversal by swapping the last and the first values and so on. But here we are going to discuss a different approach. The idea is to reverse the links. So 4–>2–>3 (head points to 4 , 3 points to None) will become 4<–2<–3 (head points to 3 , 4 points to None). This can be done iteratively and recursively.

We will keep track of three things: the current element, the previous element, and the next element. This is because once we reverse the link between the previous node and current node, we won’t be able to move to the next node of the current. That is why it becomes mandatory to track the next node of the current. Let us see this using an example:

Linked list prev curr nex After reversal
(h)4–>2–>3(None) None 4 2 (None)4–>2–>3
(None)4–>2–>3 4 2 3 (None)4<–2–>3
(None)4<–2–>3 2 3 None (None)4<–2<–3
(None)4<–2<–3 3 None None (None)4<–2<–3(h)


Note:
 In the end, we point head pointer to the previous node.

How to implement this?

Now that you have a good handle on the linked list reversal, let’s take a look at the related algorithm and code.

Iterative method

Algorithm

  1. Set previous as Nonecurrent as head and next as the next node of current
  2. Iterate through the linked list until current is None (this is the loop’s exit condition)
  3. During each iteration, set the next node of current to previous
  4. Then, set previous as currentcurrent as next and next as its next node (this is the loop’s iteration process)
  5. Once the current becomes None, set the head pointer to the previous node.

Code

def reverseList(list):

       #Initializing values
       prev = None
       curr = list.head
       nex = curr.getNextNode()
  
       #looping
       while curr:
           #reversing the link
           curr.setNextNode(prev)     

           #moving to next node      
           prev = curr
           curr = nex
           if nex:
               nex = nex.getNextNode()

       #initializing head
       list.head = prev

Recursive method

Algorithm

  1. Pass the head pointer to this method as node.
  2. Check if the next node of node is None:
    1. If yes, this indicates that we have reached the end of the linked list. Set the head  pointer to this node
    2. If no, pass the next node of node to the reverse method
  3. Once the last node is reached, the reversing happens.

Code

def reverse(self,node):

       if node.getNextNode() == None:
           self.head = node
           return
       self.reverse(node.getNextNode())
       temp = node.getNextNode()
       temp.setNextNode(node)
       node.setNextNode(None)

Conclusion

Try to solve the above problem using in place reversal as well. The reversal serves as the base for solving other problems associated with linked lists which we will see in the future tutorials. Happy Pythoning!

Singly Linked List: How To Insert and Print Node

Prerequisites

To learn about a singly linked list, you should know:

  1. Python 3
  2. OOP concepts

What are singly linked lists?

In this tutorial, we will learn about what singly linked lists are and some very basic operations that can be performed on them.

Before we get into the details of what singly lists are, we must learn what nodes are. This is because nodes are the building blocks of a linked list. A node consists of two parts:

  1. Data part – contains the data
  2. Address part – this is pointer that points to location of the next node

In a singly linked list, each node’s address part contains the information about the location of the next node. This forms a series of chain or links. The first node of the linked list is kept track by the head pointer. The last node points to None.

Let us see the following diagram to understand this better:
What are singly linked lists

Note: In the above figure, the last element 1 points to None. Even though these nodes are drawn contiguous to each other, in reality, they may or may not be in contiguous memory locations.

Check out this animation for the visualization of the working of a linked list.

Tip: Always try to draw these data structures to get a clear understanding.

How to create a Singly Linked List?

Creating classes

Firstly, you must create a node in order to create a singly linked list. To do this, we create a class Node with data and nextNode attributes. As discussed earlier, the data attribute will contain the data and the nextNode will simply point to the next node in the linked list. We will make the default value of nextNode to be None. You can use getter and setter methods to do this.

Now that the Node class is created, it is time to create the LinkedList class. This has only one attribute, head. By default, this will point to None. If the head points to None it means that the linked list is empty. To keep track of the number of nodes in the linked list, we can add a size attribute to the LinkedList class and default it to 0.

Inserting a Node

This is a method of the LinkedList class. Remember, to make the coding simple and efficient we will always add the new node to the beginning of the linked list. In other words, the head will always point to the most recently added node. If we add the new node to the end of the list, we need to do the extra work of finding the end of the list and then adding it. This is a wasteful operation. However, if you maintain another pointer, let’s call it the tail pointer such that it points to the last node, this can be done. You can insert a new node anywhere in the linked list. We have discussed the former approach i.e insertion at the beginning of the linked list.

Let’s say we need to add 7 to a linked list, we need to do the following steps:

  1. Create a node object with 7 as the data and the next node pointing to head node
  2. Point the head pointer to this new node

Finally, increment the size attribute by 1. It is always a good practice to return True if insertion was successful. This way the user knows what is happening.

Print Nodes

This is a method of the LinkedList class. To print the data present in all the nodes of the linked list, we need to traverse one node at a time and print each node’s data part.

Coding a Singly Linked List

class Node:

   def __init__(self,data,nextNode=None):
       self.data = data
       self.nextNode = nextNode

   def getData(self):
       return self.data

   def setData(self,val):
       self.data = val

   def getNextNode(self):
       return self.nextNode

   def setNextNode(self,val):
       self.nextNode = val

class LinkedList:

   def __init__(self,head = None):
       self.head = head
       self.size = 0

   def getSize(self):
       return self.size

   def addNode(self,data):
       newNode = Node(data,self.head)
       self.head = newNode
       self.size+=1
       return True
       
   def printNode(self):
       curr = self.head
       while curr:
           print(curr.data)
           curr = curr.getNextNode()

myList = LinkedList()
print("Inserting")
print(myList.addNode(5))
print(myList.addNode(15))
print(myList.addNode(25))
print("Printing")
myList.printNode()
print("Size")
print(myList.getSize())

What are the advantages and disadvantages of Singly Linked Lists?

Advantages

  1. It’s a dynamic data structure in which insertion and deletion are simple as we don’t need to shift the elements. Just updating the next pointer will do the job for us.
  2. Stack and Queue data structures can be easily implemented using linked lists.

Disadvantages

  1. Additional memory is used up by the next pointers.
  2. Random access is not possible. You must traverse the linked list from the beginning to get to a particular node.

Conclusion

That’s it for this tutorial. In the future tutorials, we will see how to remove an element from the linked list, how to find if an element exists in the linked list etc. Happy Pythoning!

What is python used for: Beginner’s Guide to python

Prerequisites

If you’re looking forward to learning python, chances are that you will find this post quite useful. Here you will learn about Python. What it is used for? where to learn it?

To know more about any language, you need to know a little bit about its history. by knowing its history you will know a lot about language main focus and it’s development directions.

Python is one of the most popular programming languages used according to the StackOverflow 2019 survey. In this article, we will know more about

  • The History of python
  • How long does it take to learn
  • The main usage of python
  • Where to learn python for free

Programming language popularity chart according to StackOverflow 2019 survey

History of python

Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991. Guido’s goal of python is to be open-source and interactive programming language. He wanted to encourage other developers to use it. Python is based on C Language, which helps python in performance. CPython’s goal is to translate a Python script into C and make direct C-level API calls into the interpreter. Python’s code readability makes it useful for long term projects. It is a good choice for different companies. And beyond the usage of python in large business projects, developers started to use python for side projects. Now you know the main goal of python. Python focus on readability, performance. Python supports different operating systems. Let’s start looking at its main usage.

The main usage of python

The support of multiple programming paradigms object-oriented and functional programming and the huge community behind are helping the language to be adapted in different development fields. Let’s talk more about Python’s popular usage.

Web development

In Web development there are a lot of programming languages options.  Python is widly adoabted in web development with frameworks like Django, Flask and Pyramid. Or with scrapping tools  like scrappy, BeautifulSoup4 that fetch the data from different websites.

Django is the biggest python web framework. It’s an MVC (model-view-controller) framework that encourages rapid development. it provides well-structured files with standard architecture. Django gives you out of the box project:

  • Scalable architecture with a lot of customizations.
  • A settings module that contains project configurations.
  • ORM (object-relational mapper) that translates your python code into SQL.
  • Admin portal with a user management system.
  • Template engine for HTML rendering.
  • Built-in form validation.
  • Vulnerabilities prevention like (SQL injection, cross-site scripting, clickjacking, and password management )

You can know more about Django in our introduction to Django.

Flask is a microframework, it called that because it doesn’t require particular tools or libraries to be installed. It has no default database or form validation, you have full control over the project architecture. You can add the tools according to your needs. Flask is a quick solution for big projects or micro-services based projects. This does not mean that Flask is not a good option for scalable projects. Flask meant to be an easy choice for

  • Projects that need detailed customization
  • Microservices systems.
  • Creating web applications quickly with the minimum amount of configurations.

Note: We did a full comparison between Django and other frameworks in the previous article. Python usage isn’t just for building web applications only, other fields like machine learning and data science.

Machine Learning and Data Science

Python is very good at resources management (RAM, CPU, and GPU). Data scientist & Machine learning engineers are using it With libraries like:

  • Tensor flow, an end to end python platform for machine learning.  it handles complex computations. it used in NLP, voice recognition with an out of the box user-friendly responses.
  • Pytorch,  A production-ready machine learning library. It takes advantage of machine CPU and GPU to enable applications to accelerate the calculations
  • NumPy, Python’s most popular library for complex mathematical operations. It has a lot of linear algebra equations like Fourier transformation.

Data science and Machine learning are heavily used recently in academic researches and in companies. You need a good Mathematical background and you’re ready to start learning it.

Automation scripts

DevOps and security engineers are using it to write automation scripts to help them in their daily work. check our article about using boto with python for access AWS services

You can use it in almost all kinds of applications except mobile and gaming it’s not good at it.

How long does it take to learn?

Apparently, the time of learning a new language isn’t fixed for everyone. It was designed to be human-readable like English. we can say that it could take about 2 weeks to learn it’s basics and start using it.

Here is an example of python syntax

# define variables
language = "english"

# check type the type
type(language)  # str

# python boolean
is_readable = True

# List Data structure
numbers = [1, 2, 3, 4, 5]

# conditional statment
If language == "english":
   print("Welcome to english language")
else:
   print("Invalid language")

# iteration and for loop
for num in numbers:
    print("current number is : ", num)

# we can use ptyhon funtions to isolate logic
def get_number_type(number):
    if number % 2 == 0:
       return "Even number"
    else:
       return "Odd number"

# calling function

number_type = get_number_type(2)
print(number_type)
# Output : Even number

number_type = get_number_type(3)
print(number_type)
# Output : Odd number

The above code was an example of easy to read Python code. that’s why Python is easy to learn. check out tips for clean python code.

Where to learn python for free?

There are tons of resources to learn it for free, we will list the best learning resources.

  • Documentation docs tutorial
  • Udacity Course Introduction to python programming
  • Coursera Specialization Python for everybody
  • Tutorialspoint tutorial
  • W3Schools tutorial
  • Sololearn course

Conclusion

From the above explanation, it must be clear that you can use python with different applications. There is a wide usage of python in different industries and fields. it’s compatible with all operating systems. It is a good start if you want to start your career with programming.  Python is a very useful tool to use as a mathematician who wants a couple of scripts in his daily work. And if you are looking for scalable web application python is a good choice too.

how to call a function in python Guide

In this article, we will know how to call a function in Python.  You should have Python installed in your machine. You should know the basics of  Python syntax.  if you don’t check our installation guide and get started guide.

Content

  • How to create a function in Python
  • What are the scopes in Python
  • How to call a function in python

In a previous article, we talked more about Python and how it supports many paradigms. One of these Paradigms is a function. The functional programming paradigm is one of the most popular paradigms. Many languages support this paradigm. The functional paradigm in a nutshell is isolating logic into functions. You can call these functions anywhere. What are the benefits of this paradigm?

It helps the code to be easy to read and maintain. Each function performs a single job. This makes it easy to reuse the different functions in different places in the code. It helps to maintain and change business logic easily without the need to refactor the whole code.

How to create a function in Python

Defining a function in Python can be done by adding the def keyword. Python will know that this logic will be inside this function. The variables will be accessible inside the function only. This called scope. we will talk more about it in the next section. Let’s define a function.

def func_name():
    """
    Here is a docstring for the fucntion.
    """
    return True

The above code describes how to define a function in Python. It has the def keyword to tell Python that the next name is a function name. The next part is func_name()the name of the function. It has brackets to accept arguments you need to pass it to this function. The docstring part is a free text area that explains what this function is doing. The final part is the return keyword. It has the value you need to return from the function.

The above was a very simple example of a function. Let’s try to start with more complex examples.

def sum_static():
    return 1 + 2

def sum_dynamic(x, y):
    return x + y

def welcome_msg(name):
    welcome_text = "Dear {name} welcome to our guide to python functions".format(name=name)
    return welcome_text

def check_type(number):
    """
    Function that detrimine the type of integer
    """
    if not isinstance(number, int):
        return "Invalid number"
    if number % 2 == 0:
        return "Even"
    else:
        return "Odd"

def dictify(key, value):
    """
    Return a dict {key: value}
    """
    data = dict()
    data[str(key)] = value
    return data

In the above, we have a couple of functions with different usage and complexity. Le’s explain them.

In the first sun_static function, it’s a static function that doesn’t take any parameters. It will always return the summation of 1 and 2. Python functions can accept parameters. The goal of these parameters is to make Python functions dynamic. In the second sum_dynamic accept two parameters x and y. If you passed them to the function it’ll add them and return the result. The Third function has more complicated logic it’ll return a welcome message with the name argument. In this function, we defined a variable welcome_text. This variable is only in the scope of this function. We need to know more about scopes in Python.

What is the scope in Python?

The scope or it can be called a namespace in Python is the area of this variable effect. In a more simple way. It’s the space that if you called this variable it’ll be valid. This means that the variable defined inside the functions is accessible only inside the function. If you tried to call it outside the function it’ll raise an exception. The below diagram explain the types of namespaces in Python.

What is the scope in Python

This means that in our welcome_msg function the welcome_text variable can’t be called outside the function. Let’s see an example.

language = "python"

def welcome_msg(name):
    welcome_text = "Dear {name} welcome to our guide to {language} functions"
    welcome_text.format(name=name, language=language)
    return welcome_text

The language variable can be called inside the function.

To continue with the other functions examples. In previous functions, we didn’t add logic. It was returning a text. In the check_type function, we added conditions to check the type of the number.

The function should have a single goal this requires to validate the function inputs. It’s a necessary part of any function to avoid unwanted behavior. Without the checking type of input, the user can pass a string or a dictionary. The code will try to divide it by 2 it’ll raise an exception. Adding instance type validation will help make this function usable.

The return statement in Python functions can return any type of data. This is what we added in the dictify function. The  Function returns a Python dictionary. This makes it easy to assign the return result of the function to a variable and work with it. Now Let’s call the functions we created and see it’s output.

How to call a function in python

To call a function in python simply mention the function. This will invoke the function logic and return the result. let’s call the above functions.

# print the falue of sum_static
print(sum_static())

# output:
3


x = 2
y = 2

# Passing arguments to the function 
result = sum_dynamic(x, y)
print(result)

# output:
4

# print the welcome message by passing name directly
result = welcome_msg("John")
print(result)

# output:
Dear John welcome to our guide to Python functions


# Apply the function logic multiple time inside a for loop 
numbers = [5, 8, 9, 87, 12, 67]
for number in numbers:
    result = check_type(number)
    print(result)

# output:
Odd
Even
Odd
Odd
Even
Odd


key = "name"
value = "John"

# assign a function to a variable and use it.
data = dictify(key, value)
print(data)
print(data[key])

# output:
{'name': 'John'}
'John'

We called the functions we created and used them in different cases.

conclusion

Python functions are extremely helpful in different Python applications. You can use it to avoid writing the same logic multiple times. A general rule if you’re writing the same code twice add it to a function and call it. To define a function in python we use def. Each function has it’s scope. This will make the variables defined inside the function not accessible outside it. To call the function you just need to write its name with proper arguments if needed. You can assign the return result to a variable and use it. check what we did in the dictify function.

How to install python on windows installation guide

Prerequisites

In this article, we will talk more about how to install python on windows. If you’re new to python. You can check our beginner guide to python to know more about its usage. In this article, we will talk about:

  • Downloading Python
  • How to install it
  • Install Python in windows OS
  • How to uninstall python

First, let’s get started with

Downloading Python

It depends on which operating system you’re using. Downloading Python is an easy process. This is one of Python’s main goal. To be easy to run, easy to install. You can download python from different resources. The official Python website is the go-to to download python. It has the download links for all operating systems. It has detailed release notes for differences between versions. You need to take a look at the release notes if you’re upgrading your python version. It’ll help you know the changes exactly.

To download python you need to

  1. Go to the download page on the official website.
  2. Select your operating system. (WindowsMacUnix)
  3. Click on the exact version you want to download. (latest version is recommended)

Your download will start automatically. Now It’s time to install Python.

Installing Python on windows

After downloading Python. Now we will install it. In this article, we gonna focus on installing python on windows. There are two ways of installing python on windows. The first one if you have Bash ubuntu installed. Bash ubuntu is an ubuntu terminal in the windows operating system. It allows you to run ubuntu commands in windows. It’s very helpful if you need a bash shell to work with. Keep in mind it’s not fully ubuntu terminal. It has some windows restrictions.

To install Python in bash ubuntu. You need first to have to download the ubuntu terminal. You can download it from the Windows store. After downloading it you will need to open the terminal. It might take some time, in the beginning, to download and install terminal necessary packages. After it finished you will find the normal ubuntu terminal. That you can run all the commands you want in it.

  1. Install dependencies.
    $ sudo apt install software-properties-common
    $ sudo add-apt-repository ppa:deadsnakes/ppa
  2. Update the OS package manager
    sudo apt update
  3. Install the latest version
    $ sudo apt install python3.8

To check python is installed. You should type the below command.

python --version

output:

Python 3.8.2

Now you have installed python successfully. Note that you installed Python in this shell. This means it’s not installed globally on the system. which means if you have a python script and tried to run this script outside the terminal. You need to run it from the shell. It’ll not run. Let’s explain why.

Your python is installed only on the Ubuntu subsystem. Ubuntu terminal is a container running in windows. It helps to translate your commands into binary system calls to Windows. By installing python. You install it on the subsystem only.

Install Python in windows OS

If you want to install python Globally on windows. You should follow these steps. After downloading Python. In your downloads, you’ll have a .exe file. Open it will open this screen.

Install Python in windows OS

You can choose to install it now. It will add the python path in your system partition. You can customize the installation path and user access.

The final step of windows installation.

After Finishing the installation. You will have the setup success screen. It’ll have links to documentation and getting start guide. After close this screen you will find a python shortcut on your desktop or windows menu. Now you can run any python script.

How to uninstall python

As you can see installing Python is easy. What about remove it. To remove Python from your device You have two options if you’re using Windows. The simplest way is:

  1. Go-to control panel
  2. Search for python
  3. Right-click and choose uninstall

This will remove python entirely from your system.

If you installed python through the ubuntu subsystem. It means that it’s not globally installed. Now You should open a new terminal window. Run the below command.

$ sudo apt remove python3.8

This will uninstall python from the subsystem. The dependencies package will be installed. This command will not delete the data files of python are still exist on your system. If you want remove it completely from your system. You should run:

$ sudo apt autoremove python3.8

This will remove python dependencies too from your system.

conclusion

Installing or uninstalling python is an easy process. Python was designed to be that from the beginning. You can install it in windows with a simple GUI. Or you can install it using the Ubuntu subsystem. Removing python as easy as installing it. You can uninstall it via the GUI or the terminal.

what is the string in python

The string is a Python data type. In this article, we will know what is the string in python, How to reverse, concatenate, and compare the string in Python. To get the most out of this article, you need to have the basic knowledge of Python. If you don’t check our intro to python here. Let’s start with what is the string in python.

What is the string in Python?

The Python string is a data type. Python doesn’t have a character data type. That’s why it has a string it’s a list of characters in Unicode representation. Python deals with string as an array of characters.

This means that you can apply all list functions to string too. Declaring a python string is very easy you can simply add the word between single or double-quotes. This will tell Python to create a list in the memory with the string length. Let’s see an example of defining a Python string.

text = 'Hello'
message = "Python string"

print(text)
print(message)

# output
'Hello'
"Python string"

The above example shows how you can define a string in python with single or double-quotes. The Python string has some functions that make use of the string. Let’s say that users registered to your application with their email. You need to validate that this the email string is lowercase. To avoid duplication in the user’s data. Python provides a built-in function lower() that convert string to lowercase.

email = "[email protected]"

print(email)
# output
'[email protected]'

print(email.lower())

# output
'[email protected]'

We mentioned that string is a list and we can execute some of the list functions to it.  This includes the reverse functionality that the list had.

How to reverse a string in Python

To reverse a string in python you need to understand that python read the string as a list of characters. The functionality of the reverse is pretty simple. First, iterate through the string. Create a new string with staring at the end of the original string. You will understand with an example.

text = 'Hello world'
new_text = ''

index = len(text)
while index > 0:
  new_text += text[index -1]
  index -= 1

print(text)
print(new_text)

# output
Hellow world
dlrow olleH

In the above code, we created an index with the length of the string. Use the loop to go through each item in the text from back to front. The final part is to add the characters to the new string and decrease the counter. This solved our problem to reverse the string. Python supports a more efficient way to reverse the string.

How to reverse a string in Python

text = 'Hello world'
new_text = text[::-1]

print(new_text)

# output
dlrow olleH

What the text[::-1] code did? It slices the string to make it starts with the length of the string and ends with a zero index. This reversed the string and stored it in the new_text string. You might have noticed in the previous example that we created an empty string and starts adding to it. This leads us to the question How to concatenate Python’s string?

Concatenate String in Python

Concatenation Python’s string is merging strings together. In a more simple explanation, if you have text_1 = “Hello” and text_2 = “world”. concatenating them will be my merging them to formulate the “Hello world”. There are many ways to concatenate strings in Python. The simplest one is using the plus signs.

text_1 = "Hello"
text_2 = "World"

print(text_1 + " " + text_2)

# output
Hello World

The more your codebase gets bigger the more you need to customize the concatenation. Python provides a couple of functions to help you concatenate the string in a more elegant and readable way. The first method is the format() function.

username = "John"

welcome_message = "Welcome {username} this is a test text".format(username=username)

print(welcome_message)

# output
Welcome John this is a test text

The format function is very handy in the large test if you needed to add spaces and you have multiple variables to add inside the text. All you need to do is to put the variable name between curly brackets. Python will get the value of this variable from the parameters passed to the format function.

The second method is using the join function.  The join function is useful if you have a list and you want to concatenate the list data to a string. Let’s take an example to understand.

full_name_parts = ['John', 'Jack', 'Watson']
full_name = "-"

full_name.join(full_name_parts)

print(full_name)

# output
John-Jack-Watson

You Can see that the join function iterated through the list and added the items to the full_name string. It added the items with a -  between them.

The third method it’s only available in python in Python 3.6 and above. It’s the f-string method. It’s a more improved version of the format function.

name = "Jack"
age = 72

f"Hi, {name}. You is {age}."

# output
'Hello, Eric. You are 74.'

The f-string method allows you to directly get the variable value in the string. If you added the f a character at the start of the string.

Compare two Python strings

Let’s assume that you have an application that stores the username. You want the username of each user to be unique. This means that you need to validate that this name is not matching any of the other registered usernames. Python provides The ability to compare strings. A basic example of this:

name = input('Enter Your Name:')

saved_name = 'Jack'

if name == saved_name:
  print('Sorry the name you entered is taken')
else:
  print('Welcome {name}'.format(name=name))


# output
Sorry the name you entered is taken

# output
Welcome John

Python compares the two string as text. This means that if the user enters a lowercase Jack name the condition will not be valid. This is very important. You need to know that Python doesn’t do automatic validation. You need to implement the validations you need manually. This was a very simple example in a more realistic example you will have a database that makes sure that the name is unique.

Conclusion

Python’s string is very handy and useful to work with. It has clear formating and contamination methods. You can work with it as a list. it supports different most of the Python list built-in functions. To reverse a Python’s string you can slice it and end with index 0. Concatenate strings in  Python provides different concatenation methods to choose from based on your need. Comparing strings in python are similar to compare two integers. You can know more about Python strings in the official documentation. You can get many more details about The string functions here.