Showing posts with label pandas. Show all posts
Showing posts with label pandas. Show all posts

Thursday, December 24, 2020

Methods to Process Lists in python

 


Lists and Tuples in Python

 


Lists and Tuples in Python

 


Lists and Tuples in Python

 

Lists and Tuples in Python

 

 

* A sequence is a datatype that represents a group of elements

* The purpose of any sequence is to store and process a group of elements

* In Python ; strings , lists , tuples and dictionaries are very important type of sequence datatypes

* All sequences allow some common operations like indexing and slicing

 

====================================================================

 

Q) What is a List ?

* A list is similar to an array that consists of a group of elements or items

* As an array , a list can also store elements

* But there is a major difference between an array and a list

* An array can store only one type of element whereas a list can store different types of elements

* Therefore , lists are more versatile and useful than an array

* Lists are the most used among all the datatypes in Python programs

 

====================================================================

 

* Let us consider a case of taking a List in our daily lives ... example , if we take marks of a student in 5

subjects such as :

 

80 , 85 , 82 , 94 , 86

 

then one can see that all of these belong to the same datatype that is an integer type . Therefore , one can

represent such elements as an array . But we need more information about the student , like the roll

number of the student , name , gender , marks etc of the student . In totality , the full information about the

student looks such as this :

 

[ 101,Andy,M,80 , 85 , 82 , 94 , 86 ]

 

Here .. one can see that there are various types of data . Here , the roll number shown for the person is

an integer i.e. 101 . Gender ('M') is a character and the marks shown are again in the form of integers

 

[ 80 ,85 , 82 , 94 , 86 ]

 

In general .. this type of information is stored and processed . This type of information cannot be stored

in an array as the data is heterogeneous in nature and an array stores only homogeneous type of data that

means an array stores only one type of elements .

 

Therefore , in order to store such type of data one needs to use a list datatype . A list can store different types of elements . In order to store the student's information , one can create a list in the following manner :

 

student = [101,'Andy','M',80,85,82,94,86]

 

One may observe that the elements of the 'student' list are stored within square braces [] . One can create

an empty list without any elements by writing empty square braces such as :

 

empty_list = [ ] # this is an empty list

 

Therefore , one can create a list by embedding the elements inside a pair of square braces [ ] . The elements in the list are separated by a comma ( , ) . In order to view the elements of a list as a whole , one can pass the list name to the print() function as in the following manner :

 

print(student)

 

The list appears in the manner below :

[101,'Andy','M',80 , 85 , 82 , 94 , 86]

 

Indexing and slicing operations are common operations that can be done over lists . Indexing represents accessing elements by their position number in the list . The position numbers start from 0 onwards and are written inside square braces as :

 

student[0] , student[1] etc .

 

This means that student[0] represents 0th element , student[1] represents 1st element and so forth . For example , in order to print the student's name one can write :

 

print(student[1])

Output

Andy

 

Slicing represents extracting a piece of the list by mentioning the starting and the ending position numbers . The general format of slicing is [ start : stop : stepsize ]. By default , 'start' will be 0 , 'stop' will be the last element and 'stepsize' value happens to be 1 .

 

Example - student[0:3:1] represents a piece of the list containing 0th to 2nd element of the list .

print(student[0:3:1])

output

[101,'Andy','M']

 

The above statement can also be written in another format as given :

print(student[:3:])

output

print(101,'Andy','M')

 

===================================================================

Python program to create lists with different types of elements

===================================================================

# create lists with integer numbers

num = [ 10 , 20 , 30 , 40 , 50 ]

print(' Total List = ',num)

print(' First = %d , Last = %d ' %(num[0],num[4]))

# create a list with strings

names = ["Andy","Barry","Carrie","Derry"]

print(' Total List =',names)

print(' First = %s , Last =%s' %(names[0],names[3]))

# create a list with different data type of elements

x = [ 10 , 20 , 30 , "Garry" , " Barry " ]

print(' Total List = ', x)

print(' Total List = ', x)

print(' First = %d , Last = %s ' %(x[0],x[5])))

 

Output

Total List = [10,20,30,40,50]

First = 10 , Last = 50

Total List = ["Andy","Barry","Carrie","Derry" ]

First = Andy , Last = Derry

Total List = [ 10 , 20 , 30 , "Garry" , " Barry " ]

First = 10 , Last = Barry

 

Wednesday, December 23, 2020

Core Python - Python program to create two decorator functions and use them in calling functions


Core Python - Python program to create two decorators

# decorator increments value of function by 5

def decorator1(fun):

    def inner():

    value = fun()

    return value + 5

    return inner

# decorator that doubles value of a  function

