Find factorial of a number in python : Python tutorial 25

Find factorial of a number using for loop , while loop and recursion in python :

What is factorial :

Factorial of a number is the multiplication of all the numbers from 1 to that number e.g. factorial of 3 is 1 * 2 * 3 i.e. 6 . To find factorial, we can either use loops or recursive approach. Following examples will explain you properly how to find factorial of a number in python :

Using for loop :

Using for loop we can iterate from 1 to that specific number we want to find out factorial . On each iteration , we will multiply the final result with current iteration count . final result will be 1 at first. So, after the loop will exit, we will get the factorial of that number .

def factorialUsingForLoop(n):
    fact = 1
    for i in range(1,n+1):
        print (i)
        fact=fact*i

    print('Factorial of the number %d is %d'%(n,fact))

if __name__== "__main__":
    factorialUsingForLoop(4)

Find factorial using while loop :

We can similarly find out the factorial of a number using a while loop. On each time , we will decrease the value of the number by 1 and multiply it with the final result.

def factorialUsingWhileLoop(n):
    fact = 1
    while(n>1):
        fact = fact*n
        n = n - 1

    print('Factorial is %d'%(fact))

if __name__== "__main__":
    factorialUsingWhileLoop(4)

Factorial using Recursion :

Recursion means the same function will be called recursively. To find factorial of a number, we can also use recursive approach like below :

def factorialUsingRecursion(n):
    if (n == 1):
        return 1
    else :
        return n* factorialUsingRecursion(n-1)

if __name__== "__main__":
    print "factorial is ",factorialUsingRecursion(4)

Python class and objects : Python tutorial 24

Python classes and objects :

Python is a “object oriented” programming language. In simple words, classes are templates for the objects , and objects are collection of variables and functions.

Defining classes in python :

Class definition looks like :

class ClassName :
    statements

Similar to functions, class definitions should execute at first before running. We can also add one string at the first line of the class with a brief description about the class. This is known as docstring.

class ClassName :
‘’’This is a sample docstring…’''
    statements

Python class object Attribute reference :

While creating a new class , python automatically creates one object with that class name. We can access any class member using dot(.) with the class name :

class DummyClass :
    ''' This is a dummy class '''
    i = 10


print DummyClass.i

It will print 10 . This is known as “Attribute Reference” in python. We can also change the value of “i” using assigning. Add the following two lines at the bottom and it will print “11” on running again :

DummyClass.i = 11

print DummyClass.i

Create a new instance of the class :

Let’s create one new instance of the above class :

class DummyClass :
    ''' This is a dummy class '''
    i = 10


myClass = DummyClass()

print myClass.i

In the above example, we have created a new instance of the class DummyClass and assign it to variable myClass . It will create an empty object myClass .
If you want to change the parameter value’s of a newly created object, one new method __init__( ) should be implemented inside it. __init__( ) is called first when creating new instance of a class.

class DummyClass :
    ''' This is a dummy class '''
    i = 10
    def __init__(self,newval):
        self.i = newval

myClass = DummyClass(11)

print myClass.i

Here, we are passing an argument 11 while instantiating class DummyClass, so it will give 11 as output on the print statement .

Accessing functions in objects :

Accessing functions inside a object is same as accessing variables, i.e. we can access by using a dot ( . ) operator :

class DummyClass :
    ''' This is a dummy class '''
    i = 10
    def __init__(self,newval):
        self.i = newval

    def myfunc(self):
        print ("value of i is = %d "%(self.i))

myClass = DummyClass(11)

myClass.myfunc()

Deleting an object in python :

Python has one garbage collector. It runs periodically and deletes unused objects automatically and free up memory space if an object is not referencing by anything. We can also manually delete an object using del
Let’s make some changes to the above example :

class DummyClass :
    ''' This is a dummy class '''
    i = 10
    def __init__(self,newval):
        self.i = newval

    def myfunc(self):
        print ("value of i is = %d "%(self.i))

myClass = DummyClass(11)

del myClass

myClass.myfunc()

Output :

Traceback (most recent call last):
  File “filename.py", line 14, in 
    myClass.myfunc()
NameError: name 'myClass' is not defined

as we have deleted the myClass object, it has thrown an error that this object is not defined.

Python Exception : Python Tutorial 23

Python Exception : What is an Exception :

Exceptions are errors that raised during execution time. That means your statement is correct but during execution time , it was trying to run a statement that cannot be done . Let’s take an example on a python exception :

