0% found this document useful (0 votes)
20 views130 pages

Module 2

This document provides an introduction to Python programming, covering its features, data types, and basic programming concepts. It explains the differences between interactive and script modes, and details various data structures such as lists and tuples. Additionally, it highlights Python's applications in various industries and its suitability for beginners.

Uploaded by

sakshiverma.h
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)
20 views130 pages

Module 2

This document provides an introduction to Python programming, covering its features, data types, and basic programming concepts. It explains the differences between interactive and script modes, and details various data structures such as lists and tuples. Additionally, it highlights Python's applications in various industries and its suitability for beginners.

Uploaded by

sakshiverma.h
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

CSE1021- Problem Solving

and Programming
UNIT II
PYTHON
DATA, EXPRESSIONS, STATEMENTS
Python interpreter and interactive mode; values and types: int,
float, Boolean, string, and list; variables, expressions, statements,
tuple assignment, precedence of operators, comments; Modules
and functions, function definition and use, flow of execution,
parameters and arguments.
PYTHON - INTRODUCTION
• Python is a general purpose, interpreted, interactive, high-level and
object-oriented programming language
• Developed by Guido Van Rossum, when he was working
at CWI (Centrum Wiskunde & Informatica) which is a National
Research Institute for Mathematics and Computer Science in
Netherlands.
• The language was released in 1991.
• Python got its name from a BBC comedy series from seventies-
"Monty Python’s Flying Circus".
PYTHON - INTRODUCTION
• Python is an easy to learn, powerful high-level programming
language.
• It has a simple but effective approach to object-oriented
programming.
• Python’s graceful semantics and syntax together with its interpreted
nature make it an ideal language for scripting and rapid application
development in many fields.
PYTHON - INTRODUCTION

Python is interpreted: Python is processed at runtime by the interpreter. You do


not need to compile your program before executing it.

Python is Interactive: You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.

Python is Object-Oriented: Python supports Object-Oriented style or technique of


programming that encapsulates code within objects.

Python is a Beginner's Language: Python is a great language for the beginner-level


programmers and supports the development of a wide range of applications
PYTHON - INTRODUCTION

Easy to learn and maintain, Portable and Open Source


Language

Scalable, High level Language and Extensible

Bit Torrent file sharing, Google search engine, YouTube, Intel,


Cisco, HP, IBM, Facebook
Major Applications (in Companies):

• In operations of Google search engine, Youtube etc.


• Bit Torrent peer to peer file sharing is written using Python.
• Intel, Cisco, HP, IBM, etc use Python for hardware testing.
• Maya provides a Python scripting API.
• i–Robot uses Python to develop commercial Robot.
• NASA and others use Python for their scientific programming task.
Salient features of Python

• It is a general purpose programming language which can be used for both


scientific and non-scientific programming.
• It is excellent for beginners as the language is interpreted, hence gives
immediateresults.
• It implements the concept of exception handling and dynamic binding
better than the other languages of its time.
• The programs written in Python are easily readable and understandable.
• It is a platform independent programming language.
• It is suitable as an extension language for customizable applications.
• It is easy to learn and use.
INTERPRETER VS COMPILER

Interpreter: To execute a program in a high-level language by translating it one line at a time.

PYTHON

Compiler: To translate a program written in a high-level language into a low-level language all at once,
in preparation for later execution.

C, C++, Java
Compiler Vs Interpreter
DOWNLOAD PYTHON
• [Link]
• [Link]
• Online Python Compiler
Setting up Python Interpreter

• To write and run Python program, we need to have Python


interpreter installed in our computer.
• IDLE (GUI integrated) is the standard, most popular Python
development environment.
• IDLE refers to Integrated Development Environment.
• It lets edit, run, browse and debug Python Programs from a single
interface.
• This environment makes it easy to write programs.
• Python shell can be used in two ways,
• i.e., interactive mode and script mode.
• Where Interactive Mode, as the name suggests, allows us to interact
with OS;
• script mode let us to create and edit python source file.
Interactive mode
• Here,
We type a Python statement and the interpreter displays the result(s)
immediately.
Basic Programming
C CODE: Hello.c

#include <stdio.h>
int main() {
// printf() displays the string inside quotation
printf("Hello, World!");
return 0;
}

PYTHON CODE: [Link]

print(‘Hello, World!’)
Basic Programming
C CODE: Addition.c
PYTHON CODE: [Link]
#include <stdio.h>
num1 = 1.5
int main() {
num2 = 6.3
int number1=2, number2=3, sum;
sum = num1 + num2
// calculating sum
# Display the sum
sum = number1 + number2;
print(‘total’, sum))
printf(“Total", sum);
return 0;
}
PYTHON INTERPRETER

Python Interpreter is a program that reads and executes Python code. It uses 2 modes of Execution.

1. Interactive mode

2. Script mode
INTERACTIVE MODE
Interactive Mode, as the name suggests, allows us to interact with OS.
When we type Python statement, interpreter displays the result(s) immediately.
Advantages:
Python, in interactive mode, is good enough to learn, experiment or explore.
Working in interactive mode is convenient for beginners and for testing small
pieces of code.
INTERACTIVE MODE
Drawback:
We cannot save the statements and have to retype all the statements once again
to re-run them.
In interactive mode, you type Python programs and the interpreter displays the
result:
>>>1 + 1
>>> 2
INTERACTIVE MODE
• The chevron, >>>, is the prompt the interpreter uses to indicate that
it is ready for you to enter code.
• If you type 1 + 1, the interpreter replies 2.

>>> print ('Hello, World!')


Hello, World!
INTERACTIVE MODE
SCRIPT MODE
• In script mode, we type python program in a file and then use
interpreter to execute the content of the file.

• Scripts can be saved to disk for future use.

• Python scripts have the extension .py, meaning that the filename
ends with .py

• Save the code with [Link] and run the interpreter in script
mode to execute the script.
• Working in interactive mode is convenient for beginners
• For testing small pieces of code, as we can test them immediately,
interactive mode is good.
• But for coding more than few lines, we should always save our code
so that we may modify and reuse the code.
SCRIPT MODE

Interactive mode Script mode


A way of using the Python interpreter by A way of using the Python interpreter to
typing commands and expressions at the read and execute statements in a script.
prompt.
Cant save and edit the code Can save and edit the code
If we want to experiment with the code, If we are very clear about the code, we can
we can use interactive mode. use script mode.
we cannot save the statements for further we can save the statements for further use
use and we have to retype and we no need to retype
all the statements to re-run them. all the statements to re-run them.
We can see the results immediately. We cant see the code immediately.
VALUES AND DATA TYPES
Value
Value can be any letter ,number or string.
EX, Values are 2, 42.0, and 'Hello, World!'. (These values belong to different datatypes.)

Data type
Every value in Python has a data type. It is a set of values, and the allowable operations on those
values.
VALUES AND DATA TYPES
VALUES AND DATA TYPES
NUMBERS
❖ Number data type stores Numerical Values.

❖ This data type is immutable [i.e. values/items cannot be changed].

❖ Python supports integers, floating point numbers and complex numbers. They are defined as,
SEQUENCE
❖▪ A sequence is an ordered collection of items, indexed by positive integers.
❖ It is a combination of mutable (value can be changed) and immutable (values cannot be changed) data
types.
❖ There are three types of sequence data type available in Python, they are

• Strings
• Lists
• Tuples
STRINGS
A String in Python consists of a series or sequence of characters - letters,
▪ numbers, and special characters.
Strings are marked by quotes:
∙ single quotes (' '), Eg, 'This a string in single quotes'
∙ double quotes (" "), Eg, "This a string in double quotes“
∙ triple quotes (""“ """), Eg, This is a paragraph. It is made up of
€ multiple lines and sentences."""
▪ Individual character in a string is accessed using a subscript (index).
Characters can be accessed using indexing and slicing operations
Strings are immutable i.e. the contents of the string cannot be changed
after it is created.
STRINGS

Strings and Operations

Indexing
Concatenation
Slicing
Repetition
Membership

Live Examples …….


LISTS
• A list in Python is used to store the sequence of various types of data.
L1 = ["John", 102, "USA"]
L2 = [1, 2, 3, 4, 5, 6]
• The items in the list are separated with the comma (,) and enclosed with
the square brackets [].
• Python lists are mutable type it means that we can modify its element after
it created.
• However, Python consists of six data-types
• They are capable to store the sequences.
• But the most common and reliable type is the list.
• print(type(L1))

• print(type(L2))

• <class ‘list’>
Characteristics of Lists

• The lists are ordered.


a = [1,2,"Peter",4.50,"Ricky",5,6]
b = [1,2,5,"Peter",4.50,"Ricky",6]
a ==b This results in False. Why?
• The element of the list can access by index.
• The lists are the mutable type.
• A list can store the number of various elements.
LISTS
Lists and Operations
Indexing
Concatenation
Slicing
Repetition
Membership
Updation-Deletion and Insertion

Live Examples …….


• list_varible(start:stop:step)
• The start denotes the starting index position of the list.
• The stop denotes the last index position of the list.
• The step is used to skip the nth element within a start:stop
list = [1,2,3,4,5,6,7]
print(list[0])
print(list[1])
print(list[2])
print(list[3])
# Slicing the elements
print(list[0:6])
print(list[:])
print(list[2:5])
print(list[1:6:2])
• Unlike other languages, Python provides the flexibility to use the
negative indexing also.
• The negative indices are counted from the right.
• The last element (rightmost) of the list has the index -1;
• its adjacent left element is present at the index -2 and so on until the
left-most elements are encountered.
Updating List values
• Lists are the most versatile data structures in Python since they are
mutable, and their values can be updated by using the slice and
assignment operator.
list = [1, 2, 3, 4, 5, 6]
print(list)
[1, 2, 3, 4, 5, 6]
list[2] = 10 [1, 2, 10, 4, 5, 6]
print(list) [1, 89, 78, 4, 5, 6]
list[1:3] = [89, 78] [1, 89, 78, 4, 5, 25]
print(list)
list[-1] = 25
print(list)
l1 = [1, 2, 3, 4] l2 = [5, 6, 7, 8]
TUPLES
❖ A tuple is same as list, except that the set of elements is enclosed in
▪ parentheses instead of square brackets.
❖ Tuple is an immutable list. i.e. once a tuple has been created, you can't add
▪ elements to a tuple or remove elements from the tuple.


Benefit of Tuple:
❖ Tuples are faster than lists.
❖ If the user wants to protect the data from accidental changes, tuple can be
used.
❖ Tuples can be used as keys in dictionaries, while lists can't.
TUPLES

Tuples and Operations

Indexing
Concatenation
Slicing
Repetition

Live Examples …….


T1 = (101, "Peter", 22)
T2 = ("Apple", "Banana", "Orange")
T3 = 10,20,30,40,50

print(type(T1)) <class 'tuple'>


print(type(T2)) <class 'tuple'>
print(type(T3)) <class 'tuple'>
• Empty Tuple
T4 = ()
• Creating a tuple with single element is slightly different. We will need
to put comma after the element to declare the tuple.
tup1 = ("JavaTpoint")
print(type(tup1)) <class 'str'>
#Creating a tuple with single element
tup2 = ("JavaTpoint",)
print(type(tup2)) <class 'tuple'>
tuple1 = (10, 20, 30, 40, 50, 60)
print(tuple1)
(10, 20, 30, 40, 50, 60)
count = 0
for i in tuple1:
tuple1[0] = 10
print("tuple1[%d] = %d"%(count, i)) tuple1[1] = 20
count = count+1 tuple1[2] = 30
tuple1[3] = 40
tuple1[4] = 50
tuple1[5] = 60
tuple1 = tuple(input("Enter the tuple elements ..."))
print(tuple1) Enter the tuple elements ...
count = 0 123456
for i in tuple1: ('1', '2', '3', '4', '5', '6')
print("tuple1[%d] = %s"%(count, i)) tuple1[0] = 1
count = count+1 tuple1[1] = 2
tuple1[2] = 3
tuple1[3] = 4
tuple1[4] = 5
tuple1[5] = 6
Tuple indexing and slicing

• The indexing and slicing in the tuple are similar to lists. The indexing
in the tuple starts from 0 and goes to length(tuple) - 1.
• The items in the tuple can be accessed by using the index [] operator.
• Python also allows us to use the colon operator to access multiple
items in the tuple.
tuple = (1,2,3,4,5,6,7)
#element 1 to end
print(tuple[1:]) (2, 3, 4, 5, 6, 7)
#element 0 to 3 element (1, 2, 3, 4)
print(tuple[:4]) (1, 2, 3, 4)
#element 1 to 4 element (1, 3, 5)
print(tuple[1:5])
# element 0 to 6 and take step of 2
• print(tuple[0:6:2])
tuple1 = (1, 2, 3, 4, 5)
print(tuple1[-1]) 5
print(tuple1[-4])
2
print(tuple1[-3:-1])
print(tuple1[:-1])
(3, 4)
print(tuple1[-2:]) (1, 2, 3, 4)
(4, 5)
Deleting Tuple

• Unlike lists, the tuple items cannot be deleted by using the del keyword as
tuples are immutable.
• To delete an entire tuple, we can use the del keyword with the tuple name
tuple1 = (1, 2, 3, 4, 5, 6)
print(tuple1) (1, 2, 3, 4, 5, 6)
del tuple1[0] Traceback (most recent call last):
print(tuple1) File "[Link]",
del tuple1 line 4, in <module> print(tuple1)
print(tuple1) NameError: name 'tuple1' is not defined
t = (1, 2, 3, 4, 5)
t1 = (6, 7, 8, 9)
Mapping and Dictionaries
❖ Unordered and Mutable data type

Dictionaries


▪ Lists are ordered sets of objects, whereas dictionaries are unordered sets.
❖ Dictionary is created by using curly brackets. i,e. {}

▪ Dictionaries are accessed via keys and not via their position.
❖ A dictionary is an associative array (also known as hashes). Any key of the dictionary is
▪ associated (or mapped) to a value.
❖ The values of a dictionary can be any Python data type. So dictionaries are unordered
key-value-pairs (The association of a key and a value is called a key-value pair )

Dictionaries don't support the sequence operation of the sequence data types like strings, tuples
and lists.
DICTIONARIES

Operations

Indexing
Slicing
Creating a Dictionary

Live Examples …….


DATA, EXPRESSIONS,
STATEMENTS
Variables

A variable allows us to store a value by assigning it to a name,


which can be used later.

Named memory locations to store values.

Programmers generally choose names for their variables that are


meaningful.

It can be of any length. No space is allowed.

We don't need to declare a variable before using it. In Python,


we simply assign a value to a variable and it will exist.
Variables

A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).