def decorator2(fun):

    def inner():

    value = fun()

    return value*2

    return inner

# take a function to which decorator  could be applied

def num():

    return 10

# call num() function and apply decor1  and then decor

result_fun = decorator1(decorator2(num))

print(result_fun)

print(result_fun)



Output

25



One can apply the decorators to num() function using '@' symbol .

Generators in Python


Generators in Python


Generators are functions that return a sequence of values . A generator function is written like an ordinary function but it uses 'yield' statement . This statement is useful to return a value .

Example , one can write a generator function to return numbers from x to y .

# here , the generator function name is  'mygen'

def mygen(x,y):

    while x <= y :

    yield x 

    x = x + 1        # increment value of x by 1


One can call this function by passing the values 5 and 10 as follows :

gen_obj = mygen(5,10)

Here , the mygen() function returns a generator object that contains sequence of numbers as returned by 'yield' statement . So 'gen_obj' refers to the generator object with a sequence of numbers from 5 to 10 . One can display the numbers from the "gen_obj" .One can display the numbers from "gen_obj" using display the numbers from "gen_obj" using a for loop as :

for i in g:

    print(i,end=' ')

In the following program , one can create a generator function that generates numbers from x to y and display those numbers .


Python program to create a generator that returns a sequence of numbers from x to y

# generator returns sequence from x to y

def mygen(x,y):

    while x <= y:

    yield x

    x = x + 1


# fill generator object with 5 and 10

gen_obj = mygen(5,10)

# display all numbers in the generator

for i in gen_obj:

    print(i,end = ' ')


Output

5 6 7 8 9 10

Once the generator object is created , we can store the elements of the generator into a list and use the list as we want . For example , to store the numbers of generator 'gen_obj' into a list 'lst' one can use the list() function as :

lst = list(gen_obj)

Now , the list 'lst' contains the elements:

[5 6 7 8 9 10]

If we want to retrieve element by element from a generator object , one can use the next() function as :

print(next(gen_obj))

which would display the first element in "gen_obj". And , when we call the above function the very next time , it will display the second element in "gen_obj" and by repeatedly calling the next() function , we would be able to display all the elements of "gen_obj" .

In the following program , a simple generator is created that returns 'A','B','C'


def mygen():

     yield 'A'

     yield 'B'

     yield 'C'


Here , mygen() is returning 'A','B','C' using yield statements . Here , yield statement returns the elements from a generator function into a generator object . And , when we call the mygen() function , it is expressed as follows :

gen_obj = mygen()

Here , the characters 'A','B','C' are present within the generator object "gen_obj" and they can be referred and called into use using the next(gen_obj) function to refer to the elements .


Monday, December 7, 2020

Global Keyword in Python and its usage

 

Global Keyword in Python

Sometimes, the global variables and the local variables have the same name. In such a case, the function by default refers to the local variable and ignores the global variable. Therefore, the global variable is not accessible inside the function but it is present outside the function where it is globally accessible.

 Program

# Python program to demonstrate the concept of  global and local variables, same 

# name used for  global and local variables in the sample code


var = 10 # this is global variable

def somefunction():

var = 20 # this is a local variable

print(' value of variable =',var) # local var


somefunction()

print(' variable value =',var)


 

Output

value of variable = 20

variable value = 10

 

When the programmer/user wants to use the global variables inside a function, he can use the keyword 'global' before the variable in the beginning of the function body.

  

For example :

global var

 

In the given programmatic method, the global

variable is made available to the function and the

programmer can work with it in whichever manner the programmer/user wishes to work with the provided object or variable .In the following program, a method to see how to

work with a global variable inside a function.

 

==================================

Program

A Python program to access global variables inside a function and modify the values .

 

# accessing a global variable inside a function

var = 10                                                                  # this is a global variable

def somefunction():

global var                                                   # this is a global variable

print(' global variable = ',var)              # display global variable

var = 20                                                       # modify global var value

print(' modified variable value = ', var)

 

somefunction()

print(' global variable value = ',var)             # display modified value

 

Output

global variable = 10

modified variable value = 20

global variable value = 20

 

When an issue arises when the global variable name and local variable names are same , the programmer/reviewer/user  will face difficulty to differentiate between them inside a function .

 

For example, if there is a global variable 'a' with some value declared above the function.... Then there is a global variable 'a' with some value declared above the function. Here, the programmer  is writing a local variable with the same name 'var' with some other values inside the function .

 

Consider the following code :

var = 10                                 # this is a global variable

def myfunction():

var = 20                       # this is a local variable

 

In a scenario, when the programmer wants to work with a global variable, then the programmer would use a 'global' keyword . Then the programmer can access only the global variable and the local variable is no more available .