for i in range(5,-1,-1):
    print 5/i

Output :

1
1
1
2
5
Traceback (most recent call last):
  File "temp.py", line 2, in 
    print 5/i
ZeroDivisionError: integer division or modulo by zero

i.e. the program was able to run for i = 5 , 4, 3, 2 and 1 . But for i= 0, it throws an exception “ZeroDivisionError” as dividing a number by “0” is not possible.

This exception is a built-in exception , i.e. it is already defined . If a built-in exception occurs, python prints the Name of the Exception and one description. Now, let’s check what happens if an exception is raised :

for i in range(5,-1,-1):
    print 5/i

print ("for loop completed")

After the exception will occure, it will not execute the final “print” line , i.e. the program will stop executing.

Handling Exceptions in python :

We can write programs to handle exceptions manually. Change the above example as below :


try:
    for i in range(5,-1,-1):
        print 5/i
except ZeroDivisionError:
    print "zero division error !!"
print ("for loop completed")

Run this program and the output will be :

1
1
1
2
5
zero division error !!
for loop completed

i.e. , if an exception occurs in the try block, it stop its execution of try-block and moves to the “except” block, runs it and continue execution below try-except .

More than one exception type handling in python :

In the above example, we are handling only one error : ZeroDivisionError. We can also write “except” condition to handle more than one exception as like below :

except (RuntimeError, TypeError, ZeroDivisionError) :
    ……

Here , RuntimeError, TypeError, ZeroDivisionError all these three errors will be handled .

Multiple errors also can be handled as like below :

try :
    // try code
except ValueError as e :
    print “Value Error “,e.strerror
except IOError :
    print “IOError ..”
except :
    print “Unknown exception …”

In this example, we have different except statement for all the three different exceptions. So, we can confirm, what is the actual cause of the exception. If an exception not listed in the “except” blocks are raised, it will run the final “except” block.

try…except….else :

We can also add one extra optional “else” block with try-except statements. It is useful to execute code that must be executed always if try clause does not raise an exception.

try :
    f = open("myfile","w")
    f.write("Hello World !!")
except IOError :
    print "Not able to read/write on the file "
else :
    print "File execution successfully completed"
    f.close()

try..finally :

If you want to execute a piece of code wheather any exception is raised or not in the try block, then place it inside finally block. You cannot use else with finally.

try:
   f = open("myfile", "w")
   try:
      f.write("Hello World !!")
   finally:
      print ("closing the file")
      f.close()
except IOError:
   print "Cannot read/write file"

It will first run the try block. If any exception occurs, it will move to the finally block, and then except block . If no exception is raised, then also it will move to the finally block.

Raising an exception :

For raising an exception in python, we can use “raise” statement . An argument can also be passed with the exception :

try:
    for i in range(5,-1,-1):
        if i == 0 :
            raise ZeroDivisionError("trying to divide by zero..")
        else :
            print 5/i
except ZeroDivisionError as e:
    print e

It will print :

1
1
1
2
5
trying to divide by zero..

Custom Exception in python :

You can also create your own exception in python. We can create a new class for these types of exceptions. But , all custom exceptions should derive “Exception” class directly or indirectly. Following example will clarify your doubts :

class Error(Exception):
pass

class MyCustomError(Error):
print "Custom error...."
pass

try:
raise MyCustomError
except MyCustomError:
pass

Here we have first create one base class “Error” and then the custom exception class “MyCustomError” . “MyCustomError” is derived from “Error” class.

Python program to check palindrome using one if-else : Python tutorial 22

Python Program to check if a string is palindrome or not :

What is a palindrome String ?

A String which is same in both direction i.e. if we reverse the String, it will remain same. e.g. “123454321” is a palindrome String but “12345” is not.

To check if a String is palindrome or not, first we will reverse the String and then check if it is same as the previous or not. Before that, let’s take a look into the slicing operation in python :

Python Slicing operation :

Using python slicing, we can extract one part of a String , lets take a look into the following example :

str = "12345"

print str[1:3:1]

print str[2:0:-1]

print str[::1]

print str[::-1]
It will print the following output :

23
32
12345
54321
str[1:3:1] means it will take the string from character position 1 to 2. “1” means it will read from left to right. Similarly “-1 “ means it will read from right to left. str[2:0:-1] will read from character position “2” to “1” in reverse direction.

