Python - Other

Difference between except: and except Exception as e:

While the except Exception as e statement is much more in-depth, it does not deliver on catching exceptions like BaseException or some of the system-exiting exceptions like KeyboardInterrupt, SystemExit, and also GeneratorExit. However, a simple except statement can fulfill this task and catches all these exceptions.


The syntax for the simple except statement is:

try:
    # write code that may throw exception
except:
    # the code for handling the exception


While the syntax for the except Exception as e statement is:

try:
    # write code that may throw exception
except Exception as e:
    # the code for handling the exception

Drawing A Shape

print("   /|")
print("  / |")
print(" /  |")
print("/___|")
//Output :    /|
//           / |
//          /  |
//         /___|


Exponent Function

print(2**3)
//Output : 8


def raise_to_power(base_num, pow_num):
    result = 1
    for index in range(pow_num):
        result *= base_num
    return result


print(raise_to_power(2, 3))
//Output : 8

For Loop

for letter in "Giraffe Academy":
  print(letter)

//Output : G
//         i
//         r
//         a
//         f
//         f
//         e
//          
//         A
//         c
//         a
//         d
//         e
//         m
//         y


friends = ["Jim", "Karen", "Kevin"]
for name in friends:
  print(name)

//Output : Jim
//         Karen
//         Kevin


for index in range(10):
  print(index)

//Output : 0
//         1
//         2
//         3
//         4
//         5
//         6
//         7
//         8
//         9


for index in range(3, 10):
  print(index)

//Output : 3
//         4
//         5
//         6
//         7
//         8
//         9


friends = ["Jim", "Karen", "Kevin"]
for index in range(len(friends)):
  print(friends[index])

//Output : Jim
//         Karen
//         Kevin


for index in range(5):
  if index == 0:
    print("First Iteration.")
  else:
    print("Not first.")

//Output : First Iteration.
//         Not first.
//         Not first.
//         Not first.
//         Not first.


Functions

def say_hi(name, age):
    print("Hello " + name + ", you are " + str(age) + ".")


print("Top")
//Output : Top
say_hi("Mike", 35)
//Output : Hello Mike, you are 35.
say_hi("Steve", 70)
//Output : Hello Steve, you are 70.
print("Bottom")
//Output : Bottom

Getting Input From Users

name = input("Enter your name: ")
age = input("Enter your age: ")

print("Hello " + name + " ! You are " + age)
//Output : Enter your name: name
//         Enter your age: age
//         Hello name ! You are age

HCF of Two Numbers

# HCF or GCD of two numbers
def hcf(num1, num2):
    if num1 > num2:
        smaller = num2
    else:
        smaller = num1
    for i in range(1, smaller + 1):
        if (num1 % i == 0) and (num2 % i == 0):
            factor = i
    return factor

print(f'hcf = {hcf(54, 24)}')

Hello World

print("Hello World")
//Output : Hello World

How to Add Python to the Windows PATH variable

  1. Search for python.exe, right-click and open file location.
  2. Copy the location path.
  3. Run dialog SystemPropertiesAdvanced.
  4. Click Environment Variables....
  5. In User variables section, click New.
  6. Type Path to the Variable name: field and paste the python.exe's location path to the Variable value: field.
  7. Click OK.
  8. In System variables section, look for the Path Variable.
  9. Select it and click New.
  10. In the Edit environment variable window, click New.
  11. Paste the python.exe's location path and click OK to close the Edit environment variable window.
  12. Click OK to close the Environment Variables window.
  13. Click OK to close the System Properties window.



How to Extract Data from PDF Files

Package installation

First, we need to install PDFQuery and also install Pandas for some analysis and data presentation.


pip install pdfquery
pip install pandas


Import the libraries

import pandas as pd
import pdfquery


Read and convert the PDF files

We will read the pdf file into our project as an element object and load it. Convert the pdf object into an Extensible Markup Language (XML) file. This file contains the data and the metadata of a given PDF page.


The XML defines a set of rules for encoding PDF in a format that is readable by humans and machines. Looking at the XML file using a text editor, we can see where the data we want to extract is.


#read the PDF
pdf = pdfquery.PDFQuery('customers.pdf')
pdf.load()


#convert the pdf to XML
pdf.tree.write('customers.xml', pretty_print = True)
pdf


Access and extract the Data

We can get the information we are trying to extract inside the LTTextBoxHorizontal tag, and we can see the metadata associated with it.


The values inside the text box, [68.0, 231.57, 101.990, 234.893] in the XML fragment refers to Left, Bottom, Right, Top coordinates of the text box. You can think of this as the boundaries around the data we want to extract.


Let’s access and extract the customer name using the coordinates of the text box.


# access the data using coordinates
customer_name = pdf.pq('LTTextLineHorizontal:in_bbox("68.0, 231.57, 101.990, 234.893")').text()

print(customer_name)

#output: Brandon James

If Statements

is_male = True
is_tall = True

if is_male or is_tall:
  print("You are a male.")
else:
  print("You are not a male.")
//Output : You are a male.


if is_male or is_tall:
  print("You are a male or tall or both.")
else:
  print("You neither male nor tall.")
//Output : You are a male or tall or both.


if is_male and is_tall:
  print("You are a tall male.")
else:
  print("You are either not male or not tall or both.")
//Output : You are a tall male.


if is_male and is_tall:
  print("You are a tall male.")
elif is_male and not is_tall:
  print("You are a short male.")
elif not is_male and is_tall:
  print("You are not a male but are tall.")
else:
  print("You are not a male and not tall.")
//Output : You are a tall male.


If Statements & Comparisons

Python has six comparison operators, which are as follows :

  • Less than ( < )
  • Less than or equal to ( <= )
  • Greater than ( > )
  • Greater than or equal to ( >= )
  • Equal to ( == )
  • Not equal to ( != )


def max_num(num1, num2, num3):
  if num1 >= num2 and num1 >= num3:
    return num1
  elif num2 >= num1 and num2 >= num3:
    return num2
  else:
    return num3


print(max_num(300, 40, 5))
//Output : 300