Monday, December 7, 2020

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

Program to check whether a number is a prime number or not

 Program to check whether a number is a prime number or not



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



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


Tuesday, December 1, 2020

Returning Results from a Function in Python

Returning Results from a Function in Python

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

* One can return the result or output from a function using a 'return' statement within the body of a function . 

Example :

return c    # this returns any value assigned to a computing variable acting as storage holder for variable

return 500   # this returns the value 500

return 50000    # this returns the value 50000

return lst          # return a list after computation of any value

return x,y,z        # return any value within a function that necessitates the return of three values as                                         output after computation of any result around these three variables

Another significant result about a function is that a function does not return any result and one need not write the return statement within the body of the function . One can rewrite the sum() function such that it will return the sum value rather than displaying the value .

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

Lets see an example with usage of return statement a python program to find the sum of two numbers and return the result from the function .

def sum(a ,b):

     """ this function returns sum of 2 no.s """

     c = a + b

     return c

     # calling the function by associating a variable to the called function

     x = sum(10,20)

     print('The sum of the function is:',x)

     y = sum(12.5,17.5)

    print('The sum of the function is:',y)

For the above program the output or result returned after computation of the parameter values to the sum function - and the calculated result is returned to the variable c which does the computation and calculation of the values which get stored within the returning variable . Then the returning value is stored into the variables over which the calling function "sum" is assigned to .

So in the above program one can see that the result of .So in the above program one can see that the result of the sum operation is computed using the sum function and then the output of the operation is stored into the values x and y .

In order to understand the concept of functions , one can visualise a function which accepts a number and tests whether the number is even or odd . The function definition can be written in the following manner :


def even_odd(num):

     if num % 2 == 0:

     print(num," is even ")

One may observe that this function has only 1 parameter that is 'num' whose value is to be tested to know whether it is even or odd . But in case , the 'num' is divisible by 2 , then one can say that the number within the parameter is an even number or else the number is an odd number .

Here , '%' operator is called the modulus operator that gives the remainder of the division of the given numbers .And , if the remainder is 0 , then we can display that 'num' is an even number . This logic is used in an even_odd() function .

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

Program - Write a program to test whether a number is even or odd

def test_even_odd(num):

     """ to know whether a number is even/odd """

     if num % 2 == 0:

     print(num," is an even number ")

     else:

     print(num," is an odd number ")

     # call the function

     test_even_odd(9)

     test_even_odd(16)

     #Output

     9 is an odd number

    16 is an even number


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




Calling a Function in Python

 Calling a Function in Python

* A function does not have the power to run on its own

* A function can run only when called by an external calling function

* So after a function has been created in Python , it can only be called later by the help of another function or object by using a name

* While calling a function , one should pass necessary values to the function within the parenthesis in the form :

sum(10,15)

* In the above calling function 'sum'  two values are passed to the calling function whose name is sum and the value arguments passed into the sum function are 10 and 20

* When this statement is executed , the Python interpreter jumps into the function definition where the function sum had been declared with the constituting parameter values which are 10 and 20 into the parameters 'a' and 'b' respectively

* These values are processed within a function body and the corresponding result is obtained for the same 

* These values passed to a function are called as 'arguments'


Program

A function that accepts two values and finds their sum has been provided below .

# a function to add two numbers

def sum(a , b):

    "" this function finds the sum of two numbers ""

    c = a + b

    print('Sum=',c)

    # calling the function

    sum(10,20)

    sum(30,40)


Output

Sum = 30

Sum = 70


In the program , the user of the program is calling the sum() function two times and after the call of the function the output pertaining to each of the called function's statement is obtained as output .

Once a function has been created , the function can be used again and again whenever the need to call that function arises and by this process the functions are made to be reusable and thus are utilised as a set of reusable function or reusable code within a body of bigger code (Project).

One may note from the above discussion , that while the function has been called , an integer type data is passed into the function . But for this type of function , one can pass float type data to the function as well whenever the function gets called at any point of time .

Difference between a Function and a Method in Python

 Difference between a Function and a Method in Python

* A function contains a group of statements and performs some specific task .This means that a function contains some set of statements , iterations and loops which help in formation of a function . Functions also help in performance of some specific tasks like execution of a set of codes or a batch of codes which might be intrinsic to the functioning of some machine or program . Also when a set of functions and codes collaborate with each other , a large scale project in the form of a compound body of code can be created which may have its own initiation and execution and termination .

* A function can be written individually in a Python Program . This means that a function can be written individually within a batch of Python programs as well which means that a program in Python (not only in Python but also in other Programming languages as well ) one can write a program in a suite which may stay isolated and individually or a Python program can also exist within a suite of other functions in a Program

* Method of calling a Python Program is by its name .

* Method of calling a Python Program is by its name.When a function is written inside a class , the function becomes a 'method' .

* A method can be called using the following ways :

objectname.methodname()

Classname.methodname()


* So , one may remember that a function and a method are the very same except the method of placement and the way the methods are called is also an intrinsic method of the way a method can be called .

* Creation of a function means defining a function or writing a function and once a function has been defined , it can be used by calling the function which can in the way presented in the above statements .