Unit 3

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

[Unit 3]

Python Function- 4. # function calling


Functions are the most important aspect of an application. A5. hello_world()
function can be defined as the organized block of reusable code, Output:
which can be called whenever required. hello world
Python allows us to divide a large program into the basic building
blocks known as a function. The function contains the set of The return statement-
programming statements enclosed by {}. A function can be called The return statement is used at the end of the function and returns
multiple times to provide reusability and modularity to the Python the result of the function. It terminates the function execution and
program. transfers the result where the function is called. The return
Python provide us various inbuilt functions statement cannot be used outside of the function.
like range() or print(). Although, the user can create its Syntax- return [expression_list]
functions, which can be called user-defined functions. Ex.1
There are mainly two types of functions. # Defining function
o User-define functions - The user-defined functions are1. def sum():
those define by the user to perform the specific task. 2. a = 10
o Built-in functions - The built-in functions are those3. b = 20
functions that are pre-defined in Python. 4. c = a+b
Advantage of Functions in Python- 5. return c
There are the following advantages of Python functions.
6. # calling sum() function in print statement
o Using functions, we can avoid rewriting the same
7. print("The sum is:",sum())
logic/code again and again in a program.
Example 2 Creating function without
o We can call Python functions multiple times in a program
return statement
and anywhere in a program.
1. # Defining function
o We can track a large Python program easily when it is
2. def sum():
divided into multiple functions.
3. a = 10
o Reusability is the main achievement of Python functions.
4. b = 20
o However, Function calling is always overhead in a
5. c = a+b
Python program.
6. # calling sum() function in print statement
Creating a Function-
Python provides the def keyword to define the function. The7. print(sum())
syntax of the define function is given below.
Syntax:
Arguments in function
The arguments are types of information which can be passed into
1. def my_function(parameters): the function. The arguments are specified in the parentheses. We
can pass any number of arguments, but they must be separate
2. function_block them with a comma.
3. return expression
Function Calling- 1. #Python function to calculate the sum of two variables
In Python, after the function is created, we can call it from
2. #defining the function
another function. A function must be defined before the function
call; otherwise, the Python interpreter gives an error. To call the3. def sum (a,b):
function, use the function name followed by the parentheses.
Consider the following example of a simple example that prints4. return a+b;
the message "Hello World". 5. #taking values from the user
1. #function definition 6. a = int(input("Enter a: "))
2. def hello_world(): 7. b = int(input("Enter b: "))
3. print("hello world") 8. #printing the sum of a and b
[By.- Prof. Narendra Kumar_CSE] Page 1
[Unit 3]

9. print("Sum = ",sum(a,b))
Types of arguments
Output: Enter a: 10 There may be several types of arguments which can be passed at
Enter b: 20 the time of function call.
Sum = 30
1. Required arguments

Call by reference in Python 2. Keyword arguments


In Python, call by reference means passing the actual value as an 3. Default arguments
argument in the function. All the functions are called by
reference, i.e., all the changes made to the reference inside the 4. Variable-length arguments
function revert back to the original value referred by the
reference.
Scope of variables
The scopes of the variables depend upon the location where the
variable is being declared. The variable declared in one part of the
Example 1 Passing Immutable Object program may not be accessible to the other parts.
In python, the variables are defined with the two types of scopes.
(List)
1. Global variables
1. #defining the function
2. Local variables
2. def change_list(list1): The variable defined outside any function is known to have a
3. list1.append(20) global scope, whereas the variable defined inside a function is
known to have a local scope.
4. list1.append(30)
5. print("list inside function = ",list1) Consider the following example.

6. #defining the list


Example 1 Local Variable
7. list1 = [10,30,40,50]
1. def print_message():
8. #calling the function
2. message = "hello !! I am going to print a message." # the variab
9. change_list(list1)
le message is local to the function itself
10. print("list outside function = ",list1)
3. print(message)
Output:
4. print_message()
list inside function = [10, 30, 40, 50, 20, 30] 5. print(message) # this will cause an error since a local variable ca
list outside function = [10, 30, 40, 50, 20, 30]
nnot be accessible here.
Example 2 Passing Mutable Object Output:
(String) hello !! I am going to print a message.
1. #defining the function File "/root/PycharmProjects/PythonTest/Test1.py", line 5, in
2. def change_string (str): print(message)
NameError: name 'message' is not defined
3. str = str + " Hows you "
4. print("printing the string inside function :",str) Example 2 Global Variable
5. string1 = "Hi I am there" 1. def calculate(*args):
6. #calling the function 2. sum=0
7. change_string(string1) 3. for arg in args:
8. print("printing the string outside function :",string1) 4. sum = sum +arg
Output:
5. print("The sum is",sum)
printing the string inside function : Hi I am there Hows you 6. sum=0
printing the string outside function : Hi I am there 7. calculate(10,20,30) #60 will be printed as the sum
[By.- Prof. Narendra Kumar_CSE] Page 2
[Unit 3]

8. print("Value of sum outside the function:",sum) # 0 will be printe


d Output:
Output:

The sum is 60
Value of sum outside the function: 0

Python String
Python string is the collection of the characters surrounded by
single quotes, double quotes, or triple quotes. The computer does
not understand the characters; internally, it stores manipulated
character as the combination of the 0's and 1's.
In Python, strings can be created by enclosing the character or the
sequence of characters in the quotes. Python allows us to use
single quotes, double quotes, or triple quotes to create the string.
Consider the following example in Python to create a string.
Syntax:
1. str = "Hi Python !"
Here, if we check the type of the variable str using a Python
script
1. print(type(str)), then it will print a string (str).
Consider the following example:
Creating String in Python 1. str = "HELLO"
We can create a string by enclosing the characters in single-
quotes or double- quotes. Python also provides triple-quotes to2. print(str[0])
represent the string, but it is generally used for multiline string3. print(str[1])
or docstrings.
4. print(str[2])
1. #Using single quotes
5. print(str[3])
2. str1 = 'Hello Python'
6. print(str[4])
3. print(str1)
7. # It returns the IndexError because 6th index doesn't exist
4. #Using double quotes
8. print(str[6])
5. str2 = "Hello Python" Output:
6. print(str2) H
E
7. #Using triple quotes L
L
8. str3 = '''''Triple quotes are generally used for
O
9. represent the multiline or IndexError: string index out of range

10. docstring''' Reassigning Strings


Updating the content of the strings is as easy as assigning it to a
11. print(str3)
new string. The string object doesn't support item assignment i.e.,
Output:
Hello Python A string can only be replaced with new string since its content
Hello Python cannot be partially replaced. Strings are immutable in Python.
Triple quotes are generally used for Consider the following example.
represent the multiline or Example 2
docstring
1. str = "HELLO"
Strings indexing and splitting
Like other languages, the indexing of the Python strings starts2. print(str)
from 0. For example, The string "HELLO" is indexed as given in3. str = "hello"
the below figure.
4. print(str)
[By.- Prof. Narendra Kumar_CSE] Page 3
[Unit 3]

Output:
HELLO to print the actual meaning of escape
hello
characters such as "C://python". To define
Deleting the String any string as a raw string, the character r or
As we know that strings are immutable. We cannot delete or
remove the characters from the string. But we can delete the R is followed by the string.
entire string using the del keyword.
1. str = "JAVATPOINT" % It is used to perform string formatting. It
2. del str[1] makes use of the format specifiers used in C
Output:
TypeError: 'str' object doesn't support item deletion programming like %d or %f to map their

String Operators values in python. We will discuss how


formatting is done in python.
Operat Description
or Example
Consider the following example to understand the real use of
Python operators.
+ It is known as concatenation operator used 1. str = "Hello"
to join the strings given either side of the 2. str1 = " world"
operator. 3. print(str*3) # prints HelloHelloHello
4. print(str+str1)# prints Hello world
* It is known as repetition operator. It
5. print(str[4]) # prints o
concatenates the multiple copies of the
6. print(str[2:4]); # prints ll
same string.
7. print('w' in str) # prints false as w is not present in str

[] It is known as slice operator. It is used to 8. print('wo' not in str1) # prints false as wo is present in str1.

access the sub-strings of a particular string. 9. print(r'C://python37') # prints C://python37 as it is written


