Social Media

Image Slider

7/30/2019

Instance Hidden Variables

Instance variables are those variables which depends upon the object.
They are not class specific, they are actually object specific.
We can also hide any instance variable.
Script: Write an script in Python which demonstrate how we can access hidden instance variable inside or outside the class.
class A:
    def __init__(self):
        self.__x=10
        self.__y=20
    def printresult(self):
        print("The value of y is",self._A__y) #Accessing inside the class
       

a1=A()
print(a1._A__x) #accessing outside the class
a1.printresult()


Output:
10
The value of y is 20


7/29/2019

Static Hidden Variables

There is no keyword like public, protected, private in Python. However you can make any hidden variable in Python.
Hidden variable can be static or instance.
You can't access hidden static variables outside the class in the same way as before.
Script1: Write an script which shows the demonstration of static hidden variable.
class A:
    x=6 #static variable
    __y=5 # static hidden variable

print(A.x) # 6 will be printed 
print(A.__y) #error comes here

Script2: Write an script which describe how to access static hidden variables.
Static hidden variables can be access inside the class using static method as given below:
class A:
    x=6 #static variable
    __y=5 # static hidden variable
    @staticmethod
    def showhiddenvar():
        print("The value of hidden variable y is",A.__y)

print(A.x)
A.showhiddenvar()

Output:
6
The value of hidden variable y is 5

Note* Static hidden variables can also be accessed  outside the class by changing the name during accessing them. Actually what Python is doing when we are making any variable hidden is, it is just changing its name. So we can access the hidden variable if we know what is the way of changing the name of variables of Python.
Example if i write__x=3
then we can access this static hidden variable outside the class as ClassName.__ClassName__x 




7/28/2019

Command Line Arguments

Command line arguments are those arguments which are given by user at a screen, when we run the python script.
You cannot directly run these kinds of programs using your IDE normally.
You will have to import argv which is defined in sys package.
argv is a kind of list in which first element is the name of the file in which you have written the script.
You can give any number of arguments at command line. They will start going into list one by one.
You have to run these kind of programs using command prompts in windows or in linux it will be terminal where you are going to learn these kinds of scripts.
A simple script to multiply two numbers is given below.
Script: Write an script in Python to multiply two numbers which are given by user at prompt screen.

7/25/2019

Polymorphism

Polymorphism comprises of two words poly+morphs.
Poly means many and morphs means forms.
If a single entity has different behaviour in different conditions then this condition is called polymorphism.
Polmorphism can be implemented using two ways.
  1. Function overloading
  2. Function overriding
Function Overloading and overriding:
Function overloading basically means functions with same names but different arguments.
But function overloading is not possible in Python language. In Python, if we are declaring more than one function with the same name, then the function that we declare currently will override the previous declared function. So function overloading is not possible in Python.
Below script will give you error due to function overriding.
Example of function overloading

class A:
   def f1(self):
      print("This is the function of class A")

class B(A):

   def f1(self,a):
      print("This is the function of class B")

a1=A()

a1.f1()
b1=B()
b1.f1()

Output:
This is the function of class A
Traceback (most recent call last):
  File "C:\Users\hp\Desktop\p1.py", line 12, in <module>
    b1.f1()
TypeError: f1() missing 1 required positional argument: 'a'

I think you got why the error is coming. 

Example of function overriding

class person:
   def __init__(self,name):
      self.name=name
   def viewProperties(self):
      print("You are in general category")
      print("Your name is ",self.name)

class student(person):

   def __init__(self,name):
      super().__init__(name)
   def viewProperties(self):
      print("Your category is student")
      print("Your name is",self.name)

p1=person("Aniket")

p1.viewProperties()
s1=student("Mayank")

s1.viewProperties()

Output:
You are in general category
Your name is  Aniket
Your category is student
Your name is Mayank

Note: In other object oriented languages like JAVA and C++, function overloading is possible.


7/16/2019

Multiple Inheritance

Multiple Inheritance denotes that a class has more than one parent classes.
In Java language multiple inheritance is not possible.
We can take advantage of multiple inheritance in Python language.
The Syntax for multiple inheritance can be as:
class A:
   ....
   ....
class B:
   ...
   ...
class C(A,B):
   ...
   ...
Script: Write an script in Python to demonstrate the use of Multiple Inheritance.
class A:
   def __init__(self,a):
      self.a=a
   def showA(self):
      print("the value of a=",self.a)

class B:

   def __init__(self,b):
      self.b=b
   def showB(self):
      print("the value of b=",self.b)

class C(A,B):

   def __init__(self,a,b,c):
      A.__init__(self,a)
      B.__init__(self,b)
      self.c=c
   def showC(self):
      A.showA(self)
      B.showB(self)
      print("the value of c=",self.c)