If first and second parameter is not mentioned, it will take the full string . Now, to check for palindrome, we will reverse the String and check if it is same as the original or not.

str1 = "123454321"
 
if str1 == str1[::-1] :
     print "Palindrome..."
else :
     print "Not palindrome..."
So, using only one if-else condition, we can check if a String is palindrome or not in python. 
 

Python File operations : Python Tutorial 21

Python File operations : Open, Close, Read , Write and Append to a file in Python :

Python has functions and methods to manipulate files . No external library is required for doing file operations in python. In this tutorial, we will learn different python file operations like reading the content of a file, writing to a file etc.

Why file operations are important ? If you want to store something that can be accessible even after system is restarted , then store it in a file. Files are stored in non volatile memory of a system, so they are available even after the program is terminated. 

Create a file in python :

Lets try to create one “.txt” file first . Before doing any operation on a file, first we must open it using built-in open() function. Create one file file_operation.py and enter the following :

 

f = open(“myfile.txt","w”)

Now run this file and check the folder : a new file “myfile.txt” should be present there.

 

We are using open() function to open a file “myfile.txt” in the folder. It takes two argument : first one is the file name we want to open and second one is the mode of operation for that file. This function returns a file object which can be used to modify and read the file .

 

Mode of operation can be different . Here we are using “w” , that means it will open a file for reading and writing . If the file is not available, it will create a new file.

Following are the different modes and description :

1. Does not create a new file if file is not present :

 

r : open a file for reading .

rb : open a file for reading in binary format.

 

2. Create a new file if the file is not present :

 

w : Open a file for writing .
wb : Open a file for writing in binary format.
a : Open a file for appending.

ab : Open a file for appending in binary format.

 

We can also use a + sign with all of these operations. For “r” and “rb” , it will be open for both read and write. For “w” and “wb”, it will be same : open for both read and write. Similarly, for “a” and “ab”, it will be for both appending and reading.

 

For binary data files like image ,songs etc. , if you are trying to do read and write ,always make sure to use binary mode ‘b’, otherwise it might corrupt the file.

 

Closing a file :

After we done editing the file, we should always close it using close() operation. After closing a file, if you want to do any other operation on it, it will fail. We can check if a file is closed or not properly using “file_name.closed” method. It returns True if it is closed.

 

The best way to perform file operations in python is by using “with” keyword :

 

with open(“myfile.txt”,’r’) as f:
    # do file operations

It will close the file automatically, even if an exception is raised.

 

with open("myfile.txt",'r') as f:
    # do file operations
    f = open("myfile.txt","w")
    print f.closed
print f.closed
If you will run the above function, first will print “False” and the second print will print “True”

Writing to a file in python :

So, we have checked how to open and close a file, now let’s check how to write data to a file . For writing , we use “file.write(string)” . It will write content of “string” to the file “file” and returns none.

 

Let’s modify the above program to write something to a file :

 

with open("myfile.txt",'w') as f:
    f.write("Hello World !!")

Now open the file “myfile.txt” and it should contain “Hello World !!” line.

 

Change it to the following :

 

with open("myfile.txt",'w') as f:
    f.write("Hello World !!")
 
with open("myfile.txt",'w') as f:
    f.write("Hello World again !!")
Run and open the file : it will contain “Hello World again !!” only . Why ? Since we have opened the file using “w” mode, it will overlap everything.

Append in a file :

In the above example, after writing to a file for the second time, it replaces the words . To append more letters to a file, we should use append file mode ( “a”) . 

Your “myfile.txt” file already has “Hello World again !!”  . Now , let’s try to add some more words to this line. Change the .py file as below :

 

with open("myfile.txt",'a') as f:
  f.write("Hello World !!")
fun this file and check the “myfile.txt” : It will contain the following text :
"Hello World again !!Hello World !!"

Reading contents of a file :

We have learnt how to open , close, write and append to file in python. Let’s take a look :

First change “myfile.txt” as below :

 

Line One
Line Two
Line Three

Now we will read these lines : Change the python file as below :

 

with open("myfile.txt",'r') as f:
  print f.read()

It will print all the three lines. We can also pass an argument to the read() function , to indicate how many characters we need to read :

 

with open("myfile.txt",'r') as f:
  print f.read(7)

It will print “Line On”

 

We can also use “readline” and “readlines” methods to read lines :

“readline” prints the first line :

with open("myfile.txt",'r') as f:
  print f.readline()
Output : “Line one”

“readlines” reads all the lines :

