Unit-1 Part-2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

Unit-1 PART-B

FUNCTIONS
If a group of statements is repeatedly required then it is not recommended to write these
statements every time separately. We have to define these statements as a single unit and we
can call that unit any number of times based on our requirement without rewriting. This unit
is nothing but function.

The main advantage of functions is code Reusability.


Note: In other languages functions are known as methods, procedures, subroutines etc.
Python supports 2 types of functions
1. Built in Functions
2. User Defined Functions
1. Built in Functions:

The functions which are coming along with Python software automatically, are called
built in functions or pre-defined functions.

Eg:

id()
type()
input()
eval()
etc..
2. User defined functions
All the functions that are written by any us comes under the category of user defined
functions. Below are the steps for writing user defined functions in Python.
• In Python, def keyword is used to declare user defined functions.

• An indented block of statements follows the function name and arguments which contains
the body of the function.

Syntax:
def function_name():
statements
Example:
# Declaring a function
def fun():
print("Inside function")

# Driver's code
# Calling function
fun()

Parameters

Parameters are inputs to the function. If a function contains parameters, then at the timeof
calling, compulsory we should provide values otherwise, otherwise we will get error.
Return Statement:
Function can take input values as parameters and executes business logic, and returns
output to the caller with return statement.

Q. Write a function to accept 2 numbers as input and return sum.

1. def add(x,y):
2. return x+y
3. result=add(10,20)
4. print("The sum is",result)
5. print("The sum is",add(100,200))
6.
7.
8. D:\Python_classes>py test.py
9. The sum is 30
10. The sum is 300

There are 4 types are actual arguments are allowed in Python.


1. positional arguments
2. keyword arguments
3. default arguments
4. Variable length arguments

1. positional arguments:

These are the arguments passed to function in correct positional order.


def sub(a,b):
print(a-b)
sub(100,200)
sub(200,100)
output: -100
100

2. keyword arguments:

We can pass argument values by keyword i.e by


parameter name.
Eg:
1. def wish(name,msg):
2. print("Hello",name,msg)
3. wish(name="Durga",msg="Good Morning")
4. wish(msg="Good Morning",name="Durga")
5.
6. Output
7. Hello Durga Good Morning
8. Hello Durga Good Morning
3. Default Arguments:

Sometimes we can provide default values for our positional arguments.


Eg:
1) def wish(name="Guest"):
2) print("Hello",name,"Good Morning")
3)
4) wish("Durga")
wish()
6)

8) Hello Durga Good Morning


9) Hello Guest Good Morning

4. Variable length arguments:

Sometimes we can pass variable number of arguments to our function, such type ofarguments
are called variable length arguments.

We can declare a variable length argument with * symbol as follows


def f1(*n):
We can call this function by passing any number of arguments including zero number.
Internally all these values represented in the form of tuple.

Eg:

1) def sum(*n):
2) total=0
3) for n1 in n:
4) total=total+n1
5) print("The Sum=",total)
6)
7) sum()
8) sum(10)
9) sum(10,20)
10) sum(10,20,30,40)
11)
12) Output
13) The Sum= 0
14) The Sum= 10
15) The Sum= 30
16) The Sum= 100

Types of Variables

Python supports 2 types of variables.

1. Global Variables
2. Local Variables

1. Global Variables

The variables which are declared outside of function are called global variables. These
variables can be accessed in all functions of that module.

Eg:
a=10 # global variable
def f1():
print(a)
def f2():
print(a)
f1()
f2()

output:
10
10

2. Local Variables:

The variables which are declared inside a function are called local variables.
Local variables are available only for the function in which we declared it.i.e from outside of
function we cannot access.

Eg:

def f1():
a=10
print(a)
def f2():
print(a)
f1()
f2()

output:
10
a is not defined

What are Lambda Functions in Python

Lambda Functions in Python are anonymous functions, implying they don't have a name. The def
keyword is needed to create a typical function in Python, as we already know. We can also use the
lambda keyword in Python to define an unnamed function.