obj=C(2,3,4)

obj.showC()
print(obj.__dict__)


Output:
the value of a= 2
the value of b= 3
the value of c= 4
{'a': 2, 'b': 3, 'c': 4}



7/15/2019

Inheritance

Inheritance is basically one of the most important feature of Object Oriented Programming.
Inheritance means acquiring the properties of a class in another class.
The parent class is called Base class while child class is called Derived class.
By using inheritance concept in our script we can reuse the code.
Inheritance saves a lot of time of programmer as writing code again and again is time consuming.
There can be many types of Inheritance. For example

  1. Single Inheritance
  2. Multiple Inheritance
  3. Multilevel Inheritance
  4. Hierarchical Inheritance
  5. Hybrid Inheritance
Script: Write an script in which class B inherit all the properties of class A.

class A:
   def __init__(self, a):
      self.a=a
   def showA(self):
      print("the value of a is "+str(self.a))
      
class B(A):
   def __init__(self,a,b):
      super().__init__(a)
      self.b=b
   def showB(self):
      print("The value of b is "+str(self.b))

obj1=B(2,3)
obj1.showA()
obj1.showB()

Output:
the value of a is 2
The value of b is 3
The following points needs to be remember in the above program.
  1. Child class constructor does not call parent class constructor implicitly in Python language.
  2. If we make object of child class and we call a function then first it will find out the function in the child class, if the function matches in the child class, then it will not search that function in the parent class.
  3. If the function is not found in the child class it will search that in the parent class.

7/14/2019

Projects in Python Language

Practice Problems

Will be updated soon...
7/12/2019

Class Method

There is a special type of method that Python language offers, this is called class method.
This function is neither static nor instance.
Notation is compulsory while we are going to declare this kind of function.
This function can also be used to create static variables.
Class method contains the class reference implicitly which means one argument is necessary while we are going to create class method.

Script1: Write an script which demonstrate the usage of class method in Python language.

class Demo:
    @classmethod
    def fun(cls):
        cls.a=10
        Demo.b=20
        
Demo.fun()
print(Demo.a)
print(Demo.b)

Output:
10
20


Script2: Write an script to print all the static variables exist in the class.

class Demo:
    x=80
    @classmethod
    def fun(cls):
        cls.a=10
        Demo.b=20
        
Demo.fun()
print(Demo.__dict__)

Instance and Static Variables

Instance Variables:
Instance variable are those variables which depends upon the creation of the object.
We can create instance variable by using any of the way you like.
  1. Using __init__() method
  2. Using a function defined in the class
  3. Outside the class
Script: Write an script to demonstrate the creation of instance variables using all three ways above.

class Test:
    def __init__(self):
        self.a=50
        print("Instance Variable a is created using init function ")
    def createinstncvar(self):
        self.b=10
        print("Instance Variable b is created using instance function")

t1=Test()
t1.createinstncvar()
t1.c=30
print("Instance variable c is created outside the class")
print("a=",t1.a," b=",t1.b," c=",t1.c)

Output:
Instance Variable a is created using init function 
Instance Variable b is created using instance function
Instance variable c is created outside the class
a= 50  b= 10  c= 30

**Here self contains current object reference.
Creation of instance variable using __init__() function is more popular and widely used way.


Static Variables:
If you have the background of Java language then for static variables there is static keyword present to create them.
Static variables are not object specific, these are class oriented.
They can be shared by any number of objects of that class in which static variable is defined.
Static variables can be created using
  1. __init__() method
  2. instance method
  3. static method
Script:Write an script which shows the creation of static variables using above three ways.

class Demo:
    a=10
    def __init__(self):
        Demo.b=20
    def fun1(self):
        Demo.c=30
    @staticmethod  # This notation is optional but advisable
    def fun2():
        Demo.d=40

print("Static variable a=",Demo.a," is created in the body of the class")
d1=Demo()
print("Static variable  b=",Demo.b," is created using __init__() function")
d1.fun1()
print("Static variable c=",Demo.c," is created using instance function")
Demo.fun2()
print("Static variable d=",Demo.d," is created using static function")
    
Output:
Static variable a= 10  is created in the body of the class
Static variable  b= 20  is created using __init__() function
Static variable c= 30  is created using instance function
Static variable d= 40  is created using static function

Types of Variables in Python Language (Local and Global)

There are mainly four types of variables that python language provide to us.
These are as follows:
  1. Local variable
  2. Global variable
  3. Instance variable
  4. Static variable
Local Variables:
Local variables are those variables which are defined inside a function. 
Their scope is limited to that function in which they are defined.
They can't be accessible from outside the function.

Global Variables:
Global variables are those variables which are defined outside the function as well as outside the class.
These types of variables can be accessible from anywhere means outside or inside the function or class.
Script: Demonstration of Local and Global Variable

