Python function
- Categories Python Functions, Python
In this post we will cover function in Python. You can watch our videos on function in Python – Click Here
Q.1 What is function?
Ans.
- A function is a block of reusable code that runs only when it is called
- You can pass data, known as parameters, into a function
- A function can return data
- Example:
def square(n): #square is function
return (n*n)
print ("The square of 3 is ")
print (square(3)) # call the function
Q.2 Why do we need function?
Ans.
- Functions provide better modularity for your application
- It provide a high degree of code reusing
- The same function can be called multiple times by your code
Q. 3 What are different types of Python Functions?
Ans. Python functions can belong to one of the following three categories
- Built-in functions -These are pre-defined functions and are always available for e.g. len( ), type( ), int( ), input( ) etc.
- Functions defined in modules-These functions are pre-defined in particular modules and can only be used when the corresponding module is
e.g.sin() - User defined Functions– Programmer can create their own
Q.4 How do you define function in Python?
Ans.
- Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
- Any input parameters or arguments are placed within these
- We can add multiple arguments separated by a
- The function definition ends with colon (:)
- The body of the function is The function block ends where the indentation ends like for if and for statements.
- The statement return exits a function, optionally passing back data to the
- A return statement with no arguments is the same as return
- If there’s no return statement, then function is called void
- To call a function, use the function name followed by
Syntax:
def functionname( parameters ): "function_docstring" function_suite return [expression]
Q.5 What are Positional Arguments?
Ans. When the function call statement must match the number and order of arguments as defined in the function definition, this is called the positional argument matching
def power(n,r):
return (n**r)
print ("The 2 raise to power 3 is ", power(2,3))# call the function
Q. 6 What are Default Arguments? Give its advantages.
Ans. A parameter having a default value in function header is known as a default parameter. It becomes optional in function call.
Function call may or may not have value for it
Advantages
- They can be used to add new parameters to the existing functions
- They can be used to combine similar functions into one
Example
def power(n, r=2):
return (n**r)
print ("2 raise to power 2 is ", power(2)) # call the function
Q. 7 What are Keyword (Named) Arguments?
Ans. Keyword arguments are the named arguments with assigned values being passed in the function call statement
def power(n,r):
return (n**r)
print ("The 2 raise to power 3 is", power(r=3, n=2)) # call the function
Q.8 What is the difference between void and non-void functions?
Ans.
Void functions | Non-void functions |
Functions not returning any value. It returns None | Functions returning some value |
It is called non-fruitful functions | It is called fruitful functions |
Q.9 What is the difference between formal and actual parameters?
Ans.
- Actual Parameters: The values passed are called Actual Parameters,
- Formal Parameters: The values received in the function definition header is called Formal parameters
e.g.def power(n,r): # n and r are formal parameters
return (n**r)
power(10,2) # 10 and 2 are actual parameters
Q.10 Difference between Global Scope and Local Scope.
Ans.
Global Scope | Local Scope |
Is a variable defined in the main program(_main_) section | Is a variable defined within a function |
It is usable inside the whole program and all locks(functions, other blocks) contained within the program | It can be used only within this function and other blocks contained under it |
e.g n = 3 # Global Variable def power(p): return (n**p) x = power (3) print (n, x) | def power(p): x = p**2 # Local variable return (x) n = power (3) print (n) |
Q. 11 What is the difference between call by value and call by reference
Ans.Call By Value Call by Reference Works with immutable type (int, float, String, Tuple) Works with mutable type (list, dictionary) When mutable types are passed then if the value is
copied in formal parametersWhen immutable types are passed then the reference
of the value is passedAny change in formal parameters does not change the actual parameter in the main function If any change is done inside the function, then the
value in the main program is changed.e.g.
def power (n): n = n**2
a = 4 power(a)
print (a) // This will print 4 onlydef power (n): n[1] = n[0]**2
a = [4,0]
power(a)
print (a) // This will print [4,16]
Q. 12 What is global keyword?
Ans. When we want a variable which is local to be available globally, we declare it with global keyword before it is used.
e.g.
def func(b):
global c
c = a + b
return c
print (func(4) )# gives 4+5=9
print (c) # now c is defined (9)
Q. 13 Write the syntax of lambda functions.
Ans. The syntax of lambda functions contains only a single statement which is as follows: Lambda[arg1,[arg2…..argn]]: expression
Q. 14 What is the use of lambda keyword in Python?
Ans. You can use the lambda keyword to create small anonymous functions
Q. 15 Differentiate between Built-in functions and functions defined in modules.
Ans.
Built-in functions | Functions |
Built-in functions are pre-defined functions | Functions defined in modules are predefined |
That are already defined in python and can be used anytime e.g. len(), type(), int(), etc. | It can be used only when the corresponding module is imported |
e.g. len(), type(), int(), etc. | e.g to use predefined function sqrt() the math module needs to be imported as import math |
Q. 16 How are following two statements different import math and from math import?
Ans.import math from math import When we use import math statement a new namespace is setup with the same name as that of the module and all the code of the module is interpreted and executed here. When we use from math import statement no new namespace is created. All the defined functions and variables of the modules are available to the program When we use from math import statement no new namespace is created.
Q. 17 What are Default arguments?
Ans.
- Value of some arguments are specified in the parameters of the function
- Such arguments are called default
- These values are used in case no matching argument is passed in the function calls
Q. 18 What is a default parameter? How is it specified?
Ans.
- A parameter having default value in the function header is known as a default
- A parameter van be specified as default only if all the parameters on its right are specified as
- Syntax : def(arg1,arg2—arg x=):
arg x will now be a default parameter with default value as the value specified
Q. 19 Explain anonymous functions.
Ans.
- You can use lambda keyword to create small anonymous functions.
- These functions are called anonymous because they are not declared in the standard manner by using the def keyword, lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace
Q. 20 What is _main_?
Ans. The segment with top level statements is named as _main_ by Python
Q. 21 What is _name_?
Ans. It is built in variable that states the name of the top level statements i.e. _main_
Q. 22 How are docstring different from comments
Ans.
- Docstrings are different from comments because docstrings are stored as documentation of the corresponding module or function or class and can be displayed using help() function with name of the corresponding module/function/class as parameter
- e. g. help(math), help(math.pow) etc. This is not true with comments
Q. 23 Write a python function to reverse the string.
Ans.
def
reverse_string(str):
str1 = ""
for i in str:
str1 = i + str1
return str1 # return the reverse string
str = "SimplyCoding" # input String
print("The original string is: ",str)
print("The reverse string is",reverse_string(str)) # Function call
Q. 24 Write a python function to find factorial of given number
Ans.
def factorial(n):
if n < 0:
return 0
elif n == 0 or n == 1:
return 1
else:
fact = 1
while(n > 1):
fact *= n
n -= 1
return fact
num = 5;
print("Factorial of",num,"is", factorial(num))
Q. 25 Write a function to calculate simple interest and default value for time is 1 year and rate is 7%.
Ans.
def cal(p,r=7, t=1)
l= (p*r*t)/100
return l
print(cal(4000))
print(cal(4000,10))
print(cal(4000,10,5))
Q. 26 Write a function called show_stars(rows). If rows is 5, it should print the following:
*
**
***
****
*****
Ans.
def show_stars(rows):
for i in range(0,rows):
for j in range(0,i+1):
print(“*”,end = “”)
print(“\n”)
print(show_stars(5))
Q. 27 Write output of the following Python code?
x = 50
def func():
global x
print('x is', x)
x = 2
print('Changed global x to', x)
func()
print('Value of x is', x)
Ans.
x is 50
Changed global x to 2
Value of x is 50