Note: By using Lambda Functions we can write very concise code so that readability of the
program will be improved.

Syntax of Python Lambda Function

lambda arguments: expression

Write a program to create a lambda function to find square of givennumber?


1) s=lambda n:n*n

2) print("The Square of 4 is :",s(4))

3) print("The Square of 5 is :",s(5))


4)

5) Output
6) The Square of 4 is : 16

7) The Square of 5 is : 25

Python Recursive Function

In Python, we know that a function can call other functions. It is even possible for the function to call
itself. These types of construct are termed as recursive functions.
The following image shows the working of a recursive function called recurse.

Advantages of Recursion

1. Recursive functions make the code look clean and elegant.


2. A complex task can be broken down into simpler sub-problems using recursion.
3. Sequence generation is easier with recursion than using some nested iteration.
Eg:

1) def factorial(n):
2) if n==0:
3) result=1
4) else:
5) result=n*factorial(n-1)
6) return result
7) print("Factorial of 4 is :",factorial(4))
8) print("Factorial of 5 is :",factorial(5))
9)
10) Output

factorial(3)=3*factorial(2)
=3*2*factorial(1)
=3*2*1*factorial(0)
=3*2*1*1
=6
factorial(n)= n*factorial(n-1)

What is Python Module


A Python module is a file containing Python definitions and statements. A module can define
functions, classes, and variables. A module can also include runnable code. Grouping related code
into a module makes the code easier to understand and use. It also makes the code logically
organized.
Python built-in modules
There are two types of modules
1. Math
2. Random
Various possibilties of import:

import modulename
import module1,module2,module3 import
module1 as m
import module1 as m1,module2 as m2,module3 from module
import member
from module import
member1,member2,memebr3
from module import memeber1 as x
from module import *

Working with math module:

Python provides inbuilt module math.

This module defines several functions which can be used for mathematical operations. The
main important functions are

1. sqrt(x)
2. ceil(x)
3. floor(x)
4. fabs(x)5.log(x)
6. sin(x)
7. tan(x)
....

Eg:

1) from math import *


2) print(sqrt(4))
3) print(ceil(10.1))
4) print(floor(10.1))
5) print(fabs(-10.6))
6) print(fabs(10.6))
7)
8) Output
9) 2.0
10) 11
11) 10
12) 10.6
13) 10.6
Working with random module:

This module defines several functions to generate random numbers.

We can use these functions while developing games, in cryptography and to generate random
numbers on fly for authentication.

• The random() Function


The random.random() function gives a float number that ranges from 0.0 to 1.0. There are no
parameters required for this function. This method returns the second random floating-point value
within [0.0 and 1] is returned.

Code

1. # Python program for generating random float number


2. import random
3. num=random.random()
4. print(num)

0.3232640977876686

• The randint() Function


The random.randint() function generates a random integer from the range of numbers supplied.

Code

1. # Python program for generating a random integer


2. import random
3. num = random.randint(1, 500)
4. print( num )
Output:

215

• The randrange() Function


The random.randrange() function selects an item randomly from the given range defined by the start,
the stop, and the step parameters. By default, the start is set to 0. Likewise, the step is set to 1 by
default.

Code

1. # To generate value between a specific range


2. import random
3. num = random.randrange(1, 10)
4. print( num )
5. num = random.randrange(1, 10, 2)
6. print( num )
Output:
e4
9

• The choice() Function


The random.choice() function selects an item from a non-empty series at random. In the given below
program, we have defined a string, list and a set. And using the above choice() method, random
element is selected.

Code

1. # To select a random element


2. import random
3. random_s = random.choice('Random Module') #a string
4. print( random_s )
5. random_l = random.choice([23, 54, 765, 23, 45, 45]) #a list
6. print( random_l )
7. random_s = random.choice((12, 64, 23, 54, 34)) #a set
8. print( random_s )
Output:

M
765
54