y=7
def fun():
    x=5
    print("x is a local variable")
    print("y is a global variable")
fun()
print("y is a global variable")
    
Output:
x is a local variable
y is a global variable
y is a global variable

From the above script we can conclude that local variables are only accessible inside the function in which they are defined while on other side global variables can be accessible from anywhere in the script.

2/20/2019

__init__() function

  • This is a function which we do not need to call.
  • If we define this function in the class then it is the first function in the life of an object which is called.
  • When we create an object of the class in which this function is defined then this function is called automatically for that object.
  • Mainly this function is used to define instance members of the object.
  • If you have knowledge of java or c++ language, then you can say that this function is just similar to constructor.

**One argument is necessary in __init__ function while we define it.
When an object call this function object itself is passed as a first argument.
class square:
    def __init__(self,side): 
        self.side=side
    def calarea(self):
        x=self.side
        print("The area of square is ",x*x)
        
s1=square(10)
s2=square(20)
s1.calarea()

Output:
The area of square is  100
The area of square is  400

Example2: Write an script to calculate the area of rectangle whose length and breadth are taken from the user in object oriented way.
class rect:
    def __init__(self,l,b):
        self.l=l
        self.b=b
    def calarea(self):
        x=self.l
        y=self.b
        print("The area of rectangle is",x*y)

a,b=int(input("Enter length ")),int(input("Enter breadth "))

r1=rect(a,b)
r1.calarea()

Output:
Enter length 3
Enter breadth 4
The area of rectangle is 12

2/12/2019

Object Oriented programming using python

If a language support object oriented way of programming it means that a large problem can be divided into smaller ones and then we can combine them to get the target output.
It means by using OOP's (Object Oriented Programming) we can achieve the solution of large and complex problems in easier way as compared to procedural programming.
The main features of object oriented programming are
  • Classes and objects
  • Polymorphism
  • Inheritance
  • Encapsulation
  • Abstraction
Classes and Objects:
  • If we are creating a class, it means that we are actually creating a new datatype.
  • We can encapsulate(bind) data members, and functions (methods) into a single unit which is called class.
  • Basically class is identified by some name.
  • Class represent a blueprint of the object(real world entity).
  • int, float, complex, list, tuple, set, dict are all examples of predefined classes in Python.
  • Object represent the instant of class.
  • By defining a class, we are not actually consuming any memory. Memory will be consume when objects of that class are made, means object consumes memory.
  • We can create any number of objects of a single class.
  • A simple script is given below for defining and creating object of the class.
 class M1:
    s=10
    def fun1():
        print("This is function of class")


print(M1.s) # M1 is class object
M1.fun1()
o1=M1()   #We are creating a new object and o1 will referring it
print(o1.s)
o1.fun1() # Error Come here


The output of this script is:
10
This is function of class
10
Traceback (most recent call last):
  File "/root/Desktop/p1.py", line 10, in <module>
    o1.fun1()
TypeError: fun1() takes 0 positional arguments but 1 was given 


Have a look on the above script and try to understand the flow of the program. Don't worry why error is coming, we will understand it later.
2/11/2019

Explicitly raising and handling of Exception

Explicitly raising and implicitly handling:

x=int(input("Enter first number "))
y=int(input("Enter second number "))
if y==0:
    raise ZeroDivisionError("Cannot divide by zero")
rslt=x/y
print("The result is",rslt)

if y=0 then output of above script can be as:
Enter first number 1
Enter second number 0
Traceback (most recent call last):
  File "/root/Desktop/p1.py", line 4, in <module>
    raise ZeroDivisionError("Cannot divide by zero")
ZeroDivisionError: Cannot divide by zero # message will be printed here


Explicitly raising and implicitly handling:

a=int(input("Enter first number "))
b=int(input("Enter second number "))
try:
    if b==0:
        raise ZeroDivisionError("Cannot divide by zero")
    rslt=a/b
    print("The result is",rslt)
except ZeroDivisionError as e:
    print("This is exception:",e)
finally:
    print("This program is created by Mayank Kumar Prajapati")


if b=0 then output of above script is as:
Enter first number 1
Enter second number 0
This is exception: Cannot divide by zero
This program is created by Mayank Kumar Prajapati


Implicitly raising and handling of Exception

Implicitly raising and implicitly handling:

a=int(input("Enter first number "))
b=int(input("Enter second number "))
rslt=a//b
print("The result is",rslt)


If b=0 then result can be as:
Enter first number 2
Enter second number 0
Traceback (most recent call last):
  File "/root/Desktop/p1.py", line 3, in <module>
    rslt=a//b
ZeroDivisionError: integer division or modulo by zero


if b!=0 then result will be:
Enter first number 2
Enter second number 1
The result is 2


Implicitly raising and explicitly handling:

a=int(input("Enter first number "))
b=int(input("Enter second number "))
try:
    rslt=a//b
    print("The result is",rslt)
except ZeroDivisionError as e:
    print(e)
else:
    print("Program executed successfully")
finally:
    print("This program is created by Mayank Kumar Prajapati")


if b=0 then the result of b=above program is:
Enter first number 2
Enter second number 0
integer division or modulo by zero
This program is created by Mayank Kumar Prajapati


if b!=0 then result is:
Enter first number 2 
Enter second number 1
The result is 2
Program executed successfully
This program is created by Mayank Kumar Prajapati

2/10/2019

try, except and finally

In try block we have to write that code of our program, where we expecting that exception will come.

Some points about try and except:
  • We cannot have any except block without try block.
  • In except we have to catch the object thrown by that line which is present in the try block.
  • There can be more than one except block for a single try block.
  • except block only executed when any exception occurs, if no exception occurs program will execute normally and don't enter in the except block.
  •  If we have not made any except block, then python will handle exception automatically.
  • We can also accept more than one exception in the except by writing the name of the class separated by the ",". 
Some points about finally block:
  • This block always be executed, it doesn't matter whether the exception is occurred or not in our program.
  • finally always come after the except block.
  • finally works before the default exception catch mechanism of python.
  • try block should have at least one except or finally block.
  • We can't made more than one finally block.
  • If we made except by ourselves and exception occurs, then in this case, first except block will be executed and then finally block executed.
Note* We can also use else block with try block. else block will execute when there is no exception occurs in our program.
We have to write the else block before finally block and after except block.


try:


   """ write your code here""" 

except ExceptionClassName1: 

   """Write your code here""" 