with open("myfile.txt",'r') as f:
  print f.readlines()
Output : [‘Line One\n’, ‘Line Two\n’, ‘Line Three’]

Python Program to find the factorial of a Number : Python Tutorial 20

Python program to find the factorial of a number :

The factorial of a number is the product of all the numbers from 1 to that number. e.g. factorial of 5 is 1 * 2 * 3 * 4 * 5 i.e. 120 .

Factorial is denoted by “!” : 5 factorial is denoted by 5!

def fact(x):
     if x == 0 :
          return 1
return x * fact(x - 1)

print fact(5)
The output is “120

In the above example ,
  1. fact() function takes one argument “x
  2. If  “x ” is “0“,  it will return
  3. Else it will return x * fact(x-1) i.e. fact(x-1) will call fact() function one more time with (x-1) as argument . 
  4. It will continue till x is 0 , i.e. the function will return 1
So, for 5, 
  1. it will call 5 * fact (4) 
  2. fact(4 ) will be 4 * fact (3)
  3. fact(3) will be 3 * fact (2 )
  4. fact(2) will be 2 * fact (1)
  5. fact(1) will be 1 * fact (0)
  6. fact(0) is 1
  7. That means , the final output is 
5 * fact(4) 
= 5 * 4 * fact(3)
= 5 * 4 * 3 * fact(2)
= 5 * 4 * 3 * 2 * fact(1)
= 5 * 4 * 3 * 2 * 1 * fact(0)
= 5 * 4 * 3 * 2 * 1 * 1
= 120
Try changing the input number to different and check the result.

Python Package : Python Tutorial 19

Python Package :

What is a python package ? In simple words , python packages are directories containing python files. We love to arrange files in our computer in different directories, like all movies in a “movie” folder or all songs in a “songs” folder etc.

So, what is the use of using packages ? We can keep similar files in the same folder. If your application is of large number of files, then don’t you think that it would be better to place related files in a same folder instead of placing in separate folders ?

Inside a folder or package , we can create another package ,known as sub-package. Similarly , inside a sub-package , we can also have another package. 

How Does python recognises package : 

As packages are simply folders, how does python know these folders are python – packages ? Let’s take a look how to create a python package :

  1. Create a folder and place your python files (.py files ) inside it .
  2. Create one __init__.py file inside the folder.
i.e. if a folder contains “__init__.py” file, it is a package.

Example of python package :

Let’s create a directory “project_dir”. Inside this directory, create one file “main.py”. Now create two more directories “package_one” and “package_two”. Inside “package_one” create two files : “__init__.py” and “one.py” . And inside “package_two” create one file : “two.py”. So the structure will be like :

/project_dir :
                —— main.py
                —— /package_one
                                — __init__.py
                                — one.py
                —— /package_two
                                — two.py
So, “package_one “ directory is a package . Now we will try to call “one.py” from “main.py” and “one.py” from “two.py” .

Edit one.py as : 
def func_one():
    print "inside function one"
Now to call “func_one” of “one.py” from “main.py”, we need to import it first :
from package_one.one import func_one and after that we can call “func_one” .

Edit “main.py” as below : 
from package_one.one import func_one
func_one()
It will print Inside function one .  So, you have seen that we can directly call a function of a package by importing the package . But , how can we call “one.py” from “two.py” ? Both are in the same level !!

using “sys.path.append” . Edit “two.py” as below : 
import sys
sys.path.append('../')
from package_one.one import func_one

func_one()
Now , if you run “two.py” , it will provide the output  “Inside function one “ .

Actually, python check for packages in all directories defined in “sys.path”. So, we have appended the parent path to “sys.path” .
 

Python Module : Python tutorial 18

Python Module :

A python module is simply a python file ( .py file ) with definitions and statements. The file name is the module name. After creating a module, we can use it any other module using “import” command. 
Module is useful for re-usability of the code. You can write one function in one module and import this module in different modules and reuse that function . 

Built in modules : 

We can use built-in modules using the same “import” syntax. e.g. “math” is a built in python module, “sqrt” is one function defined in “math”. To use “sqrt”, we should first import “math” to our program. 
import math
print math.sqrt(4)
This will print 4.0 

Find details of a python module :

As we have seen above, “math” is a system module and “sqrt” is one of its function. How to get all functions available in “math” ? use dir( module_name ) :
import math
print dir(math)
It will print :