Rules for Python variables:

A variable name must start with a letter or the underscore


character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric
characters and underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are
three different variables)
Assigning value to variable:

Value should be given on the right side of assignment operator(=) and variable on left side.

>>>counter =45
print(counter)

Assigning a single value to several variables simultaneously:

>>> a=b=c=100

Assigning multiple values to multiple variables:

>>> a,b,c=2,4,"ram"
KEYWORDS:

• Keywords are the reserved words in Python.

• We cannot use a keyword as variable name, function name or any


other identifier.
• They are used to define the syntax and structure of the Python
language.

• Keywords are case sensitive.


KEYWORDS:
IDENTIFIERS:
• Identifier is the name given to entities like class, functions, variables etc. in Python.

1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A


to Z) or digits (0 to 9) or an underscore (_).

2. All are valid example.

3. An identifier cannot start with a digit.

4. Keywords cannot be used as identifiers

5. Cannot use special symbols like !, @, #, $, % etc. in our identifier.

6. Identifier can be of any length.


IDENTIFIERS:

• Names like myClass, var_1, and this_is_a_long_variable


STATEMENTS AND EXPRESSIONS:
Statements:
Instructions that a Python interpreter can
executes are called statements.

A statement is a unit of code like creating


a variable or displaying a value.

>>> n = 17
>>> print(n)

Here, The first line is an assignment statement that gives a value to n.


The second line is a print statement that displays the value of n.
INPUT

Input is data entered by user (end user)


in the program.

In python, input () function is available


for input.

#python accepts string as default data


type. conversion is required for type.
OUTPUT

Output can be displayed to the user


using Print statement .

Syntax:
print (expression/constant/variable)
COMMENTS:

A hash sign (#) is the beginning of a comment.

Anything written after # in a line is ignored by


interpreter.

Python does not have multiple-line commenting


feature. You have to comment each line
individually as follows :

Eg: # This is a comment. Eg: percentage = (minute * 100) / 60


# This is a comment, too. # calculating percentage of an hour
# I said that already.
DOCSTRING

Docstring is short for documentation string.


Syntax:
functionname__doc.__

It is a string that occurs as the first statement in


a module, function, class, or method definition.
We must write what a function/class does in the
docstring.

Triple quotes are used while writing docstrings.


LINES AND INDENTATION
Most of the programming languages like C, C++, Java use braces { } to define a
block of code. But, python uses indentation.
Blocks of code are denoted by line
indentation.
It is a space given to the block of codes for class and function definitions or
flow control.
QUOTATION IN PYTHON
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals.
Anything that is represented using quotations are considered as string.
TUPLE ASSIGNMENT

• An assignment to all of the elements in a tuple using a single assignment statement.

• Python has a very powerful tuple assignment feature that allows a tuple of variables on
the left of an assignment to be assigned values from a tuple on the right of the
assignment.

• The left side is a tuple of variables; the right side is a tuple of values.

• Each value is assigned to its respective variable.


• All the expressions on the right side are evaluated before any of the assignments. This
feature makes tuple assignment quite versatile.
• Naturally, the number of variables on the left and the number of values on the right have
to be the same.
TUPLE ASSIGNMENT

Example:
• It is useful to swap the values of two variables. With conventional assignment statements,
we have to use a temporary variable. For example, to swap a and b:
TUPLE ASSIGNMENT
• Tuple assignment solves this problem neatly:

(a, b) = (b, a)

• One way to think of tuple assignment is as tuple packing/unpacking.


• In tuple packing, the values on the left are ‘packed’ together in a tuple:
>>> b = ("George", 25, "20000") # tuple

• In tuple unpacking, the values in a tuple on the right are ‘unpacked’ into
the variables/names on the right:
TUPLE ASSIGNMENT
• The right side can be any kind of sequence (string,list,tuple)
OPERATORS
• Operators are the constructs which can manipulate the value of operands.

• Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is


called operator
• Types of Operators:
-Python language supports the following types of operators

Arithmetic Operators

Comparison (Relational) Operators

Assignment Operators

Logical Operators

Bitwise Operators

Membership Operators

Identity Operators
Arithmetic operators
• They are used to perform mathematical operations like addition,
subtraction, multiplication etc. Assume, a=10 and b=5
Comparison (Relational) Operators:
• Comparison operators are used to compare values.

• It either returns True or False according to the condition. Assume, a=10 and
b=5
Comparison (Relational) Operators:
• Comparison operators are used to compare values.

• It either returns True or False according to the condition. Assume, a=10 and
b=5
Assignment Operators
• Assignment operators are used in Python to assign values to variables.
Assignment Operators
Assignment Operators
Logical Operators
• Logical operators are the and, or, not operators.
Bitwise Operators:
• A bitwise operation operates on one or more bit patterns at the level of individual bits

Example: Let x = 10 (0000 1010 in binary) and y = 4 (0000


0100 in binary)
Bitwise Operators:
• A bitwise operation operates on one or more bit patterns at the level of individual bits
Membership Operators
• Evaluates to find a value or a variable is in the specified sequence of string, list, tuple,
dictionary or not.

• Let, x=[5,3,6,4,1]. To check particular item in list or not, in and not in operators are used.
Identity Operators
• They are used to check if two values (or variables) are located on the same part of the
memory
OPERATOR PRECEDENCE
When an expression contains more than one operator, the order of evaluation depends on the
order of operations.
OPERATOR PRECEDENCE
• For mathematical operators, Python follows mathematical
convention.
• The acronym PEMDAS (Parentheses, Exponentiation, Multiplication,
Division, Addition, Subtraction) is a useful way to remember the
rules:
• Parentheses have the highest precedence and can be used to force an
expression to evaluate in the order you want. Since expressions in
parentheses are evaluated first, 2 * (3-1)is 4, and (1+1)**(5-2) is 8.
• You can also use parentheses to make an expression easier to read,
as in (minute*100) / 60, even if it doesn’t change the result.
OPERATOR PRECEDENCE
• Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not
27, and 2 *3**2 is 18, not 36.

• Multiplication and Division have higher precedence than Addition and


Subtraction. So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.

• Operators with the same precedence are evaluated from left to right
(except exponentiation).
Example:
a = 20
b = 10
c = 15
d=5
e=0
• e = (a + b) * c / d #( 30 * 15 ) / 5
• print "Value of (a + b) * c / d is ", e
• e = ((a + b) * c) / d # (30 * 15 ) / 5
• print "Value of ((a + b) * c) / d is ", e
• e = (a + b) * (c / d); # (30) * (15/5)
• print "Value of (a + b) * (c / d) is ", e
• e = a + (b * c) / d; # 20 + (150/5)
• print "Value of a + (b * c) / d is ", e
• Output is:
• Value of (a + b) * c / d is 90
• Value of ((a + b) * c) / d is 90
• Value of (a + b) * (c / d) is 90
• Value of a + (b * c) / d is 50
Functions
• Function is a sub program which consists of set of instructions used to perform a
specific task. A large program is divided into basic building blocks called function.
• Need For Function:
• When the program is too complex and large they are divided into parts. Each part
is separately coded and combined into single program. Each subprogram is called
as function.
• Debugging, Testing and maintenance becomes easy when the program is divided
into subprograms.
• Functions are used to avoid rewriting same code again and again in a program.
• Function provides code re-usability
• The length of the program is reduced.
Functions
• user defined function
• Built in function
• Built in functions
• Built in functions are the functions that are already created and
stored in python.
• These built in functions are always available for usage and accessed
by a programmer. It cannot be modified.
Functions
Built in function Description
>>>max(3,4) # returns largest element
4
>>>min(3,4) # returns smallest element
3
>>>len("hello") #returns length of an object
5
>>>range(2,8,1) #returns range of given values
[2, 3, 4, 5, 6, 7]
>>>round(7.8) #returns rounded integer of the given number
8.0
>>>chr(5) #returns a character (a string) from an integer
\x05'
>>>float(5) #returns float number from string or integer
5.0
>>>int(5.0) # returns integer from string or float
5
>>>pow(3,5) #returns power of given number
243
>>>type( 5.6) #returns data type of object to which it belongs
<type 'float'>
>>>t=tuple([4,6.0,7]) # to create tuple of items from list
(4, 6.0, 7)
>>>print("good morning") # displays the given object
Good morning
>>>input("enter name: ") # reads and returns the given string
enter name : George
User Defined Functions
• User defined functions are the functions that programmers create for
their requirement and use.
• These functions can then be combined to form module which can be
used in other programs by importing them.
• Advantages of user defined functions:
• Programmers working on large project can divide the workload by making
different functions.
• If repeated code occurs in a program, function can be used to include those
codes and execute when needed by calling that function.
Function definition: (Sub program)
• def keyword is used to define a function.
• Give the function name after def keyword followed by parentheses in
which arguments are given.
• End with colon (:)
• Inside the function add the program statements to be executed
• End with or without return statement
Function definition: (Sub program)
Syntax:
• def fun_name(Parameter1,Parameter2…Parameter n):
• statement1
• statement2…

• statement n
• return[expression]
Example:
• def my_add(a,b):
• c=a+b
• return c
Function Calling: (Main Function)
• Once we have defined a function, we can call it from another function, program
or even the Python prompt.
• To call a function we simply type the function name with appropriate
arguments.
Example:
• x=5
• y=4
• my_add(x,y)
Flow of Execution:
• The order in which statements are executed is called the flow of execution
• Execution always begins at the first statement of the program.
• Statements are executed one at a time, in order, from top to bottom.
• Function definitions do not alter the flow of execution of the program, but
remember that statements inside the function are not executed until the
function is called.
• Function calls are like a bypass in the flow of execution. Instead of going to the
next statement, the flow jumps to the first line of the called function, executes all
the statements there, and then comes back to pick up where it left off.
Note: When you read a program, don’t read from top to bottom. Instead, follow
the flow of execution. This means that you will read the def statements as you are
scanning from top to bottom, but you should skip the statements of the function
definition until you reach a point where that function is called.
Function Prototypes:
i) Function without arguments and without return type
• In this type no argument is passed through the function call and no output is return to main
function
• The sub function will read the input values perform the operation and print the result in the same
block
ii) Function with arguments and without return type
• Arguments are passed through the function call but output is not return to the main function
iii) Function without arguments and with return type
• In this type no argument is passed through the function call but output is return to the main
function.
iv) Function with arguments and with return type
• In this type arguments are passed through the function call and output is return to the main
function
Parameters and Arguments:
Parameters:
• Parameters are the value(s) provided in the parenthesis when we write function header.
• These are the values required by function to work.
• If there is more than one value required, all of them will be listed in parameter list
separated by comma.
• Example: def my_add(a,b):
Arguments:
• Arguments are the value(s) provided in function call/invoke statement.
• List of arguments should be supplied in same way as parameters are listed.
• Bounding of parameters to arguments is done 1:1, and so there should be same number
and type of arguments as mentioned in parameter list.
• Example: my_add(x,y)
RETURN STATEMENT
• The return statement is used to exit a function and go back to the place from where it was called.
• If the return statement has no arguments, then it will not return any values. But exits from function.
Syntax:
• return[expression]
Example:
• def my_add(a,b):
• c=a+b
• return c
• x=5
• y=4
• print(my_add(x,y))
• Output: 9
ARGUMENTS TYPES
[Link] Arguments
[Link] Arguments
[Link] Arguments
[Link] length Argument
Required Arguments: The number of arguments in the function call should match exactly
with the function definition.

Output:
Name:george
Age 56
Keyword Arguments:
• Python interpreter is able to use the keywords provided to match the
values with parameters even though if they are arranged in out of order.
• def my_details( name, age ):
print("Name: ", name)
print("Age ", age)
return
my_details(age=56,name="george")
Output:
• Name: george
• Age 56
Default Arguments:
Assumes a default value if a value is not provided in the function call for that
argument.
• def my_details( name, age=40 ):
print("Name: ", name)
print("Age ", age)
return
my_details(name="george")
Output:
• Name: george
• Age 40
Variable length Arguments
• If we want to specify more arguments than specified while defining
the function, variable length arguments are used. It is denoted by *
symbol before parameter.
• def my_details(*name ):
print(*name)
my_details("rajan","rahul","micheal",ärjun")
Output:
• rajan rahul micheal ärjun
MODULES
• A module is a file containing Python definitions ,functions, statements and
instructions.
• Standard library of Python is extended as modules.
• To use these modules in a program, programmer needs to import the module.
• Once we import a module, we can reference or use to any of its functions or
variables in our code.
• There is large number of standard modules also available in python.
• Standard modules can be imported the same way as we import our user-defined
modules.
• Every module contains many function.
• To access one of the function , you have to specify the name of the module and the
name of the function separated by dot . This format is called dot notation.
Syntax
• import module_name
• module_name.function_name(variable)
Four Ways to Import Module

You might also like