Unit - II Python Notes
Unit - II Python Notes
in
Unit – II
2.1 Functions
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, to implement the code
reusability concept and makes the code easier to read and understand.
The Python provides several functions and methods to write code very easily, and these
functions and methods are called built-in function and methods. Python allows us to create
our functions and methods, and these are called user-defined functions and methods.
2. 1.1 Built-In Functions
The Python interpreter has a number of functions that are built into it and are always
available
This gives us access to all the functions in the module(s). To call a function of a
module, the function name should be preceded with the name of the module with
a dot(.) as a separator.
The syntax is as shown below:
modulename.functionname()
32.0
>>>math.pow(6.5,2)
42.25
>>>math.pow(5.5,3.2)
233.97
>>> math.sqrt(144)
12.0
math.sqrt(x) square root of x
>>> math.sqrt(.64)
0.8
>>> math.sin(0)
0
math.sin(x) sine of x in radians
>>> math.sin(6)
-0.279
11
mode (the most
statistics.mode(x)
repeated value) >>> statistics.
mode(("red","blue","red"))
'red'
• In order to get a list of modules available in Python, we can use the following
statement:
>>> help("module")
• To view the content of a module say math, type the following:
>>> help("math")
2.4 From Statement
Instead of loading all the functions into memory by importing a module, from statement
can be used to access only the required functions from a module. It loads only the specified
function(s) instead of all the functions in a module.
Syntax :
>>> from modulename import functionname
Example :
Syntax
def function_name(list_of_parameters):
statement_1
statement_2
statement_3
...
Syntax
function_name(parameter_1, parameter_2,...)
display()
When we run the above example code, it produces the following output.
Write a user defined function to add 2 numbers and display their sum.
#function definition
def addnum():
fnum = int(input("Enter first number: "))
snum = int(input("Enter second number: "))
sum = fnum + snum
print("The sum of ",fnum,"and ",snum,"is ",sum)
#function call
addnum()
When we run the above example code, it produces the following output.
WAP using a user defined function that displays sum of first n natural
numbers, where n is passed as an argument.
#function definition
def sumSquares(n):
sum = 0
for i in range(1,n+1):
sum = sum+i
print("The sum of first",n,"natural numbers is: ",sum)
def calcFact(num):
fact = 1
for i in range(num,0,-1):
fact = fact * i
print("Factorial of",num,"is",fact)
When we run the above example code, it produces the following output.
def area_trapezium(a,b,h):
area=0.5*(a+b)*h
print("Area of a Trapezium is ",area)
def main():
area_trapezium(10,15,20)
if __name__ == "__main__":
main()
When we run the above example code, it produces the following output
A function may or may not return a value when called. The return statement returns
the values from the function.
A return statement consists of the return keyword followed by an
optional return value.
print(add(2, 2))
Output : 4
9
Armstrong Number : The sum of cubes of each digit is equal to the number itself.
For example:
153 = 1*1*1 + 5*5*5 + 3*3*3 // 153 is an Armstrong number.
When we run the above example code, it produces the following output
A variable that is defined outside any function or any block is known as a global variable. It
can be accessed in any functions defined onwards. Any change made to the global variable
will impact all the functions in the program where that variable can be accessed.
2.6.2 Local Variable
A variable that is defined inside any function or a block is known as a local variable. It can
be accessed only in the function or a block where it is defined. It exists only till the function
executes.
num1 = 5 #globalvariable
def myfunc():
# variable num1 outside the function
print("Accessing num =",num1)
num = 10 #localvariable
print("num reassigned =", num)
myfunc()
print("Accessing num outside myfunc",num1)
When we run the above example code, it produces the following output
11
Calculate and Add the Surface Area of Two Cubes. Use Nested Functions
def main():
result=add_cubes(2, 3)
print("The surface area after adding two Cubes
is",result)
if __name__ == "__main__":
main()
When we run the above example code, it produces the following output
When we run the above example code, it produces the following output
13
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))
When we run the above example code, it produces the following output
Python has **kwargs which allows us to pass the variable length of keyword arguments
to the function. In the function, we use the double-asterisk (**) before the parameter
name to denote this type of argument.
14
def Student_info(**kwargs):
print(kwargs)
Student_info(name="Raju",rollno=111,group="MSDs")
When we run the above example code, it produces the following output
import sys
print("Number of arguments:",len(sys.argv))
print('The command line arguments are:')
for i in sys.argv:
print(i)
15
3. Strings
A string is a sequence of characters which is enclosed in quotes. In Python, A string can be
created by enclosing one or more characters in single, double or triple quote.. The Python
treats both single quote and double quote as same.
For example, the strings 'Hi Friend' and "Hi Friend" both are same.
3.1 Creating and Storing Strings
In Python, creating string variables is very simple as we need to assign a string value to a
variable.
str1 = 'Hello World!'
str2 = "Hello World!"
str3 = """Hello World!
welcome to the world of Python"""
str4 = '''Hello World!
welcome to the world of Python'''
16
• The index can also be an expression including variables and operators but the
expression must evaluate to an integer
• Python allows an index value to be negative also. Negative indices are used when
we want to access the characters of the string from right to left.
• Starting from right hand side, the first character has the index as -1 and the last
character has the index –n where n is the length of the string.
17
3.3.2 Repetition
Python allows us to repeat the given string using repetition operator which is denoted by
symbol *
Note: str1 still remains the same after the use of repetition operator
18
3.3.3 Membership
Python has two membership operators 'in' and 'not in'. The 'in' operator takes
two strings and returns True if the first string appears as a substring in the second string,
otherwise it returns False.
The 'not in' operator also takes two strings and returns True if the first string does
not appear as a substring in the second string, otherwise returns False.
3.3.4 Slicing
In Python, to access some part of a string or substring, we use a method called slicing. This
can be done by specifying an index range.
To access substring from a string, we use string variable name followed by square brackets
with starting index , ending index and Step of the required substring.
19
If the first index is not mentioned, the slice starts from index and If the second index is not
mentioned, the slicing is done till the length of the string.
The slice operation can also take a third index that specifies the ‘step size’. For
example, str1[n:m:k], means every kth character has to be extracted from the string
str1 starting from n and ending at m-1. By default, the step size is one.
Negative indexes can also be used for slicing. If we ignore both the indexes and give step
size as -1 , str1 string is obtained in the reverse order.
20
3.3.4 Joining
The join() string method returns a string by joining all the elements of an iterable (list,
string, tuple), separated by a string separator.
22
23
Write Python Program to Convert Uppercase Letters to Lowercase and Vice Versa
def case_conversion(string):
str1=str()
for ch in string:
if ch.isupper():
str1+=ch.lower()
else:
str1 += ch.upper()
print("The modified string is ",str1)
def main():
str2=input("Enter a String :")
case_conversion(str2)
if __name__=="__main__":
main()
Output :
Enter a String : Hello WORLD
The modified string is hELLO world
24
Output :
String in Uppercase : HELLO WORLD!
String in Lower case : hello world!
Capitalized String : hello world!
String with first letter : Hello World!
String alphanumeric : False
String in lowercase : False
String in uppercase : False
Swapcase : HELLO wORLD!
Right Strip of String : hello World!
Left Strip of String : hello World!
Right & Left Strip of String : hello World!
Python f-string is the newest Python syntax to do string formatting. It is available since
Python 3.6. Python f-strings provide a faster, more readable, more concise, and less error
prone way of formatting strings in Python.
The f-strings have the f prefix and use {} brackets to evaluate values.
The format strings will contain the curly braces { } and the format() method will use those
curly braces { } as placeholders to replace with the content of the parameters.
25
name = 'Raju'
age = 23
print('%s is %d years old' % (name, age))
print('{} is {} years old'.format(name, age))
print(f'{name} is {age} years old')
Output :
Raju is 23 years old
Raju is 23 years old
Raju is 23 years old
• In this type of functions there is data transfer from calling-function to called function
(parameters) but there is no data transfer from called function to calling-function
(return value).
• The execution control jumps from calling-function to called function along with the
parameters and executes called function, and finally comes back to the calling
function.
def add(a,b):
c=a+b
print(c) Output :
enter a 10
enter b 20
a=int(input("enter a")) 30
b=int(input("enter b"))
add(a,b)
def add():
a = int(input("enter a"))
b = int(input("enter b"))
c = a + b Output :
return c enter a 10
enter b 20
c = add() 30
print(c)
def add(a,b):
c = a + b Output :
return c enter a 10
a = int(input("enter a")) enter b 20
b = int(input("enter b")) 30
c = add(a,b)
print(c)
27
Unit-II Questions
1. Explain 4 different function prototypes with an example programs
2. Explain built in functions with suitable examples
3. Write a short note on return statement in function with an example
program.
4. Explain Commonly used modules with an example programs
5. Write a short note on formatted strings
6. Explain built-in functions with examples
7. Differentiate between local and global variables with suitable examples
8. Define Function. Explain with syntax how to create a used-defined functions
and how to call the user -defined functions / how to call user defined
functions from the main function
9. Explain about default arguments , *args and **kwargs
10. Write a short note on Command line arguments with an example program
11. Explain strings in detail (Creating and accessing )
12. Explain string operations in detail.
13. Explain string methods with an example programs
28