10. print("The string str : %s"%(str)) # prints The string str : Hello
[:] It is known as range slice operator. It is
used to access the characters from the Output:
HelloHelloHello
specified range. Hello world
o
ll
in It is known as membership operator. It False
False
returns if a particular sub-string is present in
the specified string. Escape Sequence-
not in It is also a membership operator and does Sr. Escape Descripti Example
Sequence on
the exact reverse of in. It returns true if a
particular substring is not present in the
1. \newline It ignores print("Python1 \
specified string.
the new Python2 \

r/R It is used to specify the raw string. Raw line. Python3")

strings are used in the cases where we need Output:


Python1

[By.- Prof. Narendra Kumar_CSE] Page 4


[Unit 3]

Python2 Tab Output:


Python3 Hello World!

2. \\ Backslash print("\\") 11. \v ASCII print("Hello \v


Output: Vertical World!")
\ Tab Output:
Hello
3. \' Single print('\'')
World!
Quotes Output:
' 12. \ooo Character print("\110\145\
with octal 154\154\157")
4. \\'' Double print("\"")
value Output:
Quotes Output:
Hello
"
13 \xHH Character print("\x48\x65\
5. \a ASCII print("\a")
with hex x6c\x6c\x6f")
Bell
value. Output:
Hello
6. \b ASCII print("Hello \b
Backspace World")
(BS) Output:
Hello World
Python Data Types
Variables can hold values, and every value has a data-type.
7. \f ASCII print("Hello \f Python is a dynamically typed language; hence we do not need to
Formfeed World!")
define the type of the variable while declaring it. The interpreter
implicitly binds the value with its type.
Hello World!
Python enables us to check the type of the variable used in the
program. Python provides us the type() function, which returns
8. \n ASCII print("Hello \n
the type of the variable passed.
Linefeed World!")
1. a=10
Output:
2. b="Hi Python"
Hello
3. c = 10.5
World!
4. print(type(a))
9. \r ASCII print("Hello \r 5. print(type(b))
Carriege World!") 6. print(type(c))
Output:
Return(C Output: <type 'int'>
R) World! <type 'str'>
<type 'float'>

10. \t ASCII print("Hello \t


Horizontal World!")

[By.- Prof. Narendra Kumar_CSE] Page 5


[Unit 3]
c is complex number: True
Standard data types Python supports three types of numeric data.
A variable can hold different types of values. For example, a
person's name must be stored as a string whereas its id must be 1. Int - Integer value can be any length such as integers 10,
stored as an integer. 2, 29, -20, -150 etc. Python has no restriction on the
Python provides various standard data types that define the
storage method on each of them. The data types defined in Python length of an integer. Its value belongs to int
are given below. 2. Float - Float is used to store floating-point numbers like
1. Numbers 1.9, 9.902, 15.2, etc. It is accurate upto 15 decimal
2. Sequence Type points.
3. Boolean 3. complex - A complex number contains an ordered pair,
4. Set i.e., x + iy where x and y denote the real and imaginary
5. Dictionary parts, respectively. The complex numbers like 2.14j, 2.0
+ 2.3j, etc.

Sequence Type
String

The string can be defined as the sequence of characters


represented in the quotation marks. In Python, we can use single,
double, or triple quotes to define a string.
String handling in Python is a straightforward task since Python
provides built-in functions and operators to perform operations in
the string.
In the case of string handling, the operator + is used to
concatenate two strings as the operation "hello"+"
python" returns "hello python".
The operator * is known as a repetition operator as the operation
"Python" *2 returns 'Python Python'.
Numbers The following example illustrates the string in Python.
Number stores numeric values. The integer, float, and complex Example - 1
values belong to a Python Numbers data-type. Python provides1. str = "string using double quotes"
the type() function to know the data-type of the variable.
Similarly, the isinstance() function is used to check an object2. print(str)
belongs to a particular class. 3. s = '''''A multiline
Python creates Number objects when a number is assigned to a
variable. For example; 4. string'''

1. a = 5 5. print(s)
Output:
2. print("The type of a", type(a)) string using double quotes
3. b = 40.5 A multiline
string
4. print("The type of b", type(b)) Consider the following example of string handling.
Example - 2
5. c = 1+3j
1. str1 = 'hello javatpoint' #string str1
6. print("The type of c", type(c))
2. str2 = ' how are you' #string str2
7. print(" c is a complex number", isinstance(1+3j,complex))
Output: 3. print (str1[0:2]) #printing first two character using slice operator
The type of a <class 'int'>
The type of b <class 'float'>
The type of c <class 'complex'> 4. print (str1[4]) #printing 4th character of the string

[By.- Prof. Narendra Kumar_CSE] Page 6


[Unit 3]

5. print (str1*2) #printing the string twice 3. print (type(tup))


6. print (str1 + str2) #printing the concatenation of str1 and str2 4. #Printing the tuple
Output:
he 5. print (tup)
o 6. # Tuple slicing
hello javatpointhello javatpoint
hello javatpoint how are you 7. print (tup[1:])
8. print (tup[0:1])
List 9. # Tuple concatenation using + operator
Python Lists are similar to arrays in C. However, the list can
contain data of different types. The items stored in the list are10. print (tup + tup)
separated with a comma (,) and enclosed within square brackets11. # Tuple repatation using * operator
[].
We can use slice [:] operators to access the data of the list. The12. print (tup * 3)
concatenation operator (+) and repetition operator (*) works with
13. # Adding value to tup. It will throw an error.
the list in the same way as they were working with the strings.
Consider the following example. 14. t[2] = "hi"
Output:
1. list1 = [1, "hi", "Python", 2]
<class 'tuple'>
2. #Checking type of given list ('hi', 'Python', 2)
('Python', 2)
3. print(type(list1)) ('hi',)
4. #Printing the list1 ('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
5. print (list1)
Traceback (most recent call last):
6. # List slicing File "main.py", line 14, in <module>
7. print (list1[3:]) t[2] = "hi";
TypeError: 'tuple' object does not support item assignment
8. # List slicing
9. print (list1[0:2])
Dictionary
10. # List Concatenation using + operator Dictionary is an unordered set of a key-value pair of items. It is
like an associative array or a hash table where each key stores a
11. print (list1 + list1)
specific value. Key can hold any primitive data type, whereas
12. # List repetation using * operator value is an arbitrary Python object.
The items in the dictionary are separated with the comma (,) and
13. print (list1 * 3) enclosed in the curly braces {}.
Output: Consider the following example.
[1, 'hi', 'Python', 2]
[2] 1. d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}
[1, 'hi']
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2] 2. # Printing dictionary
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2] 3. print (d)
4. # Accesing value using keys
Tuple 5. print("1st name is "+d[1])
A tuple is similar to the list in many ways. Like lists, tuples also
6. print("2nd name is "+ d[4])
contain the collection of the items of different data types. The
items of the tuple are separated with a comma (,) and enclosed in7. print (d.keys())
parentheses ().
A tuple is a read-only data structure as we can't modify the size8. print (d.values())
and value of the items of a tuple. Output:
1st name is Jimmy
Let's see a simple example of the tuple.
2nd name is mike
1. tup = ("hi", "Python", 2) {1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
dict_keys([1, 2, 3, 4])
2. # Checking type of tup dict_values(['Jimmy', 'Alex', 'john', 'mike'])

[By.- Prof. Narendra Kumar_CSE] Page 7


[Unit 3]
accept any number of arguments, but they can return only one
value in the form of expression.
Boolean Syntax
Boolean type provides two built-in values, True and False. These
values are used to determine the given statement true or false. It lambda arguments: expression
denotes by the class bool. True can be represented by any non-
zero value or 'T' whereas false can be represented by the 0 or 'F'.
Example 1
Consider the following example. 1. # a is an argument and a+10 is an expression which got evaluated
1. # Python program to check the boolean type and returned.
2. print(type(True)) 2. x = lambda a:a+10
3. print(type(False)) 3. # Here we are printing the function object
4. print(false) 4. print(x)
Output:
<class 'bool'> 5. print("sum = ",x(20))
<class 'bool'> Output:
NameError: name 'false' is not defined <function <lambda> at 0x0000019E285D16A8>
sum = 30

Set
Python Set is the unordered collection of the data type. It is Built-In Functions
iterable, mutable(can modify after creation), and has unique
elements. In set, the order of the elements is undefined; it may The Python interpreter supports many functions
return the changed sequence of the element. The set is created by that are built-in: sixty-eight,
using a built-in function set(), or a sequence of elements is passed Math
in the curly braces and separated by the comma. It can contain
Function Description
various types of values. Consider the following example.
abs() Returns absolute value of a number
1. # Creating Empty set
divmod() Returns quotient and remainder of integer division
2. set1 = set() max() Returns the largest of the given arguments
3. set2 = {'James', 2, 3,'Python'} or items in an iterable
4. #Printing Set value min() Returns the smallest of the given arguments
5. print(set2)
or items in an iterable
pow() Raises a number to a power
6. # Adding element to the set
round() Rounds a floating-point value
7. set2.add(10)
sum() Sums the items of an iterable
8. print(set2)
9. #Removing element from the set
Type Conversion
10. set2.remove(2) Function Description
11. print(set2) ascii() Returns a string containing a printable
Output: representation of an object
{3, 'Python', 'James', 2}
{'Python', 'James', 3, 2, 10} bin() Converts an integer to a binary string
{'Python', 'James', 3, 10} bool() Converts an argument to a Boolean value
chr() Returns string representation of character given
by integer argument
Python Lambda Functions complex()
Python Lambda function is known as the anonymous function Returns a complex number constructed from
that is defined without a name. Python allows us to not declare arguments
the function in the standard manner, i.e., by using float() Returns a floating-point object constructed
the def keyword. Rather, the anonymous functions are declared from a number or string
by using the lambda keyword. However, Lambda functions can

[By.- Prof. Narendra Kumar_CSE] Page 8


[Unit 3]

Function Description
hex() Converts an integer to a hexadecimal string Classes, Attributes, and Inheritance
int() Returns an integer object constructed from a Function Description
number or string classmethod() Returns a class method for a function
oct() Converts an integer to an octal string delattr() Deletes an attribute from an object
ord() Returns integer representation of a character getattr() Returns the value of a named attribute of an
repr() Returns a string containing a printable object
representation of an object hasattr() Returns True if an object has a given
str() Returns a string version of an object attribute
type() Returns the type of an object or creates a new isinstance() Determines whether an object is an instance
type object of a given class
issubclass() Determines whether a class is a subclass of
Iterables and Iterators a given class
Function Description property() Returns a property value of a class
all() Returns True if all elements of an iterable are setattr() Sets the value of a named attribute of an
true object
any() Returns True if any elements of an iterable are super() Returns a proxy object that delegates
true method calls to a parent or sibling class
enumerate() Returns a list of tuples containing indices and
values from an iterable Input/Output
filter() Filters elements from an iterable Function Description
iter() Returns an iterator object format() Converts a value to a formatted representation
len() Returns the length of an object
map() Applies a function to every item of an iterable input() Reads input from the console
next() Retrieves the next item from an iterator open() Opens a file and returns a file object
range() Generates a range of integer values print() Prints to a text stream or the console
reversed() Returns a reverse iterator
slice() Returns a slice object Variables, References, and Scope
sorted() Returns a sorted list from an iterable Function Description
zip() Creates an iterator that aggregates elements dir() Returns a list of names in current local scope
from iterables or a list of object attributes
Composite Data Type globals() Returns a dictionary representing the current
Function Description global symbol table
id() Returns the identity of an object
bytearray() Creates and returns an object of
the bytearray class locals() Updates and returns a dictionary representing
bytes() Creates and returns a bytes object (similar current local symbol table
to bytearray, but immutable) vars() Returns __dict__ attribute for a module, class,
dict() Creates a dict object or object
frozenset() Creates a frozenset object
list() Creates a list object Miscellaneous
object() Creates a new featureless object Function Description
set() Creates a set object callable() Returns True if object appears callable
tuple() Creates a tuple object compile() Compiles source into a code or AST object

[By.- Prof. Narendra Kumar_CSE] Page 9


[Unit 3]

Function Description Unpacking in Python


eval() Evaluates a Python expression
exec() Implements dynamic execution of Python
Unpacking in Python refers to an operation that consists
code
of assigning an iterable of values to a tuple (or list ) of
hash() Returns the hash value of an object
variables in a single assignment statement. As a
help() Invokes the built-in help system
complement, the term packing can be used when we
memoryview() Returns a memory view object
collect several values in a single variable using the
staticmethod() Returns a static method for a function iterable unpacking operator, * .
__import__() Invoked by the import statement

Packing and Unpacking in Python


Use lambda function with filter()
Python allows a tuple (or list) of variables to appear on
The Python built-in filter() function accepts a function and a list the left side of an assignment operation. Each variable in
as an argument. It provides an effective way to filter out all the tuple can receive one value (or more, if we use the *
elements of the sequence. It returns the new sequence in which operator) from an iterable on the right side of the
the function evaluates to True.
Consider the following example where we filter out the only odd assignment.
number from the given list.
1. #program to filter out the tuple which contains odd n
In Python, we can put a tuple of variables on the left side
umbers of an assignment operator (=) and a tuple of values on the
2. lst = (10,22,37,41,100,123,29) right side. The values on the right will be automatically
assigned to the variables on the left according to their
3. oddlist = tuple(filter(lambda x:(x%3 == 0),lst)) # the position in the tuple. This is commonly known as tuple
tuple contains all the items of the tuple for which the unpacking in Python. Check out the following example:
lambda function evaluates to true
>>> (a, b, c) = (1, 2, 4)
4. print(oddlist)
5. Output:
6. (37, 41, 123, 29)
>>> a

1
Using lambda function with map()
The map() function in Python accepts a function and a list. It >>> b
gives a new list which contains all modified items returned by the
function for each item. 2
Consider the following example of map() function.
1. #program to filter out the list which contains odd nu >>> c
mbers
4
2. lst = (10,20,30,40,50,60)
3. square_list = list(map(lambda x:x**2,lst)) # the tupl When we put tuples on both sides of an assignment
e contains all the items of the list for which the lamb operator, a tuple unpacking operation takes place. The
values on the right are assigned to the variables on the left
da function evaluates to true according to their relative position in each tuple. As you
4. print(square_tuple) can see in the above example, a will be 1, b will be 2, and
5. Output: c will be 4.
6. (100, 400, 900, 1600, 2500, 3600)

[By.- Prof. Narendra Kumar_CSE] Page 10

You might also like