Category: python

python if else condition and indentation – python code for if else

In this article we will see how to use if else condition in python(python3). In python everything is indeneted esepcially conditions and loops with spaces or tabs. And these spaces and tabs are uniform accross the program. If the number of spaces/tabs is violated it is a syntax error.

So this is a simple example of if else block. Note the indentation and colon. Below you can see more examples.

If Elif Else:

Now if else statement with many examples:

You can find the all the above examples in the below code:

# this program is for indentation and if else


# here i am declaring two variables

a = 5
b = 6

print("Value of a is %d, b is %d" %(a, b))

#change the above variables with many possibulites and see what it will print

#now lets test if a is greater or b is greater

#example1
print("Example1")

if( a > b):
    print("a is greater than b")
    #here you can write as many statements as you want
else:
    print("b is greater than a")
    #here you can write as many statements as you want


#in the above code block if a is greater than b then if condition will be true and the statement underneath will execute
#else statemnets under else will be executed        


#now what if there are many if conditions for ex: a>b, a<b, a==b etc


#example2
print("Example2")

if ( a > b):
    print("a is greater than b")
    #here you can write as many statements as you want
elif (a < b):
    print("b is greater than a")
    #here you can write as many statements as you want
else:
    print(" both are equal")
    #here you can write as many statements as you want

#example3
print("Example3")
    
if ( a > b):
    print("a is greater than b")
    #here you can write as many statements as you want
elif (a < b):
    print("b is greater than a")
elif(a == b):
    print("a and b are equal")
    #here you can write as many statements as you want
else:
    print("all the conditions failed")
    #here you can write as many statements as you want

#example4 more complex if else statements

name = 'Manisha'
salary = 10000    #change this value and play with it

print("Example4")
if(salary > 50000):
    print("Salary of %s is %d" %(name,salary))
    print("So she will buy a car")
    print("She will buy a house")
    print("She will not give parties")
else:
    print("Salary of %s is %d" %(name,salary))
    print("She will try for new job")
    print("She will not give parties")

Finding word frequency using Collections module in Python

In this post I am going to discuss how to use Collections module in Python. In simple words collections are nothing but containers that has list, tuple, dict, set etc.

From collections I am going to explain how to use defaultdict and counter subclasses.

Let’s take a basic example:
Suppose we want to get the frequency of words from a text. We do the following.

word_frequency = {}
for words in sent.split(" "):
    if words in word_frequency:
        word_frequency[w]+=1
    else:
        word_frequency[w]=1

But using Collections module our task is more simplified.

from collections import defaultdict
word_frequency = defaultdict(int)
for words in sent.split(" "):
    word_frequency[words]+=1

Using Counter from Collections

from collections import Counter
word_frequency = Counter()
for words in sent.split(" "):
    word_frequency[words]+=1

For more understanding of how this module works visit /https://stackabuse.com/introduction-to-pythons-collections-module/.
Also if you have any doubts or questions please comment on this post so that I can get back to you.

Simple Python program to find the sum of prime numbers between two given digits

In this post I will explain you how to find if a number is prime or not and then add the prime numbers between two given numbers.

First of all let us check if a number is prime or not:

def checkPrime(n):
     flag = 0
     for j in range(2,n):
         #print(n,j)
         if(n%j == 0):
             flag = 1
     #print(flag)
     if(flag == 1):
         return 0
     else:
         return n

As you can see this subroutine does the job of checking if a number is prime or not. If we are good at Math then this logic is pretty simple. But still let me explain, a prime number is the one that is divisible by 1 and itself. So simply we need to find a number when divided by any number lower than it gives a reminder equal to zero which means it is divisble by that number.

In our subroutine the part if(n%j ==0) does the same. And now the remaining portion of adding all the prime numbers between two given numbers.

#program to find sum of primes between two given numbers
 def checkPrime(n):
     flag = 0
     for j in range(2,n):
         #print(n,j)
         if(n%j == 0):
             flag = 1
     #print(flag)
     if(flag == 1):
         return 0
     else:
         return n
 #execution starts from here
 a = int(input("Enter first number: "))
 b = int(input("Enter second number: "))
 total = 0 #variable to store sum of primes
 for i in range(a,b):
     res = checkPrime(i)
     total += res
 print(total)