The globals() function can be used to solve this problem of using global variable which would solve the problem .This is a built-in function which returns a table of current global variables in the form of a dictionary.

 

Program

# Python program to get a copy of global variable into a

# function and work with it

 

# same name for global and local variable

 

var = 10                                                       # this is a global variable

def myfunction():

var = 20                                           # this var is a local variable

x = globals()['var']

print('global variable var = ', x)

print(' local variable var = ',var)

myfunction()

print(' global variable value =',var)

 

Output

global variable var = 10

local variable var = 20

global variable var = 10

Local and Global Variables in Python

 

Local and Global Variables in Python

 

When we declare a variable inside a function , it becomes a local variable . A local variable is a variable whose scope is limited only to that function where it has been created .

 

This means that the local variable value is available only within that function and not outside that function .

 

Example

variable 'a' is declared inside the myfunction() function

and hence this is available within that function .

 

Once the code logic comes out of the scope of the function , the variable in use over here that is 'a' is removed from the memory and it is no more available in the memory .

 

Following is an example of a code, which uses a local variable within a function , and when the local variable defined within a function is tried to be accessed outside the scope of the function , an error is produced .

 

# local variable within a function

def myfunction():

a = 1                        # here , a is a local variable

a = a + 1                   # increment local variable value

print(a)

myfunction()

print(a)                              # error , not available

 

 

One can observe from the last statement that is print(a) we are displaying the value of variable 'a' outside the scope of the function . This statement raises an error with a message name 'a' not defined .

 

 

When a variable is declared above a function, the value becomes a global variable. Such variables are available to all the functions which are written after it, If such a variable is declared above a function, then such a variable becomes a global variable. Such type of variables is available to all the functions which are written after it. One can consider a sample piece of code for understanding the same :

 

Example

# global variable example

var_a = 1                                           # this is a global variable

def somefunction():

var_b = 2                                   # this is a local variable

print(' variable a = ',var_a  # call to display global var val

print(' variable b = ,'var_b) # call to display local variable's

somefunction()                                 # call to the function

print(var_a)      # the value is accessible outside function

print(var_b)      # the value is not accessible outside function

rather its value was only obtained when the call to

function 'somefunction' got executed.

Thursday, December 3, 2020

Write a program in Python to calculate the factorial value of a number

 Write a program in Python to calculate the factorial value of a number

When we talk about factorial of a number , then the factorial of that number can be represented in the following manner :

n! = n * (n-1) * (n-2) * (n-3)

So , if one wants to calculate the factorial of a number using a logical code construct , then one may write the same using a decremental loop and the loop iteration would work till the value of the loop iterator reaches the value of '1' and in each of the step of iteration , the cumulative value of the product of the number with a number decremented by 1 at each of the step is multiplied with each other at each of the steps .

Let this be represented in the following manner :


product = 1

while n >= 1:

    product = product * n

    n = (n-1)


Here , first the value of product is initialized to 1 which is the cumulative product of the values is multiplied at each of the step iterated over a while loop and then product of the cumulative end result is published at product of the cumulative end result is published at the end when value of n happens tobe either 1 or greater than or equal to 1 which self deprecates to the value of 1 by reducing the value of n by 1 in each of the steps till the while loop evaluates to the condition true in each of the looping iterations at each of the steps within the while loop The program for the above evaluation can be given in the following manner :


def fact(n):

    """ find the factorial value """

    product = 1

    while n >= 1:

    product = product * n

    n = n - 1

    return product

""" display the factorials of first 10 numbers call fact() function and pass the numbers from 1 to

10 within the fact function as a parameter """

for i in range(1,11):

    print(' Factorial of {} is {}'.format(i,fact(i)))


Output

======

Factorial of 1 is 1

Factorial of 2 is 2

Factorial of 3 is 6

Factorial of 3 is 6

Factorial of 4 is 24

Factorial of 5 is 120

Factorial of 6 is 720

Factorial of 7 is 5040

Factorial of 8 is 40320

Factorial of 9 is 362880

Factorial of 10 is 3628800


Saturday, September 26, 2020

Python Pattern Programming - 25

 Python Pattern Programming - 25



Python Pattern Programming - 24

 Python Pattern Programming - 24



Python Pattern Programming - 21

 Python Pattern Programming - 21



Python Pattern Programming - 20

 Python Pattern Programming - 20



Python Pattern Programming - 18

 Python Pattern Programming - 18



Python Pattern Programming - 17

 Python Pattern Programming - 17



Python Pattern Programming - 16

 Python Pattern Programming - 16



Python Pattern Programming - 16

 Python Pattern Programming - 16