except ExceptionClassName2: 

   """Write your code here" 

else:   

   """Write your code here"""

finally:

    """Write your code here"""
2/09/2019

Exception Handling

When a program terminates in abnormal condition, it is called exception.
The normal flow of the program is disturbed if any exception situation occurs in the program. The simplest example of exception situation is as:
e.g. Suppose we have to calculate a/b where a and b are entered by the user. What will  happen if user unknowingly enter the value of b 0. Exception will arise, because we can't divide any number by 0.

Our program will terminate from that line where exception is occurred.
Python has mechanism to deal such kinds of situation. We have 4 ways to deal with these kinds of situation.
  1. Python raise exception and also handle it implicitely
  2. Python raise raise exception and user handle it explicitely
  3. User raise exception and python handle it implicitely
  4. User raise exception and also handle it explicitely
 Exceptions can be of two types.
  1. Predefined Exceptions
  2. User defined Exceptions
The keywords that we will use in Exception handling are as follows:
  1. try
  2. except
  3. finally
  4. raise 



2/07/2019

Anonymous function (Lambda Expression)

Anonymous function is that function which has no name.
lambda keyword is used for defining anonymous function.

Script1: Write anonymous function to calculate the sum of two variables.

sm=lambda a,b: a+b
n1=int(input())
n2=int(input())
ans=sm(n1,n2)
print(ans)

Script2: Write anonymous function for calculating factorial of a given number.

f=lambda n: 1 if n==0 or n==1 else n*f(n-1)
n=int(input("Enter the number "))
ans=f(n)
print("The factorial of",n," is",ans)

Recursion

When a function calls itself, then this is called recursion.
These are some of the script which are illustrating the use of recursion.

Script1: Write an script to print natural numbers from 1 to n in descending order using recursion, the value of n will be entered by the user.

def printnatno(n):
    if n==0:
        return
    else:
        print(n)
        printnatno(n-1)

n=int(input("Enter the value of n "))

printnatno(n)


Script2: Write a function to calculate the factorial of a number using recursion.

def calfact(n):
    if n==0 or n==1:
        return 1
    else:
        return n*calfact(n-1)

n=int(input("Enter the number "))
ans=calfact(n)
print("The factorial of {} is {}".format(n,ans))

2/06/2019

Examples on functions

Script1: Write a function in python which can calculate the factorial of a number entered by the user.
def calfact(n):
    x=1
    while n!=1:
        x*=n
        n-=1
    return x

a=int(input("Enter the number "))

f=calfact(a)
print("The factorial is {}".format(f))

Script2: Write a function in python which can print the fibonacci series up to n numbers, value of n is entered by the user.
def printfibo(n):
    x=1
    y=2
    if n==1:
        print(x)
        return
    print(x,end=" ")
    print(y,end=" ")
    while n!=2:
        print(x+y,end=" ")
        x,y=y,x+y
        n-=1

n=int(input("Enter the number "))

printfibo(n)



Script3. Write a function which can decide whether the entered number by the user is prime or not.
def checkprime(n):
    i=2
    if n==1 or n==2:
        print("Number is prime")
        return
    while i!=n-1:
        if n%i==0:
            print("Number is not prime")
            break
        i+=1
    else:
        print("Number is prime")

x=int(input("Enter the number "))

checkprime(x)

Script4: Write a function which check whether the number entered by the user is armstrong or not.
def checkarmstrong(n):
    sum=0
    temp=n
    while n!=0:
        sum+=(n%10)**3
        n//=10
    if sum==temp:
        print("Number is armstrong")
    else:
        print("Number is not armstrong")

print("Enter the number ")

x=int(input())
checkarmstrong(x)

Script5: Write a function which check whether the entered string is palindrome or not.
def checkpalindrome(s):

    m=s[::-1]
    if m==s:
        print("String is palindrome")
    else:
        print("String is not palindrome")

print("Enter the string you want to check ")

x=input()
checkpalindrome(x)



2/05/2019

Variable length arguments

Variable length arguments:
If a function has variable length arguments, it means it has the capability to accept any number of arguments.
Variable length argument is prefixed with *.
The type of variable length argument is tuple.

Write a function which can return the sum of any number of arguments passed to it.
def f1(*a):
    return sum(a)

print(f1(2)) # 2
print(f1(2,3)) # 5
print(f1())  # 0


Note* In this case keyword argument is compulsory to set the value of second argument.
def f1(*m,s):
    print(m,s) # (2, 3, 4) 5

f1(2,3,4,s=5)


Variable length keyword arguments:
If we write ** then its type will be dictionary.
It always accepts keyword arguments.
If positional arguments are passed to it, it will shows error.

def f1(**x):
    print(x)

f1(a=2,b=3) # {'a': 2, 'b': 3}
f1(a=1,b=2,c=3) # {'a': 1, 'b': 2, 'c': 3}

f1(a=1,a=2) # will show error

Types of arguments in a function

There can be different types of arguments which a function can have. These are as follows:
  • Default arguments
  • Positional arguments
  • Keyword arguments
  • Variable length arguments
  • Variable length keyword arguments
Default arguments: The usage of default argument is shown below in the simple python script.

def addition(a,b,c=0):
    return a+b+c

x=addition(2,3)
y=addition(2,3,4)
print(x,y) # 5 9

Here addition function can accept maximum three arguments and minimum two arguments. If we pass only two arguments then third argument will automatically initialized to 0 and we get the sum of two arguments in return.
If we pass three arguments then third argument hold that value which is passed by us and in return we get the sum of three numbers.

Positional and keyword arguments:
def f1(x,y):
    print("x=",x,"y=",y)

f1(1,2) # Positional arguments
f1(x=1,y=2) # Keyword arguments
f1(y=1,x=2) # Keyword arguments

f1(x=1,y) # error comes
f1(3,x=3) # error comes
In keyword arguments order is not really important. You can pass the keyword argument in any order you want, but in case of positional arguments order matters.

Note* Positional arguments can never come after keyword arguments, if we do so error will come.

2/04/2019

Functions Introduction

Function is actually a block of code.
It increases the reusability of code in our script or program.
The syntax for function in the python language is as:
def f1():
    statement 1
    statement 2
A function can take any number of arguments.

Example1: Write an script to multiply two  numbers entered by the user.
def multiply(n1,n2):
    print("The multiplication is ",n1*n2)

a,b=int(input("enter first number")), int(input("Enter second number"))

multiply(a,b)

A function can also return any kind of data, means it can be used to return an integer, string, list tuple etc.

Example2: Write an script which return the factorial of a given number.
def fact(n):
    s=1
    while n!=1:
        s=s*n
        n-=1
    return s

x=int(input("Enter the number "))
f=fact(x)
print("factorial is",f)

Note* If a function does not return anything in python then it will automatically return None.


Input data structure from user

Reading multiple values:
There can be many ways to take multiple in inputs from the user. Some of them are shown below.
x,y=int(input("Enter first number")),int(input("Enter second number"))

x,y=input("Enter two numbers").split()


x,y=map(int,input().split())


Note* x,y=int(input("Enter two numbers")).split() is wrong. This will show ValueError.

Taking different Values as input using eval() method:
x,y,z=[eval(x) for x in input().split()]
If we give input: 1 2 "mayank"
x and y type are int and z type will be string automatically. We don't need any type of conversion here because we are using eval() function for that.

Taking list as input from user:
l=[eval(x) for x in input().split()]

l=list(map(int,input().split()))

Taking tuple as input from user:
t=tuple([eval(x) for x in input().split()])

t=tuple(map(int,input().split()))

Taking set as input from user:
s=set([eval(x) for x in input().split()])

s=set(map(int,input().split()))

Taking dictionary as input from user:
d={int(input("enter key ")) : input("enter value ") for i in range(3)}
Here second input() method execute before the first input() method.

d={x: input() for x in range(3)}

Here 0 1 and 2 will becomes key and values will be enter by user.






1/14/2019

Methods related to dictionary data structure

del() method: This method is used to delete any item from the dictionary.
d={1:"mayank",2:"aniket",3:"prajapati"}
del(d[1])
print(d) # {2: 'aniket', 3: 'prajapati'}


clear() method: This function is used to delete all the values from the dictionary and our dictionary will be emptied after executing this function.
d={1:"mayank",2:"aniket",3:"prajapati"}
d.clear()
print(d) # {}


copy() function: This function is used to copy all the items of dictionary into another object.
d={1:"mayank",2:"aniket",3:"prajapati"}
e=d.copy()
print(e) # {1:"mayank",2:"aniket",3:"prajapati"}


pop(): This function will take key as an argument. This function will only return value not the item.
d={1:"mayank",2:"aniket",3:"prajapati"}
x=d.pop(1)
print(x) # "mayank"

print(d) # {2:"aniket",3:"prajapati"}

popitem(): This function does not require any argument. It will randomly remove an item from the dictionary and return that item as a tuple.
d={1:"mayank",2:"aniket",3:"prajapati"}
x=d.popitem()

print(type(x)) # tuple
print(x) # (3, 'prajapati')
print(d) # {1:"mayank",2:"aniket"}




1/10/2019

Introduction to dictionary

Dictionary concept is used for association purpose.
We use dictionary data structure when there is an association required between two objects.
Values are stored pairwise in dictionary in the form of keys and values.
Key act as primary key (keys cannot be repeated).
Value repetition can be possible in dictionary data structure.
The nature of key and values can be heterogeneous.
Indexing and slicing cannot be used in dictionary.
There is no specific order for storing elements in the dictionary.
Dictionary is mutable data structure.
We can use add, delete and update methods in dictionary data structure.
Dictionary is denoted using {}.

How to create an empty dictionary??
d={}
print(type(d)) #<class 'dict'>
Empty dictionary can also be created using dict() method as shown below.
d=dict()

Storing values in dictionary:
d={1:"Mayank",2:"Aniket",3:"Prajapati"}
print(d)


Accessing elements of dictionary:
We can access the element of dictionary using for loop as shown below.
d={1:"mayank",2:"aniket",3:"prajapati"}
for x in d:
    print(d[x],end=" ")

Output: mayank aniket prajapati



Accessing specific element using key in dictionary:
 d={1:"mayank",2:"aniket",3:"prajapati"}
print(d[2]) # aniket
print(d[4]) # KeyError
1/09/2019

pop, discard, remove methods of Set Data Structure

pop() function: This function will remove any random element from the set.
It will return that element which is removed by it.
If set is empty this function will give error (KeyError).
s1={1,2,3,4}
s1.pop()
print(s1) # {2,3,4}

discard() function: This function will remove the specified element from the set.
The return type of this function is None.
s1={1,2,3,4}
s1.discard(2)
print(s1) # {1,3,4}

There is no error come if the specified element is not present in the set or if the set is empty.

remove() function: The return type of this function is None.
It will give error (KeyError) if the specified element is not present in the set or if the set is empty.
s1={1,2,4}
s1.remove(2)
print(s1) # {1,4}

copy() function: This function is used to copy whole data of one set to other set object.
s1={1,3,4}
s2=s1.copy()
print(s2) # {1,3,4}

Note** List cannot be an element of set.
Tuple can be an element of set.



1/08/2019

Methods related to Set

add(): This method is used to add any new value to set data structure.
s={1,2,3}
print(id(s))
s.add(4)
print(s)
print(id(s))


Both id will be same, this proves that set is mutable data structure.

update() function: This function actually useful when we want to add all the elements of a sequence or more than one sequence into a single set.
s={1,2,3}
s.update([4,5])
print(s) # {1,2,3,4,5}

We can also pass more than one sequence in the update method.
s={1,2,3}
l1=[1,4,5]
l2=[6]
s.update(l1,l2)
print(s) # {1,2,3,4,5,6}


intersection() method: The return type of intersection method is a set. The simple example of usage of intersection method is given below.
s1={1,2,3}
s2={3,4,5}
s3=s1.intersection(s2)
print(s3) # {3}


union() method: As suggested by the name it will perform union operation between the two sets. Its return type is also a set.
s1={1,2,3}
s2={4,5,6}
s3=s1.union(s2)
print(s3) # {1,2,3,4,5,6} 


issubset() method: This function will tells us whether a given set is a subset of targeted set or not. Its return type is boolean.
s1={1,2,3}
s2={1,2}
print(s2.issubset(s1)) # True


issuperset() function: This method will tells us whether a given set is a superset of targeted set or  not. Its return type is also boolean.
s1={1,2,3}
s2={1,2}
print(s1.issuperset(s2)) # True



clear() function: This function is used to remove all the elements from the set data structure, means it will empty the targeted set.
s={1,2,3}
s.clear()
print(s) #set()


1/04/2019

Set Introduction

Set is a data structure in Python which is denoted by {}.
Duplicate values are not allowed in set.
We cannot use indexing and slicing here.
It is mutable data structure.

Creation of empty set:
s=set()
print(type(s)) # set
Note* s={} is not empty set. It is dictionary.

Set does not preserve any sequence of storing data elements.
s=set("mayank")
print(s) # {'n', 'm', 'a', 'y', 'k'}

Set can only take sequence as argument.
s=set([1,2,2,3,4]) # 2 will store only once as repetition is not allowed here. 
print(s) # {2,1,4,3}






1/03/2019

Some methods related to tuple data structure:

max() and min(): These functions are used to calculate the max and minimum element from the tuple.
t=(1,2,3)
print(max(t)) # 3
print(min(t)) # 1

sum() function: This function is used to calculate the sum of all the elements of the tuple
t=(1,2,3)
print(sum(t)) # 6

len() : This function is used to calculate the length of the tuple.
t=[1,2,3,3,4]
print(len(t)) # 5

Accessing element of tuple using for loop:
We can access elements of tuple using for and while loop.
t=(1,2,3)
for x in t:
    print(x)

Accessing elements of tuple using while loop:
t=(1,2,4,4)
l=len(t)
i=0
while i<l:
    print(t[i])
    i+=1

Taking tuple from user:
t=tuple([eval(x) for x in input().split()])
Note: If we are giving string input here we have to use quotes in the input as well.

If we wan to store only integer in the tuple then we can do like this.
t=tuple([int(x) for x in input().split()])
print(t)

We can also use map() function for this purpose.
t=tuple(map(int,input().split()))
print(t)



Introduction to tuple data structure

Tuple is a sequential data structure.
As string and list tuple also support indexing and slicing.
The elements of tuple can be heterogeneous in nature.
Tuple is immutable data structure.
We have to use () to defining the tuple.
We cannot use append() method in tuple because it is immutable data structure.
example
t=(1,2,3,4)
print(type(t)) #tuple

Creating an empty tuple:
tuple() method can be used to create an empty tuple.
t=tuple()
print(type(t)) # tuple

Creating a tuple with single element:
t=(1,) # , is necessary if we are creating a tuple of single element, otherwise it will be int type.

Conversion of list into tuple:
We can also convert list data structure into tuple as shown below.
l=[1,2,3,4,5]
t=tuple(l)
print(t) # (1, 2, 3, 4, 5)


Problems on String

Problem1: Check whether the string entered by the user is palindrome or not.
s=input()
if s==s[len(s)::-1]:
    print("Palindrome")
else:
    print("Not palindrome")

Problem2: Write script to count the number of lower case letters in Python.
s=input()
count=0
for x in s:
    if x.islower():
        count+=1
print("Number of lower case letters are",count)

Problem3: Write an script to count the number of digits in a given string.
s=input()
count=0
for x in s:
    if x.isdigit():
        count+=1
print("Number of digits are",count)

1/02/2019

More functions of String

list(): String can be converted to list using list() method.
s="mayank kumar"
l=list(s)
print(l) # ['m', 'a', 'y', 'a', 'n', 'k', ' ', 'k', 'u', 'm', 'a', 'r']

isalnum(): This function returns True if all the characters of string are A-Z, a-z or 0 to 9, else return False.
s="sm32"
print(s.isalnum()) #True

isdigit(): This function returns True if all the characters of string are 0 to 9.
s="0383m"
print(s.isdigit()) # False

isalpha(): This function returns True if all the characters of the string are A -Z or a-z.
s="mayank"
print(s.isalpha()) # True

isupper(): This function returns True if all the letters of string are in capital letters.
s="MAYANK"
print(s.isupper()) #True

islower(): This function returns True if all the letters in the string are in lower case.
s="mayank"
print(s.islower()) # True

Functions Related to string

len() method: This function is similar to the len() function we have used in case of list data structure.
This will give us the length of the string.
s="mayank"
print(len(s)) #6

upper() method: This method is used to convert all characters of string into uppercase. The original string is not affected by this method.
s1="mayank"
s2=s1.upper()
print(s1) #mayank
print(s2) # MAYANK

lower() method: It converts all the characters of string into lower case. It is similar to upper() method and does not affect the original string.
s1="Mayank"
s2=s1.lower()
print(s1) #Mayank
print(s2) # mayank

startswith() and endswith() method: This method returns True or False. If the string starts with the supplied sequence it will return True otherwise return False.
s="Mayank"
s.startswith("Ma") #True
Similarly ends with check the ending of the string with given sequence.
s.endswith("an") #False

split() function: The return type of this function is a list. String is separated on the basis of given character. This character will not be included in the final list.
s="mayank kumar prajpati"
l=s.split(" ")
print(l) #["mayank","kumar","prajapati"]



Introduction To String

String is a sequential data structure.
Indexing and slicing is supported by String.
It is immutable.
String also support negative indexing. Negative indexing start from -1 in the last.
example:
s="Mayank"
print(s,type(s)) # Mayank <class 'str'>
print(s[-2]) # n

How to take string from user??
String can simply be taken from user using input() function.
s=input()
print(s)
String also support concatenation. Means we can concatenate a string to another string also.
s="Mayank"
print(id(s)) 
s+="Prajapati"
print(id(s))
Both will print different id which shows that string is immutable data structure.

Conversion of list into string:
We can convert a whole list into a string. This can be done simply using the join method. A simple script which will illustrate this concept is given below:
l=["mayank", "kumar", "prajapati"]
s=" ".join(l)
print(s) # mayank kumar prajapati

Taking list from user

There can be many ways to take the list from the user.]
1. Taking element one by one and append it in  the list
l=list()
n=int(input("enter number of elements : "))
for i in range(n):
    x=input()
    l.append(x)
print(l)

2. Using map() function:
l=list(map(int,input().split()))
This function converts the value entered by the user and append it into the list one by one.
split() function tells us where inputs end. By default it is space. After space character next input is counted.

3. Using for loop in single line:
l=[int(x) for x in input().split()]

4. Using eval() function:
l=eval(input("Enter the list"))   #[1,2,3]
print(l)
   


1/01/2019

append,pop and remove function in List

append() function:
This function is used to append any value at the end of the list.
eg
l=[1,2,3]
l.append(4)
print(l) # [1,2,3,4]

pop() function:
It deletes the last value of the list by default.
It returns the value which is deleted  by this method.
It raises IndexError if no element found.
l=[10,20,30]
x=l.pop()
print("The deleted element is",x)
print(l)  # [10,20]
pop function can also be used to delete any specific value from the list as shown below.
l=[1,2,3]
l.pop(2) #here 2 is the index means 3 will be deleted from the list
print(l) # [1,2]

remove() function:
This function does not return the value it has removed from the list.
It always requires an argument.
It raises ValueError if element is not found in the list.
l=[1,2,3]
l.remove(2)
print(l) # [1,3]


Some useful Functions of List data structure

There are some most important functions of list data structure which we can use in our script without knowing the internal structure of the functions.

len() function: This function will give us the length of the list.
l=[1,2,"mayank",3]
x=len(l)
print(x) # 4

index(): This method is used to find out the index of any element in the list.
The usage of this function can be as:
l=list()
l=[1,2,3,4,5]
print(l.index(3)) #2
index() method gives IndexError if we have not supplied a right index to this function.

Another usage of index() method is as:
l=[1,2,3,4]
i=l.index(2,3) # will start find index of two and searching will start from index 3
print(i)  # gives ValueError

reverse() function:  This function will reverse the element of the whole list.
l=[1,2,3]
l.reverse()
print(l) # [3,2,1]

sort() function: This method is used to sort the given list.
l=[2,5,1,4,6,2]
l.sort()
print(l) # [1,2,2,4,5,6]

clear() function: This function is used to delete all elements from the list.
The usage of this function is as follows:
l=[1,2,3,4]
l.clear()
print(l) #[]

max() function: This function returns the maximum value from the given list.
A simple script to demonstrate this function is as:
l=[2,3,5,2,6,6,4]
m=max(l)
print(m) #6

min() function: This function returns the maximum element from the list.
The script can be as:
l=[1,2,,5,2,5]
m=min(l)
print(m) #1

sum() function: This method returns the sum of all values present in the list.
example:
l=[1,2,3,4]
s=sum(l)
print(s) #10


List Introduction

List:
List is a data structure in Python which is very similar to arrays in C.
The difference between array and list is that array can able to store only homogeneous elements while in list we can have non homogeneous elements also.
List is a iterative and sequential data structure.
Indexing and slicing is possible in case of list data structure.
List are denoted by [].
Duplicates values are allowed in list data structure.
Creation of empty list::
If we want to create an empty list then we can do this in two ways. These are given below:
l=[]  # empty list
l=list()  # empty list

Initializing the list:
l=[1,2,3,4]
print(l[2])  # 3

Printing whole list:
We can print the all elements of list in two ways.
print(l)

Using for loop

for x in l:
     print(x) 

Editing values of List:

l=[1,2,4]
print(l[0])  # 1
l[0]=8
print(l[0])  # 8