Basic Errors in python

      A successful developer needs to know how to handle the errors. In python, basic errors are listed below.

  1. ·       Indentation error.
  2. ·       Syntax error
  3. ·       Type error
  4. ·       Name error  

1.Indentation error:

Python follows indentation properly.

Let a is assigned to 7 and b is assigned to 4. Just check if a is greater than b, print a.

Here, if statement and its block is in same indentation. In python, it is an indentation error.


Let us rewrite the code with proper indentation.

 2.Syntax error:

           This error comes when the user misses the syntax. The below example, user missed colon(:) in the while loop.

Let we correct the error putting : after the while loop condition. Here, is the outcome.

3.Type error:

         This error occurs, when the user wrongly uses the datatype. Instead of int datatype , somebody used char datatype. Example is given below.

Note: use proper datatype.

The error is corrected below.

4.Divide by zero error:

           This is the very common error. Let us, code an example below.

Just change the code by z = y/2 or any number.

These are the basic errors in python.

How to create a user defined package in python???

Package is a collection of files which contains various member functions and its definitions. When a user creates a package with their own definition, it can be considered as a module. It can be reused anywhere.

Let us create a package in your system by creating a folder “greetings” by right click in the folder. Choose “new” option and select new folder. Name it as “greetings”.

Next, create three files. One is “__init__.py”,other two’s are “greet1.py” and “greet2.py”.

It look like below.

greetings

     |-------   __init__.py  

     |-------   greet1.py

     |-------   greet2.py

 __init__.py is a file which represents a initialization file. it denotes the it belongs to a package.

greet1.py and greet2.py defines the member functions.

Here ,it contains the below code.

“greet1.py”

#This file has a definition of function “message1” as a print statement.

def message1():

              print("Welcome to the world of python")

 

“greet2.py”

#It defines a function “message2’” with displaying greetings message.

def message2():

              print("Enjoy coding")

Now ,its time to use this package “greetings” to an external file “Test.py”

Steps:

  • Open a text editor like notepad, save it as a python file “Test.py”
  • Add the code to the file.

#import the package “greetings” and its sub modules “greet1,greet2”

from greetings import greet1,greet2

#call the functions by mentioning the filename followed by. with function.

greet1.message1()

greet2.message2()

Next, execute the file in command prompt. Set the path for folder. Execute the file “Test.py”. you will get the below output.

 

This is the simple way to create a package in python is explained.

How to find the path of a file or directory is exists or not???

    Directory contains all the files available in the system. Each and every file is specified with a path. This blog gives the way to find the path and its existence.

First, list out all the paths available in the system by the below code.

#Import the sys module.

import sys

#print the available system paths

print(sys.path)

when executing this code, the available paths in system is displayed.

['', 'C:\\Users\\rajeswari jeevananth\\AppData\\Local\\Programs\\Python\\Python311\\python311.zip', 'C:\\Users\\rajeswari jeevananth\\AppData\\Local\\Programs\\Python\\Python311\\DLLs', 'C:\\Users\\rajeswari jeevananth\\AppData\\Local\\Programs\\Python\\Python311\\Lib', 'C:\\Users\\rajeswari jeevananth\\AppData\\Local\\Programs\\Python\\Python311', 'C:\\Users\\rajeswari jeevananth\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages']

Finding the file path available or not by path.exists() method:

This method uses a built-in module “OS”.  Let us use the function “path.exists()” to check the path exists or not.

#First,import os module

import os

#Set the path

path ='C:\\Users\\rajeswari jeevananth\\AppData\\Local\\Programs\\Python\\Python311\\DLLs'

#using os.path.exists(path) function,get the value of ex.

ex = os.path.exists(path)

#if the ex is assigned to 1 means, the file exists already. Just print the value as the path exists. Else prints that the path doesnot exist.

if ex == 1 :

    print("The path exists")

else :

    print("The path doesnot exist")

The output is:

The path exists

 Finding the file exists or not by isfile() method:

              This method is used to check whether the file is available or not.

#import os module.

import os

#assign the path of the file.

path = 'C:\\raji\\blog\\avg.py'

#Find the file existence by the isfile() and assign the value to ex.

ex = os.path.isfile(path)

#If the ex value is 1, the file exists. Otherwise, it does not exist. Print the output accordingly.

if ex == 1 :

     print("The file exists")

else :

    print("The file doesnot exist")

Just execute this program. you get the below output.

Output:


Finding the directory by isdir() method:

            This method finds the directory availablitiy.

#import the built in module.

import os

#set the path of directory.

path = 'C:\\Users\\rajeswari jeevananth\\AppData\\Local\\Programs\\Python\\Python311'

#use the method isdir() to check the directory is available or not.

sdir = os.path.isdir(path)

# check the variable assigned to the function output. If true, it prints “This directory available”. Else, it prints “This directory doesn’t exist”

if sdir == 1:

   print("This directory exists")

else :

   print("This directory doesnot exist")

The output of the program is


 This is the simple way to find the path of a file or directory existence.

How to create, read and write contents to a file???

              In the computer world, a basic thing is called files. It contain set of instructions that can be a text,,image ,commands or any type of information. Generally, files can be of 3 types.

  • ·       System files
  • ·       Application files
  • ·       Data files

Based on the usage of information, it can be of any above type.

How to create file and write contents to the file in python:

              A file can  be created or created file can be opened by the following syntax.

File_object = open(“filename”,”mode”)

Where

File_object is the object from which, we access the file.

File name is the name of the file with extension.

Mode depends on the operations we perform on file.

Mode

Purpose

“x”

It creates a new file. If the file exists, this mode fails.

“b”

It represents binary mode.

“a”

It represents append mode.

“t”

It represents text mode.

“r”

Reading the file

“w”

Writing contents to the file.If the file exists, it writes the content.Else, it creates a new file.

“+”

It represents read and write operations.

 Let a example shown below.

#creates a file object(fo) and opens a file “sample.txt” with both reading and writing purpose

fo = open("sample.txt", "a+")

#create a for loop and prints hi message 5 times with number

for i in range(5) :

      fo.write("%d hi \n" %(i+1))

while executing this program, the user gets the following text in sample.txt.


How to read files in python ???

              It creates a file object using open method.

#open the file in read mode.

fo = open("sample.txt","r")

# check the mode and read using read method and write the contents using print()

if fo.mode == "r" :

   fc = fo.read()

   print(fc)

This program gives the below output.

These are the simple ways to create a file, read and write the contents.

Python enumeration

     Enumeration is one of the concepts in python. It deals with collection of things grouped under a common name. It follows an order.

Syntax:

enumerate(iterable, StartIndex)

where iterable – it is the object.

             StartIndex – it is the beginning of list. Default value is 0.

Eg:

#Creating a fruit list

Fruitslist = ['apple', 'banana', 'orange', 'grapes']

#Making the list as a enumerated list

F_list = enumerate(Fruitslist)

#printing the enumerated list

print(list(F_list))

Executing this, the following output is shown in the output screen.

When the startindex value is mentioned in the code, it becomes…

Fruitslist = ['apple' , 'banana' , 'orange' , 'grapes']

F_list = enumerate(Fruitslist,2)

print(list(F_list))

just execute this code,you will get the below output.

Python program to print the items in the list using enumeration:

Let us create list of vehicles and print it using enumerated list.

#First,create a list (v_list)

V_list = ['car' , 'bus', 'van' ,'truck']

#create a loop and make the list as enumerated and print the  value until the last element.

for i in enumerate(V_list):

   print(i)

# start the index as 4 and print the list.

print("Using startindex as 4")

for i in enumerate(V_list ,4):

    print(i)

 Here is the output.


Enumeration : tuple

Tuple is a set of objects. It can be separated by a comma. Let  us create a enumerated tuple.

#create a v_tuple and print with for loop.

V_tuple = ['car' , 'bus', 'van' ,'truck']

for i in enumerate(V_tuple):

   print(i)

The output is

Enumeration: Strings

              String is a collection of characters. Enumeration in string is given below.

msg = "Welcome to the python world"

for i in enumerate(msg):

    print(i)

while running this program, it lists all the characters with index.


Enumeration : Dictionary:

              Dictionary is a collection of data with meaning. Let us create a dictionary for vehicles.

#create a dictionary v_dict and print the elements using for loop.

v_dict = { "car" : "4 wheels" , "bike" : "2 wheels" , "auto" : "3 wheels" , "truck" : "6 wheels" }

for i in enumerate(v_dict):

  print(i)

The output of the program is:



These are the some coding samples using enumeration.

Python programs using Functions :Factorial of a number and Division of two numbers

 Functions are set of statements for performing a specific task. A function includes a declaration, definition and function call.

A function declaration includes a key word ‘def’ follows by a function name and arguments.

Syntax:

def  function_name(arg1,arg2,…..,argn)

where arg1…argn – arguments

Note: You can define a function without arguments also.

A function call uses the function name and arguments.

Eg: function_name(arg1,arg2,…argn)

Python program to do division of two numbers using functions:

#first, function definition. Here,‘div’ is the function name. x,y are the arguments. This function performs division of two numbers.

def div(x,y):

    return x/y

#Next, x and y values are read from runtime.

x = int(input("Enter the numerator value"))

y = int(input("Enter the denominator value"))

#The function call div(5,2) control goes to function definition. It return the output to print statement. It prints the output.

print(div(5,2))

It gives you the following output.


A function call may contain the arguments in different order. For eg, div(x,y) is the function definition. But we call the function with  different order of arguments as follows.

div(y = 3 ,x = 15)

let this function call differ from previous code.

def  div(x,y):

    return x/y

print(div(y = 3, x = 15))

The output is…

Python program to find factorial of a number using function:

Factorial is one of the important function in mathematics. It continuously multiply a number from 1 to that number. For example, 5!  = 5*4*3*2*1.

#Define the function fact with one argument ‘n’. This function uses recursive function call. That means, a function calls itself. If the ‘n’ value is greater than 1,it multiply and calls itself by ‘n-1’ times. Otherwise, it returns 1.

def fact(n):

    if n >= 1 :

        return n*fact(n-1)

    else :

        return 1

 #Get the ‘n’ value from the user at run time.

n = int(input(“Enter the number”))

#function call with ‘n’ value. Print the output.

print(“The factorial of the given number is”, fact(n))

while executing this program, you get the below output.


Thus the python programs using functions are briefly described with examples.