In the rest of the program we take user input and check the primes between those numbers and add them up to get result.

If you have any doubts don’t forget to comment.

Simple calculator program using Python3

In this post we are going to learn how to use Python’s while loop, if conditioning, break, taking input from user.

Well that seems a lot, but its all simple when you look at the program.

#subroutine to calculate addition and subtraction by taking user choice as input
 def operate(o):
     #convert user input into integer
     a = int(input("enter first number "))
     b = int(input("enter second number "))
     if(o == "a"):
         return a+b
     elif(o == "s"):
         return a-b
 #execution starts from here
 operation = input("Enter your choice: ")
 total = 0
 while(operation!=""):
     if(operation == "a"):
         print("you choose addition")
         total = operate(operation)
     elif(operation == "s"):
         print("you choose substraction")
         total = operate(operation)
     else:
         print("you choose nothing")
     #print the actual result
     print("Result = ",total)
     #choice of user which decided whether to continue or not
     choice = input("Do you want to continue?Type Y to continue or any other key to quit: ")
     if(choice == "y"):
         operation = input("Enter your choice: ")
     else:
         break

For easier understanding let me explain it to you in the form of algorithm.

  • Execution starts from asking user the input.
  • Then using if condition we check what type of operation the user has chosen.
  • Then according to the operation we call the subroutine and result is returned.
  • At the end we ask the user once more if the user wants to continue or exit.

If any doubts or needed clarifications don’t forget to comment.

Finding last element in array – Check if current element is last element in Python arrays

When we are using loops in Python we might fumble onto a situation where we have to check if we reached the end of the array or simply say that we are iterating through each element in array and checking if the current element exists in a hash/dictionary/database and upon a match we still want to continue until the end of the array is reached.

So there are multiple ways of achieving this but I am going to give a simple solution that is easier to understand.

for suffix in suffixes:
        if(re.search(suffix+'

So the line that checks for the last element of array is

        elif(suffix == suffixes[-1]):

Similarily, to access for last but second element use suffixes[-2] and so on.

Hope its useful.

, my_string)):
#do something
elif(suffix == suffixes[1]):
print(“reached end of array”)
So the line that checks for the last element of array is







					

python capture regex groups in variables

The below snippet is useful when we have a string and we want to save the pattern in a variable. We can do this using regex, i.e we can capture groups in regex and then access them later using variables,

This is how it is done.

#python script to capture regex matched groups into variables
import re

suffix = 'en'
word = 'children'

#print(word,suffix)

m = re.search(r'(.*)'+suffix + '

, word)

print(m.group(1))

What is a hash or a dictionary in Python? Understanding hashes.

Hash tables or Dictionaries(as referred to in Python) are associative arrays. From Wikipedia associative arrays are defined as a collection of key, value pairs such that each key appears at most once in the hash table.
Question: Why can’t we use arrays?

Answer: Because, when we use arrays its difficult to find an element in the array since the searching will loop through all the elements in the array until the element is found.

This will compromise efficiency if the array is large in size. This problem is solved in hash table as elements can be accessed quickly without looping through the entire array.

Okay lets dig deeper…

A real life example:

I am going to explain this one with an example that we see daily. In this example we are going to store all members of a family relations and their names in a hash.

So the hash name is family_dict = {}

I am listing out all the elements I am going to store in it. It is going to contain wife, son, daughter, friend, father, mother….

All these relations have a name that we can call with. Now to build a hash we need keys and values. Identifying keys and values is the important thing because ultimately it will satisfy our need to use hash data structure.

In our hash we are going to store relations and their names. Before that one thing we all need to keep in mind while we build  a hash is that keys should be unique and values we will not care about them until there is really a need.

So our family hash needs unique things as keys. Names can’t be unique as many people can be named with same name.

This is as simple as that. Therefore, our hash is going to contain relations as keys and names as its corresponding values.

A doubt:

Now there will be a question what if our relations can also be same like when we have many brothers/sisters. Simply we are going to manipulate our keys are brother1, sister2 to make them unique. Enough of theory now and we will start our implementation.

family_dict = {
  "me": "Mr.x",
  "father": "Mr.y",
  "mother": "Mrs.z",
  "son":"kid1",
  "daughter1":"d1"
  "daughter2":"d2",
  "wife":"w1"
}

This seems simple. Each element mapped to its corresponding value. Now think of a situation where we might need to point same key to many values.

For it lets assume Mr.x is a bit cheeky and has another wife w2. One just can’t put two wives in same house. So in computers what happens is when you add same key with different value like “wife”:”w2″. 

Our hash would store only one key that would be the one added last. That is previous keys are forgotten or overridden when same keys are added.

To solve this issue MR.x would compromise with his family and come to an agreement to put two of them in the same hut. But how do we do it here? No delay just scroll down.

family_dict = {
  "me": "Mr.x",
  "father": "Mr.y",
  "mother": "Mrs.z",
  "son":"kid1",
  "daughter1":"d1"
  "daughter2":"d2",
  "wife":"w1, w2"
}

If you observe clearly we just updated our hash key such that its value holds the previous one too. So in real time programming we should always check for existence of a key in hash if it already exists so as to make sure all our values being taken care of and none are overridden because of duplicate entry.

And this is how is is done. Now think of a hash which is going to store how many times a word occurs in the given text. For this we will store each word as a hash and its count as value. So everytime a word is revisited we will check for the value of the word and increment it by one.

    if word not in wordcount:
        wordcount[word] = 1
    else:
        wordcount[word] += 1

And finally we will print our hash:

#print the dictionary with sorted keys(words) and count as values
for k in sorted(wordcount):
    print (k, wordcount[k])

This has been a bit long post but thanks for coming here.
Bonus: Finding word frequency using Python

PDF Splitter using PyPDF2 module of Python – Split PDF into multiple pages

Often when working with a large PDF we fumble upon of a need where we need each page of the PDF in one separate  PDF file.So in this article we are exactly going to do this but not using any Linux command but using Python.

For that lets get our dependencies get installed. Just run the below command and you are all ready.

pip3 install pypdf2

Now open a editor and save the following code in to your editor.

from PyPDF2 import PdfFileWriter, PdfFileReader

inputpdf = PdfFileReader(open("largefile.pdf", "rb"))

for i in range(inputpdf.numPages):
    output = PdfFileWriter()
    output.addPage(inputpdf.getPage(i))
    with open("largefile-page%s.pdf" % i, "wb") as outputStream:
        output.write(outputStream)

Thanks to StackOverflow for this part. Thats it now you are ready to split a PDF file into multiple files with each file containing one page.

OpenNMT installation using PyTorch

Reference from OpenNMT Official Site

This manual will guide you through openNMT installation using PyTorch.

We assume that you have python3 already installed and ‘pip3’ the python3 package installer and your OS is assumed to be Linux(ideally Ubuntu)

Step1 Install PyTorch

pip3 install torch torchvision

If you are having python2 version then you may use the below command.

pip install torch torchvision

While this package downloads and installs you may have a cup of tea as this will take a while. Remember you need to have good internet connection as this package is about 582.5MB.

Step2 Clone the OpenNMT-py repository

git clone https://github.com/OpenNMT/OpenNMT-py
cd OpenNMT-py

Step3 Install required libraries

pip3 install -r requirements.txt

For python2 use

pip install -r requirements.txt

Thats it now you are ready to take off. To get familiarize about how to use openNMT follow the link

Python Mysql connection and extracting sample data

In this tutorial we are going to learn how to connect to MYSQL using python.

DB Configuration:

First of all we need a config.py that will act as a configuration file that our python script will read. This configuration file consists information of MYSQL database username and password, database name and host where the MYSQL is at.

This is how config.py will look like

server = dict(
    #serverip = 'localhost',
    dbhost = 'localhost',
    dbname = 'userdb',
    dbuser = 'root',
    dbpassword = 'root123'
)

Then the actual python script that will connect using these parameters to our db and fetch results as needed.