['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
Similarly, to get details of a function, we can use “help” .
import math
print help(math.sqrt)
It will print :
Help on built-in function sqrt in module math:
 
sqrt(...)
    sqrt(x)
   
    Return the square root of x.
(END)

User defined python module :

Create one file mymodule.py as below :
def boo():
    return "inside boo function.."
 
def booboo():
    return "inside booboo function.."
Now create one temp.py file in the same folder and import “mymodule” as :
import mymodule
 
print mymodule.boo()
print mymodule.booboo()
If you execute temp.py, It will print the following : 
inside boo function..
inside booboo function..
 
We can also import the name of the functions using from…import statement as below :
from mymodule import boo,booboo
 
print boo()
print booboo()
It will print same result as shown in the above example. 
Or we can import all function names using “ * “ :
from mymodule import *
 
print boo()
print booboo()

Importing a module by renaming it :

We can import a module and rename it using import….as statement :
import mymodule as m
 
print m.boo()
print m.booboo()

Import one module multiple times :

If we import a module multiple times, it is imported only for once. If we include “import” more than one time , then also it will be executed only one time. Let’s change mymodule.py as below :
def boo():
    return "inside boo function.."
 
def booboo():
    return "inside booboo function.."
 
print "mymodule loaded"
Now change temp.py as below :
import mymodule as m
import mymodule as m2
 
print m.boo()
print m.booboo()
run temp.py and you will get the following output :
mymodule loaded
inside boo function..
inside booboo function..
i.e. mymodule.py is run only for once .

Python anonymous or lambda function : Python Tutorial 17

Python anonymous or lambda function :

Anonymous or lambda functions are functions without a name. In python, we can create an anonymous function using a construct called “lambda” unlike “def” keyword we use to create other functions. 

Difference between normal function and lambda function :

def function1(x) : return x ** x

function2 = lambda x : x ** x

print function1(2)
print function2(2)
In the above example, both print statement will give the same result “4” . The difference between both is that the lambda function does not have any return statement. In this example , we are using only one argument but lambda function can have multiple arguments.  
In the above example function2 is a lambda function, “x” is its argument and “x ** x” is the return statement. 

Lambda function as a return statement :

We can also create a lambda function as return statement of other functions like :

def function1(x):
    return lambda y : x * y

print function1(2)(3)
The above example will print 6.

Lambda function with filter() :

filter() takes one list and a function as argument . Using the function, it filters out the elements from the list and returns a new list.

mylist = [ 1, 2, 3, 4, 5, 6, 7, 8, 9]

print filter(lambda x : x % 2 == 0 , mylist)
In this example, filter will pick elements from list “mylist” one by one and it will check if it is divisible by 2 or not. If divisible , it will add it to an another list. This list will be returned at last. So, the output will be : [2, 4, 6, 8]

lambda function with map() :

map() function also takes one function and one list as argument. Similar to filter, it will return one new list. The elements of the list will be the return value for each item of the function.

mylist = [ 1, 2, 3, 4, 5, 6, 7, 8, 9]

print map(lambda x : x % 2 == 0 , mylist)
The output will be : [False, True, False, True, False, True, False, True, False]

lambda function with reduce() :

reduce() takes two arguments as like the above two . But the function passes as argument should also have two arguments not one. It will calculate the result for the first two , then again it will calculate result and the third value and so on. Let’s take a look :

mylist = [ 1, 2, 3, 4, 5, 6, 7, 8, 9]

print reduce(lambda x,y : x + y , mylist)
This example will print the sum of all the elements of the list “mylist” i.e. 45.

Python Function : Python Tutorial 16

Python Function tutorial : What is a function ? 

Suppose you need to find the factorial of a number and you wrote a loop to calculate it. Again in the same project, factorial calculation is required again for a different number. In this case, we can write one similar “for” loop as before . But don’t you think that it would be better if we write the “for” loop only for one time and on second case, we will just run it using a “name” ? That will be great, if factorial is required to calculate in thousands of places, we don’t have to duplicate the same code again and again. These types of “ reusable code block that performs a specific task” is known as function. 

Python Function Types :

Two types of functions are available in python. Built-in functions and User-defined functions. Built-in functions are already available functions in python like print() . User-defined functions are defined by a user . In this tutorial , we will check how to create a function .

Defining a function in python :

The syntax of a function is as below :

 

def function_name( parameters ) :
    “docstring”
    function_expressions
    return [expression]
– “def” keyword is used to define a function.
– “function_name” is the name of the function. “parameters” are one or more than one input values we are passing to the function. These are optional. We can even have a function with no parameters. In this case , it will be empty parentheses. 
– “docstring” is the documentation string for this function. With this string, we define what this function is used for. Documentation string is optional. 
– After the documentation, we write the main function body. All lines inside the body should have the same indentation level. 
– Finally, one optional return statement . It may return a expression that will calculate the final value and return to the caller or return None

Example of a function :

def isEven( num ) :
    if num % 2 == 0 :
        return True
    else :
        return False
This function will check if a number is even or not. If even, it will return “True” , and if odd, it will return “False”.

Calling a python function :

After defining a function, we can call this function from a different function or even directly from the python prompt. 

Let’s try to call the above function :

 

def isEven( num ) :
    if num % 2 == 0 :
        return True
    else :
        return False


print isEven(2)
print isEven(5)

It will print :

 

True
False

Passing a argument by reference :

In python, an argument is passed by reference . That means , if you change the argument inside the calling function, it will also change the value of that argument inside the caller.

Let’s take a look into the following example :

 

def changeDictionary( my_dict ):
    my_dict.update({'first' : 10})
    print "change dictionary ", my_dict

def changeDictionaryAgain( my_dict ):
    my_dict = {'first' : 1 , 'second' : 2}
    my_dict.update({'first' : 10})
    print "change dictionary again ",my_dict

temp_dict = {'first' : 1 , 'second' : 2}
temp_dict_2 = {'first' : 1 , 'second' : 2}


changeDictionary( temp_dict )
print "temp dict changed ",temp_dict

changeDictionaryAgain( temp_dict_2 )
print "temp dict 2 changed ",temp_dict_2

It will print the following output :

 

change dictionary  {'second': 2, 'first': 10}
temp dict changed  {'second': 2, 'first': 10}

change dictionary again  {'second': 2, 'first': 10}
temp dict 2 changed  {'second': 2, 'first': 1}

First “temp_dict” is passed to thechangeDictionary() function. Inside it, we have change the value of these dictionary. But since we are actually passing a reference , it will also change the main “temp_dict” .

In the second case, we are doing the same thing, i.e. passing the reference to the function “changeDictionaryAgain” . But before changing the value of the dictionary “temp_dict_2”, we have changed the reference by “my_dict = {‘first’ : 1 , ‘second’ : 2}” inside “changeDictionaryAgain” function. So “my_dict” inside this function holds a reference to a different dictionary and that’s why after we have updated the values, these are not reflected outside the function.

Scope of function variables :

Variables defined inside a function are not accessible from the outside. After the function execution is completed, these variables are destroyed.These are also known as local variables. 

Similarly, variables defined outside of functions are accessible from anywhere in the program, known as global variables.

 

answer = 10

def multiply(num1 , num2):
    answer = num1 * num2
    print "answer inside : ",answer
    return answer

multiply(10 , 2)
print "answer outside : ",answer
Output :

answer inside :  20
answer outside :  10

In this example, we have created one new variable “answer” inside function “multiply” and assign it a value 20. But since it is a local variable, it will not change the value of the global variable “answer”.

Python function unordered arguments :

We can call a function with multiple arguments without passing them in order. For this, we need to use the argument names as keyword with the passing value.

 

def sampleFunction(var1 , var2):
    print "var1 ",var1
    print "var2 ",var2

sampleFunction( 1, 2 )
sampleFunction( var2 = 2, var1 = 1)

Output :

 

var1  1
var2  2
var1  1
var2  2

Python function with a default value argument :

def sampleFunction( var1 , var2 = 10 ):
    print "var1 ",var1
    print "var2 ",var2

sampleFunction( 1, 2 )
sampleFunction( 20 )

Output :

 

var1  1
var2  2
var1  20
var2  10

In the above example, it prints the default value of var2 if nothing is passed for var2 .

Variable Length argument function :

If a * is placed before an argument name, it can take multiple arguments .
def sampleFunction( *var_argument ):
    print "argument : "
    for i in var_argument:
        print i

sampleFunction( 1, 2 , 4, 5)

Output :

 

argument :
1
2
4
5
For the below example, first no. is send as var1 . 

def sampleFunction( var1, *var_argument ):
    print "first argument"
    print var1
    print "argument : "
    for i in var_argument:
        print i

sampleFunction(1,2,4,5)

output :

 

first argument
1
argument :
2
4
5