• The shuffle() Function


The random.shuffle() function shuffles the given list randomly.

Code

1. # To shuffle elements in the list


2. list1 = [34, 23, 65, 86, 23, 43]
3. random.shuffle( list1 )
4. print( list1 )
5. random.shuffle( list1 )
6. print( list1 )
Output:

[23, 43, 86, 65, 34, 23]


[65, 23, 86, 23, 34, 43]

String Data Type

Any sequence of characters within either single quotes or double quotes is considered as a
String.
Syntax:

s='durga'
s="durga"

Eg:
>>> ch='a'
>>> type(ch)
<class 'str'>

How to define multi-line String literals:

We can define multi-line String literals by using triple single or double quotes.
Eg:

>>> s='''durga software solutions'''

We can also use triple quotes to use single quotes or double quotes as symbol inside String
literal.

How to access characters of a String:

We can access characters of a string by using the following ways.


1. By using index
2. By using slice operator
1. By using index:

Python supports both +ve and -ve index.


+ve index means left to right(Forward direction)
-ve index means right to left(Backward direction)
Eg:

s='durga'
Eg:
>>> s='durga'
>>> s[0]
'd'
>>> s[4]
'a'
>>> s[-1]
'a'
>>> s[10]
IndexError: string index out of range
2. Accessing characters by using slice operator:

Syntax: s[bEginindex:endindex:step]

bEginindex:From where we have to consider slice(substring)


endindex: We have to terminate the slice(substring) at endindex-
1 step: incremented value
Eg:

1) >>> s="Learning Python is very very easy!!!"


2) >>> s[1:7:1]
3) 'earnin'
4) >>> s[1:7]
5) 'earnin'
6) >>> s[1:7:2]
7) 'eri'
8) >>> s[:7]
9) 'Learnin'
10) >>> s[7:]
11) 'g Python is very very easy!!!'
12) >>> s[::]
13) 'Learning Python is very very easy!!!'
14) >>> s[:]
15) 'Learning Python is very very easy!!!'
16) >>> s[::-1]
17) '!!!ysae yrev yrev si nohtyP gninraeL'

len() in-built function:

We can use len() function to find the number of characters present in the string.
Eg:

s='d
urga
'
print
(len(
s))
#5

Finding Substrings:
We can use the following 4 methods
For forward direction:

find()
index(
)
For backward direction:

rfind()
rindex()

1. find():

s.find(substring)

Returns index of first occurrence of the given substring. If it is not available then
we will get -1

Eg:

1) s="Learning Python is very easy"

2) print(s.find("Python")) #9
3) print(s.find("Java")) # -1
4) print(s.find("r"))#3
5) print(s.rfind("r"))#21
index() method:

index() method is exactly same as find() method except that if the


specified substring is not available then we will get ValueError.
Eg:

1) s=input("Enter main string:")


2) subs=input("Enter sub string:")
3) try:
4) n=s.index(subs)
5) except ValueError:
6) print("substring not found")
7) else:
8) print("substring found")

Output:
D:\python_classes>py test.py
Enter main string: learning python is very easy Enter sub string: python
substring found

Counting substring in the given String:

We can find the number of occurrences of substring present in the given string by
using count() method.

1. s.count(substring) ==> It will search through out the string


2. s.count(substring, bEgin, end) ===> It will search from bEgin index to end-1
index

Replacing a string with another string:

s.replace(oldstring,newstring)
inside s, every occurrence of oldstring will be replaced with newstring.

Changing case of a String:


We can change case of a string by using the following 4 methods.
1. upper()===>To convert all characters to upper case
2. lower() ===>To convert all characters to lower case
3. swapcase()===>converts all lower case characters to upper case and all upper
case characters to lower case
4. title() ===>To convert all character to title case. i.e first character in every word
should be upper case and all remaining characters should be in lower case.
5. capitalize() ==>Only first character will be converted to upper case and all
remaining characters can be converted to lower case

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy