[go: up one dir, main page]

0% found this document useful (0 votes)
8 views18 pages

Python Unit 3

Python unit 3

Uploaded by

Sandhiya Ammu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views18 pages

Python Unit 3

Python unit 3

Uploaded by

Sandhiya Ammu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

PROBLEM SOLVING USING PYTHON

UNIT 3
2 MARKS

1
1. What Is a Function Routine?
➢ Computer program as a single series of instructions.
➢ A routine is a named group of instructions performing some task.
➢ A routine can be invoked (called) as many times as needed in a given program.

= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
2. Define: Function.
➢ A function is a block of statements under a name that can execute independently.
➢ The functions are used to perform a specific task.
➢ Functions allow us to divide a larger problem into smaller subparts to solve efficiently.
= = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = =
3. How to create/ define a function?
➢ The Python programming language provides the keyword def to create functions.
➢ The general syntax to create functions is as follows.
Syntax:
def function_name(list_of_parameters):
statement_1
statement_2
statement_3
...

= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
4. What is calling a function in Python?
➢ In Python, we use the name of the function to make a function call.
➢ If the function requires any parameters, we need to pass them while calling it.
Syntax:
function_name(parameter_1, parameter_2,...)

Example:

def sample_function():

2
print('This is a user-defined function')
sample_function()
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =

5. What is Value-Returning Functions in Python?


➢ A value-returning function in Python is a program routine called for its return value,
and is therefore similar to a mathematical function.

➢ Function avg takes three arguments (n1, n2, and n3) and returns the average of the three.
➢ The function call avg(10, 25, 16), therefore, is an expression that evaluates to the
returned function value.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
6. What is Non-Value-Returning Functions in Python?
➢ A non-value-returning function is called not for a returned value, but for its side
effects.
➢ A side effect is an action other than returning a function value, such as displaying
output on the screen.
Example:

= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
7. What is Actual arguments and Formal arguments in Python?
➢ Actual arguments, or simply “arguments,” are the values passed to functions (or
method) when the calling function to be operated on.

3
➢ Formal parameters, or simply “parameters,” are the “placeholder” names
(variables/identifiers) specified in the (header of) function definition.
def addition(x, y): →Formal parameters
addition = x+y
print(f”{addition}”)
addition(2, 3) →Actual Parameters
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
8. What is Local Variable?
➢ A local variable is a variable that is only accessible from within a given function.
➢ In Python, the variable that created inside a function is said to be under the local scope.
Example:
In this example Variable ‘a’ is used within the function named my_function() only.
def my_function():
a = 10
print('Inside my_function a value is: ', a)
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
9. What is Global Variable?
➢ A global variable is a variable defi ned outside of any function definition. Such
variables are said to have global scope.

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

4
10. What is Variable scope in Python?
➢ The scope refers to the accessibility of a variable or object in the program.
➢ The scope of a variable determines the part of the program in which it can be accessed
or used.
➢ In Python programming, there are two different levels of scope and they are as follows.
1. Local Scope
2. Global Scope
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
11. What is built-in functions in Python?
➢ Built-in functions are defined as the functions whose functionality is pre-defined in
Python.
➢ There are several built-in functions in Python which are listed below:
1. abs()
2. all()
3.any()
4. bin()
5. bool()
6. sum() and so on.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =

5
PROBLEM SOLVING USING PYTHON
UNIT 3
5 & 10 MARKS

6
1. Explain about function in Python?
➢ Computer program as a single series of instructions.
➢ A routine is a named group of instructions performing some task.
➢ A routine can be invoked (called) as many times as needed in a given program.
➢ When a routine terminates, execution automatically returns to the point from which it
was called.
➢ A function is Python’s version of a program routine. Some functions are designed to
return a value, while others are designed for other purposes.
➢ Functions allow us to divide a larger problem into smaller subparts to solve efficiently.
Create/ Define a function:
➢ The Python programming language provides the keyword def to create functions.
➢ The general syntax to create functions is as follows.
Syntax:
def function_name(list_of_parameters):
statement_1
statement_2
statement_3
...

Calling a function:
➢ In Python, we use the name of the function to make a function call.
➢ If the function requires any parameters, we need to pass them while calling it.
Syntax:
function_name(parameter_1, parameter_2,...)

Example:

def sample_function():
print('This is a user-defined function')
sample_function()

7
Value-Returning Functions :
➢ A value-returning function in Python is a program routine called for its return value,
and is therefore similar to a mathematical function.

➢ Function avg takes three arguments (n1, n2, and n3) and returns the average of the three.
➢ The function call avg(10, 25, 16), therefore, is an expression that evaluates to the
returned function value.
Non-Value-Returning Functions:
➢ A non-value-returning function is called not for a returned value, but for its side effects.
➢ A side effect is an action other than returning a function value, such as displaying
output on the screen.
Example:

= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
2. Discuss about: Parameter passing in Python.
➢ Information can be passed into functions as arguments.
➢ Arguments are specified after the function name, inside the parentheses.
➢ You can add as many arguments as you want, just separate them with a comma.
➢ In Python, all the parameters are passed using pass by reference only.
Example1:
def fn1(name):
print(f'Hello! {name}')
name = 'Raja'

8
name = 'Rama'
fn1 (name)
print(f'name outside the function is {name}')

Output:
Hello! Rama
name outside the function is Rama
➢ In the above example program, the changes made in the called function does not affect
the name value outside the function.
➢ Because here the name variable has redefined, so it becomes a local variable for the
function.
➢ So, when we change the 'name' value in the function, it creates a new reference to it,
but it does not change the name outside the function.
Example2:
def myFun(x):
x[0] = 20

lst = [10, 11, 12, 13, 14, 15]


myFun(lst);
print(lst)
Output:
[20, 11, 12, 13, 14, 15]

Example 3:
def myFun(x):
x = [20, 30, 40]

lst = [10, 11, 12, 13, 14, 15]


myFun(lst);
print(lst)
Output:
[10, 11, 12, 13, 14, 15]
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
3. Explain about: a) Actual Arguments vs. Formal Parameters
b) Mutable vs. Immutable Arguments
Actual Arguments vs. Formal Parameters:
➢ Actual arguments, or simply “arguments,” are the values passed to functions (or
method) when the calling function to be operated on.
➢ Formal parameters, or simply “parameters,” are the “placeholder” names
(variables/identifiers) specified in the (header of) function definition.

9
def addition(x, y): →Formal parameters
addition = x+y
print(f”{addition}”)
addition(2, 3) →Actual Parameters
Mutable vs. Immutable Arguments
➢ When a function is called, the current values of the arguments passed become the
initial values of their corresponding formal parameters.

Example:

➢ In this case, literal values are passed as the arguments to function avg.
➢ When variables are passed as actual arguments. Here we can change the value.
➢ It is considered as Mutable.

➢ In this case, function avg doesn’t assign values to its formal parameters, so there is no
possibility of the actual arguments being changed. It is considered as Immutable.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
4. Explain Python function arguments?

In Python, there are different ways to pass arguments to a function. They are as follows.

1. Positional Arguments (or) Required Arguments


2. Default Arguments
3. Keyword Arguments
4. Variable-length Arguments

10
1. Positional Arguments (or) Required Arguments

➢ The positional arguments are the arguments passed to a function in the same positional
order as they defined in the function definition.
➢ Here, the number of arguments and order of arguments in the function call should
exactly match with the respective function definition.
➢ If any mismatch leads to error.
➢ The positional arguments are also known as required arguments.
Example:
def addition(num1, num2, num3):
return num1 + num2 + num3

result = addition(10, 20, 30)


print(f'Sum = {result}')

#result = addition(10, 20) # Error


print(f'Sum = {result}')

2. Default Arguments

➢ The default argument is an argument which is set with a default value in the function
definition.
➢ If the function is called with value then, the function executed with provided value,
otherwise, it executed with the default value given in the function definition.
Example:
def addition(num1, num2, num3=300):
return num1 + num2 + num3

result = addition(10, 20, 30)


print(f'Sum = {result}')
result = addition(10, 20) # 3rd argument uses default value
print(f'Sum = {result}')

Output:
Sum = 60
Sum = 330

3. Keyword Arguments
➢ The keyword argument is an argument passed as a value along with the parameter name
(parameter_name = value).
➢ When keyword arguments are used, we may ignore the order of arguments.
➢ We may pass the arguments in any order because the Python interpreter uses the
keyword provided to match with the respective parameter.

11
Example:
def student_info(rollNo, name, dept, year):
print(f'Roll Number : {rollNo}')
print(f'Student Name : {name}')
print(f'Department : {dept}')
print(f'Year of Study : {year}')

student_info(name='Rama', dept='CSE', rollNo=111, year=4)

Output:
Roll Number : 111
Student Name : Rama
Department : CSE
Year of Study : 4

4. Variable-length Arguments
➢ The Python provides variable-length of arguments which enable us to pass an arbitrary
number of arguments.
➢ Here, all the arguments are stored as a tuple of parameters in the function definition.
And they are accessed using the index values (similar to a tuple).
Example:
def largest(*numbers):
return max(numbers)

print(largest(20, 35))
print(largest(2, 5, 3))
print(largest(10, 40, 80, 50))
print(largest(16, 3, 9, 12, 44, 40))

Output:
35
5
80
44
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
5. Explain about Variable scope in Python.
➢ The scope refers to the accessibility of a variable or object in the program.
➢ The scope of a variable determines the part of the program in which it can be accessed
or used.
1. Local Variable and Local Scope

12
➢ A local variable is a variable that is only accessible within a given function itself.
Such variables are said to have local scope.
Example:
def my_function():
a = 10
print('Inside my_function a value is: ', a)

2. Global Variables and Global Scope


➢ A global variable is a variable that is defi ned outside of any function defi nition. Such
variables aresaid to have global scope .
Example:

= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
6. Discuss about Built-in function in Python.
➢ The Python built-in functions are defined as the functions whose functionality is pre-
defined. These functions are known as Built-in Functions.
➢ There are several built-in functions in Python which are listed below:
abs()Function:
➢ The python abs() function is used to return the absolute value of a number.
➢ It takes only one argument, a number whose absolute value is to be returned.
➢ The argument can be an integer and floating-point number.
➢ If the argument is a complex number, then, abs() returns its magnitude.
Examples:
1) x = abs(-7.25)
print(x)
Output:
7.25
2) x = abs(3+5j)
13
print(x)
Output:
5.830951894845301
all() Function:
➢ The all() function returns True if all items in an iterable are true, otherwise it returns
False.
➢ If the iterable object is empty, the all() function also returns True.
➢ Ex:
mylist = [0, 1, 1] mylist = [True, True, True]
x = all(mylist) x = all(mylist)
print(x) print(x)
Output:
False True
Any() Function:
➢ The any() function returns True if any item in an iterable are true, otherwise it returns
False.
➢ If the iterable object is empty, the any() function will return False.
Ex 1:
mylist = [False, True, False]
x = any(mylist)
Output:
True
Ex 2:
mytuple = (0, 1, False)
x = any(mytuple)
Output:
True
Ex 3:
myset = {0, 1, 0}
x = any(myset)
Output:
True
complex() Function:

14
➢ The complex() function returns a complex number by specifying a real number and an
imaginary number.
Syntax:
complex(real, imaginary)
Ex:
x = complex(3, 5) x = complex('3+5j’)
print(x) print(x)
Output: (3+5j) Output: (3+5j)
dict() Function:
➢ The dict() function creates a dictionary.
➢ A dictionary is a collection which is unordered, changeable and indexed.
Ex:
x = dict(name = "John", age = 36, country = "Norway")
print(x)
Output:
{'name': 'John', 'age': 36, 'country': 'Norway'}
eval() Function:
➢ The eval() function evaluates the specified expression.
Example:
x=5
print(eval('x + 1’))
Output:
6
exec() Function:
➢ The exec() function executes the specified Python code.
➢ The exec() function accepts large blocks of code, unlike the eval() function which
only accepts a single expression
Ex:
x = 'name = "John
print(name)'
exec(x)
Output: John
len() Function:
➢ The len() function returns the number of items in an object.
15
➢ When the object is a string, the len() function returns the number of characters in the
string.
Ex:
mylist = ["apple", "orange", "cherry"]
x = len(mylist)
print(x)
Output:
3
id() function
➢ The id() function returns a unique id for the specified object.
➢ All objects in Python has its own unique id.
➢ The id is the object's memory address, and will be different for each time you run the
program. (except for some object that has a constant unique id, like integers from -5 to
256)
Example
x = ('apple', 'banana', 'cherry')
y = id(x)
print(y)
# This value is the memory address of the object and will be different every time you
run the program
Output:
88991544
list() function
➢ The list() function creates a list object.
➢ A list object is a collection which is ordered and changeable.

Example:

x = list(('apple', 'banana', 'cherry'))

print(x)

Output:

['apple', banana', 'cherry']

16
map() function

➢ The map() function executes a specified function for each item in an iterable.
➢ The item is sent to the function as a parameter.
Example:
def myfunc(a):
return len(a)
x = map(myfunc, ('apple', 'banana', 'cherry'))
print(x)
#convert the map into a list, for readability:
print(list(x))
Output:
<map object at 0x056D44F0>
['5', '6', '6']
max() function
➢ The max() function returns the item with the highest value, or the item with the highest
value in an iterable.
➢ If the values are strings, an alphabetically comparison is done.
Example:
x = max(5, 10)
print(x)
Output:
10
min() function
➢ The min() function returns the item with the lowest value, or the item with the lowest
value in an iterable.
➢ If the values are strings, an alphabetically comparison is done.
Example:
x = min(5, 10)
print(x)
Output:
5
range() function

17
➢ The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and stops before a specified number.
Example:
x = range(6)
for n in x:
print(n)
Output:
0
1
2
3
4
5

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

18

You might also like