Thursday, August 6, 2020

Error handling in python

Become a coder is very easy things but become a good coder you must know how to handle the error in the program during execution.so if you want to handle the error in code you must follow the try and except in code. When the program run and got the run time error it will not execute the script print then you have to use try/except/else/final command to get the output according to command.

Common Exceptions:
Python provides the number of built-in exceptions, but here we are describing the common standard exceptions. A list of common exceptions that can be thrown from a standard Python program is given below.


ZeroDivisionError:

This occurs when a number is divided by zero.
NameError:

It occurs when a name is not found. It may be local or global.
IndentationError:

If the incorrect indentation is given.
IOError:

It occurs when the Input-Output operation fails.
EOFError:

It occurs when the end of the file is reached, and yet operations are being performed.



example:When you divide the number by any by zero then python gives the zero devision error.

try:  
    num1= int(input("Enter num1:"))    
    num2= int(input("Enter num2:"))    
    num= a/b  
except:  
    print("Can't divide with zero")

output:

Enter num1:10

Enter num2:0

Can't divide with zero

Declaring Multiple Exceptions: The Python allows us to declare the multiple exceptions with the except clause.

try:    

    #block of code     

    

except (<Exception 1>,<Exception 2>,<Exception 3>,...<Exception n>)    

    #block of code     

    

else:    

    #block of code  


example:

try:      
    a=10/0;      
except(ArithmeticError, IOError):      
    print("Arithmetic Exception occur")      
else:      
    print("Successfully Done it")


output:

Arithmetic Exception


The try & finally block:

Python provides the optional finally statement, which is used with the try statement. It is executed no matter what exception occurs and used to release the external resource. The finally block provides a guarantee of the execution.

syntax:

try:    
    # block of code     
    # this may throw an exception    
finally:    
    # block of code    
    # this will always be executed


example:

try:    

    fileptr = open("file2.txt","r")      

    try:    

        fileptr.write("Hi I am good")    

    finally:    

        fileptr.close()    

        print("file closed")    

except:    

    print("Error")

output:

file closed

Error



Raising exceptions:

An exception can be raised forcefully by using the raise clause in Python. It is useful in that scenario where we need to raise an exception to stop the execution of the program. eg: I have 4gb memory and when it occupied then it raises an exception.

syntax:
raise Exception_class,<value> 

example:

try:    
    age = int(input("Enter the age in number:"))    
    if(age<18):    
        raise ValueError   
    else:    
        print("the age is a valid value ")    
except ValueError:    
    print("The age is not a valid value ") 

output:

Enter the age:17

The age is not a valid value 



example:
try:    
    num1 = int(input("Enter num1:"))    
    num2 = int(input("Enter num2:"))    
    if num2 is 0:    
        raise ArithmeticError  
    else:    
        print("num1/num2 = ",num1/num2)    
except ArithmeticError:    
    print("The value of b can't be 0") 

output:

Enter a:10

Enter b:0

The value of b can't be 0

Custom Exception:
The Python allows us to create our exceptions that can be raised from the program and caught using the except clause. However, we suggest you read this section after visiting the Python object and classes.

example:
class ErrorInCode(Exception):      
    def __init__(self, data):      
        self.data = data      
    def __str__(self):      
        return repr(self.data)      
      
try:      
    raise ErrorInCode(4000)      
except ErrorInCode as ae:      
    print("Received error:", ae.data) 

output:
Received error: 4000

Friday, July 31, 2020

Python file operation

In python, If we have a file then we can perform three types of operation like open a file, read or write operation a file, and close a file.


Opening a file: Python provides an open() function that accepts two arguments syntax is like below.

file object = open(<file-name>, <access-mode>, <buffering>) 


access-mode:

r: open a file for reading.
w: open a file writing, create if does not exist, truncate the file if it exists.
b: open a file in binary mode.
a: open a file for appending at the end of the file without truncating it, create a new file if does not exist.
t: open a file in text mode.
+: '+'open a file updating(reading and writing).


a file can perform below these operations at a time.

r,rb,r+,rb+

w,wb,w+,wb+

a,ab,a+,ab+


Some basic operation and example are below:


#opens the file file.txt in read mode    
file = open("file.txt","r")    
    
if file:    
    print("file is opened successfully")   

Output:
<class '_io.TextIOWrapper'>
file is opened successfully


The close() method:


Once all the operations are done on the file, we must close it through our Python script using the close() method.

syntax:
fileobject.close() 



# opens the file file.txt in read mode    
file = open("file.txt","r")    
    
if file:    
    print("file is opened successfully")    
    
#closes the opened file    
file.close()  


try:  
   file = open("file.txt")  
   # perform file operations  
finally:  
   file.close()



The with statement
The with statement was introduced in python 2.5. The with statement is useful in the case of manipulating the files. It is used in the scenario where a pair of statements is to be executed with a block of code in between.

syntax:
with open(<file name>, <access mode>) as <file-pointer>:    
    #statement suite 


example:

with open("file.txt",'r') as f:    
    data = f.read();    
    print(data)  


......................................................................................................................................................................
# open the file.txt in append mode. Create a new file if no such file exists.  
file = open("file2.txt", "w")  
  
# appending the content to the file  
file.write('''''Python is the modern day language. It makes things so simple. 
It is the fastest-growing programing language''')  
  
# closing the opened the file  
file.close()


conclusion: We have opened the file in w mode. The file1.txt file doesn't exist, it created a new file and we have written the content in the file using the write() function.




......................................................................................................................................................................
#open the file.txt in write mode.    
file = open("file2.txt","a")  
    
#overwriting the content of the file    
file.write(" Python has an easy syntax and user-friendly interaction.")    
      
#closing the opened file     
file.close()  


......................................................................................................................................................................

#open the file.txt in read mode. causes error if no such file exists.    
file = open("file2.txt","r")  
#stores all the data of the file into the variable content    
content = file.read(10)   
# prints the type of the data stored in the file    
print(type(content))      
#prints the content of the file    
print(content)       
#closes the opened file    
file.close()   


......................................................................................................................................................................


Read file through for loop:

#open the file.txt in read mode. causes an error if no such file exists.    
file = open("file2.txt","r");     
#running a for loop     
for i in file:    
    print(i) # i contains each line of the file 




Reading lines using readline() function:

#open the file.txt in read mode. causes error if no such file exists.    
file = open("file2.txt","r");     
#stores all the data of the file into the variable content    
data = file.readline()     
data1 = file.readline()  
#prints the content of the file    
print(content)     
print(content1)  
#closes the opened file    
file.close()    


Creating a new file:


#open the file.txt in read mode. causes error if no such file exists.    
file = open("file2.txt","x")   
print(fileptr)    
if file:    
    print("File created successfully")



......................................................................................................................................................................

File Pointer positions:

Python provides the tell() method which is used to print the byte number at which the file pointer currently exists.


# open the file file2.txt in read mode    
file = open("file2.txt","r")    
  
#initially the filepointer is at 0     
print("The filepointer is at byte :",file.tell())    
    
#reading the content of the file    
content = file.read();    
    
#after the read operation file pointer modifies. tell() returns the location of the file.     
    
print("After reading, the filepointer is at:",file.tell()) 


......................................................................................................................................................................

Modifying file pointer position:

sometimes we need to change the file pointer location externally since we may need to read or write the content at various locations. For this purpose, the Python provides us the seek() method which enables us to modify the file pointer position externally.

<file-ptr>.seek(offset[, from)


offset: It refers to the new position of the file pointer within the file.

from: It indicates the reference position from where the bytes are to be moved. If it is set to 0, the beginning of the file is used as the reference position. If it is set to 1, the current position of the file pointer is used as the reference position. If it is set to 2, the end of the file pointer is used as the reference position.

# open the file file2.txt in read mode    
file = open("file2.txt","r")    
    
#initially the filepointer is at 0     
print("The filepointer is at byte :",file.tell())    
    
#changing the file pointer location to 10.    
file.seek(10);    
    
#tell() returns the location of the file.     
print("After reading, the filepointer is at:",fileptr.tell())

......................................................................................................................................................................

Python OS module:

Renaming the file:

It provides us the rename() method to rename the specified file to a new name.

syntax:

rename(current-name, new-name)

import os    
    
#rename file2.txt to file3.txt    
os.rename("file2.txt","file3.txt")

Removing the file:

The os module provides the remove() method which is used to remove the specified file.

import os;    
#deleting the file named file3.txt     
os.remove("file3.txt")


Creating the new directory:

The mkdir() method is used to create the directories in the current working directory. The syntax to create the new directory is given below.

import os    
    
#creating a new directory with the name new    
os.mkdir("new")  


The getcwd() method:

This method returns the current working directory.

import os  
os.getcwd()

Changing the current working directory:

The chdir() method is used to change the current working directory to a specified directory.

import os   
# Changing current directory with the new directiory  
os.chdir("C:\\Users\\DEVANSH SHARMA\\Documents")  
#It will display the current working directory  
os.getcwd() 

Deleting directory:

The rmdir() method is used to delete the specified directory.

import os  
#removing the new directory     
os.rmdir("directory_name")



Writing Python output to the files:

In Python, there are the requirements to write the output of a Python script to a file.

The check_call() method of module subprocess is used to execute a Python script and write the output of that script to a file.

file.py
temperatures=[10,-20,-289,100]    
def c_to_f(c):    
    if c< -273.15:    
        return "That temperature doesn't make sense!"    
    else:    
        f=c*9/5+32    
        return f    
for t in temperatures:    
    print(c_to_f(t))


----------------------------------------------------------------------------------------------------------------------------
file.py

import subprocess    
    
with open("output.txt", "wb") as f:    
    subprocess.check_call(["python", "file.py"], stdout=f) 



Wednesday, July 29, 2020

Python Interview questions:

These questions are very helpful to those who are trying to get the job in python field and these questions are as standard per industry right now which I have faced currently.


If any point is mention in question goes in detail and revise your concept.so first we will start with basic data structure and then we will cover basic to advance python interview questions.

During the interview, they will take first round as technical round and ask some basic python questions then in the second round they will ask for your project and what type of work you handle in the previous company, experience-based technical questions standard of the current industry scenario in the market. The final round will be your CEO round and they will ask some project or directly discuss the money.


1. What is the basic data type in python or Why you choose python language or explain  PEP 8?
2. Explain the List, Tupple, Set &Dictionary, and their functions?
3.Difference between List and Tupple?
4.Difference between mutable and immutable nature of list and python?
5.Memory management in python?
6. Is the set holds the duplicate value or uniqueness of the set?
7. How can convert a value from int to float or string?
8. Explain dict and their functions?
9.Difference between set and frozen set?
10.Difference between dict and default dict?
11. How can access a value in dict?
12. Can we take the key: value as an integer if yes then how can we access the value?
13.Pickling and unpickling?
14. What is Iterator /Generotorand decorator give the proper definitions and what is Time log decorator give an example?
15. What are *args and **kwargs or give the example of it?
16. What is Enumerate and zip functions?
17.Shallow copy and deep copy?
18. Explain the map , reduce, and filter functions?
19. What are Lambda functions and their use cases?
20. How can optimize your python code?
21. Is python-support Multithreading and multiprocessing then explain it?
22.Lower case and Upper case?
23. What is a namespace or explain LEGB rule?
24. Explain oop's concept and types of Inheritance with example?
25. What is instance and instance variable?
26. What is the class?
27.Difference between closure - decorator and their use cases?
28. Explain polymorphism and encapsulation?
29. Is python-support method overriding or method overloading if yes then explain it?
30.The key difference between method overriding and method overloading?
31.Difference between iterator and for loop?
32. How you can make a protective , private, and local variable? 
33. Difference between global and local variables give an example of that?
34. What is the enclosing scope or scope in python?
35.D difference between public method and private method?
36.Difference between abstraction and encapsulation?
37. Difference between multilevel and multiple inheritances gives an example of it?
38. What is ternary operator in python and use cases of it?
39.Difference between sort and sorted?
40.The physical key, foreign key, and logical key?
41. What is Enum?
42.Is python supported switch?
43. What is self in python or constructor in python?
44. Explain the magic method or dunder in python?
45.Difference between str() and repr()?
46. What are python inbuilt functions?
47. What is a break , pass, and continue?
48. What is Numpy array explain it with example and their functions according to a dimension?
49. What is Pandas explain it with example and their functions according to a dimension?
50.File handling in python?
51. How can read ten files at a time , explain with example?








Thursday, July 23, 2020

python installation and environmental setting

1. Downloads & Install Python from python.org which version you want it.

https://www.python.org/



2. Install pycharm community edition from the given below link.

https://www.jetbrains.com/pycharm/download/#section=windows






3. Go in file >New project > Give your project name and then Set the environment variable in pycharm in file > setting > project interpreter & give the path where you install the python.exe file.





Tuesday, July 21, 2020

Data structure & their functions

Python has four types of data structure.
1. LIST
2. TUPLE
3. SET
4. DICTIONARY


List: The list is the data structure of item which are ordered, mutable and these are comma the separated value stored in square bracket.


The basic operation of List and functions:

1.   Accessing elements –[0],[1],[2],[3],[4].

2.   Modifying individuals item- You can modify in the list individually users[0], users[-2].

3.   Adding elements- You can add elements in the list by users. append.

4.   Removing elements- you remove any item by their position or value of the item. users.remove(‘list_iem_name’).

5.   List length-  len() functions return the number in list.

6.   Sorting a list –You can sort list increasing or decreasing order
Sorting permanently => users.sort(),users.sort(reversed=True)
Sorting temporary=> print(sorted(usres)),print(sorted,reversed=True))

7.   Slicing a list: You can slice a portion of the list [:3],[1:3],[-3:]

8.   Copying a list => copy_users=[:]

#some example of List
users=['val','bob','mia','ron','ned']
first_item=users[0]
print(first_item)
# sorting a list permanently
users.sort()
print(users)
users.sort(reverse=True)
print(users)
# for usrers in users:
#      print(users)
# finding length of the list
num_users=len(users)
print(num_users)
# slicing a list
first_three=users[:3]
print(first_three)
midle_three=users[1:4]
print(midle_three)
last_three=users[-3:]
print(last_three)

# copying a list
copy_of_users=users[:]
print(users)


   Tupple: Tuple is a set of an item which is ordered and immutable ().

Due to immutable in nature, we can’t apply so many functions like a list.
only count and index functions are there.




   Set: Set is data structured which is ordered, mutable in nature, and does not hold the duplicate value in the set.

Operations and functions of Set:
(A)          Creating a set :{}
1.   Duplicate element-does not hold the duplicate element in set.
2.   Mutable -but may not contain mutable items like a set, or even a dictionary.
3.   Python set function
(B).Accessing a set in python: Since the set is not support indexing so we can access the entire set at once. Because set does not support slicing so we can’t access the element one by one or [:3].
(C).Deleting a set: Because the set is not indexed then we can’t delete any element from the set. By using some method we can remove or discard any item from the set.
        Set. Pop() ->It will pop an element from beginning one by one
        Set. Clear() -> It will clear all the element from set.


(D). updating a set: You can add and update the number in your set.

          (E) Function on sets:
          Len()->The len function return the length of the functions.
          Max() ->This function can return the highest value from set.
          Min()->This function can return the Lowest value from the set.
          Sum()->This function sum all the value from the set.
          All/any()->True or False
          Sorted()->It will sort the item in ascending order.






(E).Methods on set:

          Union(),Intersection(),difference(),symmetric_difference,intersection_update,difference_updat
          Symmetric_difference_update() ,copy,isdisjoint,issubset,issuperset,
          (F).Operation on sets:
Membership: We can apply the ‘in’ and ‘not’ in python operator on items for set. This tells us weather they are belong to set.
(H): Iterating on set: We can iterate on set in a for a loop. 

(I): The frozenset: A frozenset is in-effect an immutable set. You can’t change its value. Also, a set can’t be used a key for a dictionary , but a frozenset can


d=set()
print(type(d))
# =========Deleting===========
# we can't delete any item from the list but by suing discard or delete method we can
set={1,3,3,4,5,5,7}
set.discard(
3)
print(set)
set.remove(
5)
print(set)
# pop()
set.pop()
print(set)
# clear
set.clear()
print(set)
# Updating a set
numbers={1,1,2,2,3,3,4,5}
# numbers[9]
# print(numbers)
numbers.add(3.5)
print(numbers)
numbers.update([
7,8],[1,10,9])
print(numbers)
# Functions on set
print(len(numbers))
print(max((numbers)))
print(min(numbers))
print(sum(numbers))
print(any(numbers))
print(all(numbers))
print(sorted(numbers))
# Methods on set
set1,set2,set3={1,2,3,4},{4,5,6},{4,5,7,8,9}
print(set1.union(set2,set3))
print(set2.intersection(set3))
print(set1.difference(set2))
print(set1.symmetric_difference(set2))
print(set1.intersection_update(set2))
print(set1.difference_update(set2))
print(set1.symmetric_difference_update(set2))
print(set3.copy)
print(set1.isdisjoint(set3))
print(set1.issubset(set2))
print(set1.issuperset(set1))
# Operation on set
# 'p' in {'a','c','p','d'}
for i in {'a','c','p','d'}:
   
print(i)




Dictionary: A dictionary has to contain key-value with semicolon pair in the curly bracket.




Creating a dictionary: dict = {‘a’:1,’b’:2,’c’:3}
(A): Python dictionary with comprehension: It’s just like range function.
mydict={x*x:x for x in range(8)}
     print(mydict)
     output= {0: 0, 1: 1, 4: 2, 9: 3, 16: 4, 25: 5, 36: 6, 49: 7}
(B): Dictionary with mixed keys: The key-Val pair should not sa me necessary in dictionary.
dict3={1:'carrots','two':[1,2,3]}
(C)dict(): Using dict function we can convert in dictionary.
dict(([1,2],[2,4],[3,6]))

(D): Declaring one key more than once: Like set dictionary can’t hold more than one key.
mydict2={1:2,1:3,1:4,2:4}

(E):Declaring empty dictionary and adding elements later: When you can add key-value pair in dictionary.
animals={}
animals[1]='dog'
animals[2]='cat'

(F)Accessing python dictionary:
(a)accessing an entire python dictionary: print the dict name
(b)accessing a value: To access an item from a dictionary we can use square bracket in the dictionary.
(c)get(): The Python dictionary get() functions takes a key as an argument and returns the corresponding value.
  Mydict.get(49)
Output=7
(G): Updating the value of an Existing key: you can update the dictionary value by using square bracket.
(H)You can delete the item from dict like-  del dict[2]
(I) In-built functions on dictionary:
Len(),any()->return true if any key has Boolean value.
All(),sorted() ->function returns a  sorted sequence key in ascending order dictionary.

(J)In-built methods of dictionary:
Keys()-> used for return the key of dictionary
Values()-> used for return the value of dictionary
Items()->return the key-value of dictionary
Get()->dict4.get(3,0 ) it will return the key if there is in dictionary or return 0.
Clear()->represent the empty  dictionary
Copy()->copy methods creates the shallow copy of the python dictionary.
Pop()->This method is used to remove and display an item from the dictionary. It takes one to two arguments. The first is the key to be deleted, while the second is the value that’s returned if the key isn’t found.
Popitem(): pop item() method is such that for a particular dictionary, it always pops pairs in the same order.
From keys()->This method creates a new Python dictionary from an existing one.

Update():This method is used for updating the dictionary as a key value.


Python Dictionary Operation:
Membership: We can apply the ‘in’ and ‘not in’ operators on a Python dictionary to check whether it contains a certain key.


Python Iterate dictionary: When in a for loop, you can also iterate on a Python dictionary like on a list, tuple, or set.





Nested Dictionary: Finally, let’s look at nested dictionaries. You can also place a Python dictionary as a value within a dictionary.  , dict1={4:{1:2,2:4},8:16}

# dictionary -contain key-value pair
dict={x*x:x for x in range (8)}
print(dict)
# updating the value of the existing key
dict1={1:2,3:4,5:6,7:8}
dict1[
3]=#You can update the value by assigning key in square bracket
print(dict1)
# Deleting a dict
del dict1[3]
print(dict1)




Difference between List, Tuple, Set  &  Dictionary



List
Tupple
Set
Dictionary
List is a collection that is ordered, mutable.
Tupple is a collection that is ordered, immutable.
Collection of Unordered and Unindexed items & mutable in nature.
A dictionary is a the collection which is unordered, changeable and indexed & Key: Value Pair in Python.
Allows duplicate members[]

Tuples are faster than lists as they are immutable& hold the duplicacy().
Does not take duplicate Values{}.
Does not take duplicate Values{}.

Lists are like arrays declared in other languages.


Sets are not faster than lists however they have an upper hand when it comes to membership testing.

Functios:append,remove,len
Sort,slicing,copy,pop


Functions: not support like list due to immutable in nature.
Functions:len,max,min,sum,all,
Any, sort, pop clear, delete
Functions:len ,all
Sorted,keys,values,items,get,
Clear, copy