0% found this document useful (0 votes)
31 views26 pages

Unit Ii Data, Expressions, Statements

Uploaded by

Hridey Dalal
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)
31 views26 pages

Unit Ii Data, Expressions, Statements

Uploaded by

Hridey Dalal
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/ 26

UNIT II

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; Illustrative programs: exchange the values of two
variables, circulate the values of n variables, distance between two points.

1. Introduction to python:
Python is a general-purpose interpreted, interactive, object-oriented, and high-level
programming language. It was created by Guido van Rossum during 1985- 1990.
Python got its name from “Monty Python’s flying circus”. Python was released in the
year 2000.
 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.
1.1. Python Features:
 Easy-to-learn: Python is clearly defined and easily readable. The structure
of the program is very simple. It uses few keywords.
 Easy-to-maintain: Python's source code is fairly easy-to-maintain.
 Portable: Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
 Interpreted: Python is processed at runtime by the interpreter. So, there is no
need to compile a program before executing it. You can simply run the program.
 Extensible: Programmers can embed python within their C,C++,Java script
,ActiveX, etc.
 Free and Open Source: Anyone can freely distribute it, read the source code, and
edit it.
 High Level Language: When writing programs, programmers concentrate on
solutions of the current problem, no need to worry about the low level details.
 Scalable: Python provides a better structure and support for large programs
than shell scripting.
1.2. Applications:
 Bit Torrent file sharing
 Google search engine, youtube
 Intel, Cisco, HP, IBM
 i–Robot
 NASA
 Facebook, Drop box

1 Unit 2: Data ,expressions, Statements by C.Vijayalakshmi, AP, CSE


1.3. Python interpreter:
Interpreter: To execute a program in a high-level language by translating it one line at
a time.
Compiler: To translate a program written in a high-level language into a low-level
language all at once, in preparation for later execution.

Compiler Interpreter
Interpreter Takes Single instruction as
Compiler Takes Entire program as input
input
No Intermediate Object Code
Intermediate Object Code is Generated
is Generated
Conditional Control Statements are Conditional Control Statements are
Executes faster Executes slower
Memory Requirement is More(Since Object
Memory Requirement is Less
Code is Generated)
Every time higher level program is
Program need not be compiled every time
converted into lower level program
Errors are displayed after entire Errors are displayed for every
program is checked instruction interpreted (if any)
Example : C Compiler Example : PYTHON

1.4 Modes of 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
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:
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 filename.py and run the interpreter in script mode to execute
the script.

2 Unit 2: Data ,expressions, Statements by C.Vijayalakshmi, AP, CSE


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.

Integrated Development Learning Environment (IDLE):


 Is a graphical user interface which is completely written in Python.
 It is bundled with the default implementation of the python language and also
comes with optional part of the Python packaging.

Features of IDLE:
 Multi-window text editor with syntax highlighting.
 Auto completion with smart indentation.
 Python shell to display output with syntax highlighting.

2. VALUES AND DATA TYPES

Values:
Value can be any letter, number or string.
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong to different data types.)

Data type:
Every value in Python has a data type.
It is a set of values, and the allowable operations on those values.
Python has four standard data types:

3 Unit 2: Data ,expressions, Statements by C.Vijayalakshmi, AP, CSE


Numbers:
 Number data type stores Numerical Values.
 This data type is immutable [i.e. values/items cannot be changed].
 Python supports following number types
1. integers
2. floating point numbers
3. Complex numbers.
2.1 integer:
Integers are the whole numbers consisting of +ve or –ve sign.

Example:
a=10
a=eval(input(“enter a value”))
a=int(input(“enter a value”))

2.2 Float:
it has decimal part and fractional part.

Example:
a=3.15
a=eval(input(“enter a value”))
a=float(input(“enter a value”))

2.3.Complex:
It is a combination of real and imaginary part.
Example:
2+5j
a+bi

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
1. Strings
2. Lists
3. Tuples
2.4.Strings:
 String is defined as a continues set of characters represented in quotation marks
(either single quotes ( ‘ ) or double quotes ( “ ).
 An individual character in a string is accessed using a subscript (index).
 The subscript should always be an integer (positive or negative).
 A subscript starts from 0 to n-1.
 Strings are immutable i.e. the contents of the string cannot be changed after it is
created.
 Python will get the input at run time by default as a string.

4 Unit 2: Data ,expressions, Statements by C.Vijayalakshmi, AP, CSE


 Python does not support character data type. A string of size 1 can be treated as
characters.
1. single quotes (' ')
2. double quotes (" ")
3. triple quotes(“”” “”””)

Operations on string:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Member ship

>>>a=”HELLO”  Positive indexing helps in accessing


indexing >>>print(a[0]) the string from the beginning
>>>H  Negative subscript helps in accessing
>>>print(a[-1]) the string from the end.
>>>O
Print[0:4] – HELL The Slice[n : m] operator extracts sub
Slicing: Print[ :3] – HEL string from the strings.
Print[0: ]- HELLO A segment of a string is called a slice.

a=”save” The + operator joins the text on both


Concatenation b=”earth” sides of the operator.
print(a+b)
saveearth

a=”panimalar ” The * operator repeats the string on the


Repetitions: print(3*a) left hand side times the value on right
panimalarpanimalar hand side.
panimalar

Membership: >>> s="good morning" Using membership operators to check a


>>>"m" in s particular character is in string or not.
True Returns true if present
>>> "a" not in s
True

5 Unit 2: Data ,expressions, Statements by C.Vijayalakshmi, AP, CSE


2.5 Lists
 List is an ordered sequence of items. Values in the list are called elements / items.
 It can be written as a list of comma-separated items (values) between square
brackets[ ].
 Items in the lists can be of different data types.

Operations on list:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
create a list >>> a=[2,3,4,5,6,7,8,9,10] in this way we can create a
>>> print(a) list at compile time
[2, 3, 4, 5, 6, 7, 8, 9, 10]
Indexing >>> print(a[0]) Accessing the item in the
2 position 0
>>> print(a[8]) Accessing the item in the
10 position 8
>>> print(a[-1]) Accessing a last element
10 using negative indexing.
Slicing >>> print(a[0:3])
[2, 3, 4]
>>> print(a[0:]) printing a part of the string.
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> print(a[:8])
[2, 3, 4, 5, 6, 7, 8, 9]
>>>b=[20,30] Adding and printing the
Concatenation >>> print(a+b) items of two lists.
[2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30]
>>> print(b*3) Create a multiple copies of
Repetition [20, 30, 20, 30, 20, 30] the same string
>>> print(a[2])
4 Updating the list using
Updating the list >>> a[2]=100 index value
>>> print(a)
[2, 3, 100, 5, 6, 7, 8, 9, 10]
Inserting an >>> a. insert(0,"apple") Inserting an element in 0th
element >>> print(a) position
a=[“apple”,2,3,4,5,6,7,8,9,10]
Removing an >>> a. remove(“apple”) Removing an element by
element >>> print(a) giving the element directly
a=[2,3,4,5,6,7,8,9,10]

6 Unit 2: Data ,expressions, Statements by C.Vijayalakshmi, AP, CSE


2.6.Tuple:
 A tuple is same as list, except that the set of elements is enclosed in parentheses
instead of square brackets.
 A 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.
Operations on Tuples:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
Creating the tuple with
Creating a tuple >>>a=(20,40,60,”apple”,”ball”) elements of different data
types.
>>>print(a[0]) Accessing the item in the
Indexing 20 position 0
>>> a[2] Accessing the item in the
60 position 2
Slicing >>>print(a[1:3]) Displaying items from 1st
(40,60) till 2nd.
Concatenation >>> b=(2,4) Adding tuple elements at
>>>print(a+b) the end of another tuple
>>>(20,40,60,”apple”,”ball”,2,4) elements
Repetition >>>print(b*2) repeating the tuple in n no
>>>(2,4,2,4) of times
updating a tuple >>>a[2]=100 Altering the tuple data type
Type Error: 'tuple' object does not leads to error.
support item assignment
2.7. Boolean:
 Boolean data type have two values either it can take 0 or 1.
 0 means False
 1 means True
 True and False is a keyword.

Example:
>>> 3==5
False
>>> True+True
2
>>> False+True
1
>>> False*True
0

7 Unit 2: Data ,expressions, Statements by C.Vijayalakshmi, AP, CSE


2.8.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. 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 key-
value-pairs
 Dictionaries don't support the sequence operation of the sequence data types like
strings, tuples and lists.

Creating a a={'name':"abi",'age':18,'mark':100} Creating the dictionary with


dictionary print(a) elements of different data
{'name': 'abi', 'age': 18, 'mark': 100} types.
Indexing print(a['name']) Accessing the item with keys.
abi

2.9.Sets:
 Set is an unordered collection of values of any data type with no duplicate entry.
 In set every element is unique.
 Elements are separated by”,” enclosed with { }

Example:
a={1,2,3,4,5,6,7,6,7}
print(a)
a={1,2,3,4,5,6,7}

3.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.

Assigning values to variables:


= sign used to assign values to a variables.

Example:
a=5 // single assignment
a,b,c=2,3,4 // multiple assignment
a=b=c=2 //assigning one value to multiple variables

8 Unit 2: Data ,expressions, Statements by C.Vijayalakshmi, AP, CSE


4.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.

5.IDENTIFIERS:
 Identifier is the name given to entities like class, functions, variables etc. in
Python.
 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 (_).
 all are valid example.
 An identifier cannot start with a digit.
 Keywords cannot be used as identifiers.
 Cannot use special symbols like !, @, #, $, % etc. in our identifier.
 Identifier can be of any length.

Valid identifiers Invalid identifiers


num Number 1
Num num 1
Num1 addition of program
_NUM 1Num
NUM_temp2 Num.no
IF if
Else else

6. 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.
There are two types of statements available
1. single line statements
2. multi line statements

9 Unit 2: Data ,expressions, Statements by C.Vijayalakshmi, AP, CSE


Single line statements:
single line statements are end with newline
Examples:
a=1
b=2
c=a+b

Multiline statements:
python allows the user to write multi line statement using line continuation character
(\) to denote that the line should continue.

Example:
total=mark1+\
mark2+\
mark3
7.INPUT AND OUTPUT
INPUT:
 Input is a data entered by user in the program.
 In python, input () function is available for input.

Syntax:
variable = input (“data”)

Example:
a=input("enter the name:")

How to get different data type from user:


Data type Compile time Run time
int a=10 a=int(input(“enter a”))
float a=10.5 a=float(input(“enter a”))
string a=”panimalar” a=input(“enter a string”)
list a=[20,30,40,50] a=list(input(“enter a list”))
tuple a=(20,30,40,50) a=tuple(input(“enter a tuple”))

OUTPUT:
 Output can be displayed to the user using Print statement.
Syntax:
print (expression/constant/variable)

Example:
print ("Hello") // Hello
print(5) //5
print(3+5) //8
Print(c)

10 Unit 2: Data ,expressions, Statements by C.Vijayalakshmi, AP, CSE


8.COMMENTS:
 Comments are used to provide more details about the program like name of the
program, author of the program, date and time, etc.
Types of comments:
1. single line comments
2. multi line comments

Single line comments


 A hash sign (#) is the beginning of a comment.
 Anything written after # in a line is ignored by interpreter.
Example:
Percentage = (minute * 100) / 60 # calculating percentage of an hour

Multi line comments:


 Multiple line comments can be written using triple quotes “”” ……….”””

Example:
“”” This program is created by Robert
in Dell lab on 12/12/12
based on newtons method”””

9.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.

Example:
a=3
b=1
if a>b:
print("a is greater")
else:
print("b is greater")

10.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.

11 Unit 2: Data ,expressions, Statements by C.Vijayalakshmi, AP, CSE


(a,b,c)=(3,4,5)
(a, b, c, d) = (1, 2, 3)
ValueError: need more than 3 values to unpack
Swapping two numbers using tuple
(a, b) = (b, a)

11.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

Types of Operators:
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators

Arithmetic operators:
They are used to perform mathematical operations like addition, subtraction,
multiplication etc.
Operator Description Example
a=10,b=20

+ Addition Adds values on either side of the operator. a + b = 30

- Subtraction Subtracts right hand operand from left hand a – b = -10


operand.

* Multiplication Multiplies values on either side of the operator a * b = 200

/ Division Divides left hand operand by right hand operand b/a=2

% Modulus Divides left hand operand by right hand operand b % a = 0


and returns remainder

** Exponent Performs exponential (power) calculation on a**b =10 to the


operators power 20

// Floor Division - The division of operands where the 5//2=2


result is the quotient in which the digits after the
decimal point are removed

12 Unit 2: Data ,expressions, Statements by C.Vijayalakshmi, AP, CSE


Comparison (Relational) Operators:
Comparison operators are used to compare values.
It either returns True or False according to the condition.
Operator Description Example
a=10,b=20

== If the values of two operands are equal, then the condition (a == b) is


becomes true. not true.

!= If values of two operands are not equal, then condition


(a!=b) is true
becomes true.

> If the value of left operand is greater than the value of right (a > b) is
operand, then condition becomes true. not true.

< If the value of left operand is less than the value of right (a < b) is
operand, then condition becomes true. true.

>= If the value of left operand is greater than or equal to the (a >= b) is
value of right operand, then condition becomes true. not true.

<= If the value of left operand is less than or equal to the value (a <= b) is
of right operand, then condition becomes true. true.

Assignment Operators:
Assignment operators are used in Python to assign values to variables.
Operator Description Example

= Assigns values from right side operands to left c = a + b


side operand assigns value
of a + b into c

+= Add AND It adds right operand to the left operand and c += a is


assign the result to left operand equivalent to c
=c+a

-= Subtract AND It subtracts right operand from the left operand c -= a is


and assign the result to left operand equivalent to c
=c-a

*= Multiply AND It multiplies right operand with the left operand c *= a is


and assign the result to left operand equivalent to c
=c*a

/= Divide AND It divides left operand with the right operand c /= a is


and assign the result to left operand equivalent to c

13 Unit 2: Data ,expressions, Statements by C.Vijayalakshmi, AP, CSE


= c / ac /= a is
equivalent to c
=c/a

%= Modulus AND It takes modulus using two operands and assign c %= a is


the result to left operand equivalent to c
=c%a

**= Exponent Performs exponential (power) calculation on c **= a is


AND operators and assign value to the left operand equivalent to c
= c ** a

//= Floor It performs floor division on operators and c //= a is


Division assign value to the left operand equivalent to c
= c // a

Logical Operators:
Logical operators are and, or, not operators.

Bitwise Operators:
Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)

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.

14 Unit 2: Data ,expressions, Statements by C.Vijayalakshmi, AP, CSE


Example:
x=[5,3,6,4,1]
>>> 5 in x
True
>>> 5 not in x
False

Identity Operators:
They are used to check if two values (or variables) are located on the same part of the
memory.

Example
x=5
y=5
a = 'Hello'
b = 'Hello'
print(x is not y) // False
print(a is b)//True

Operator Precedence:
When an expression contains more than one operator, the order of evaluation
depends on the order of operations.
Operator Description

** Exponentiation (raise to the power)

~+- Complement, unary plus and minus (method


names for the last two are +@ and -@)

* / % // Multiply, divide, modulo and floor division

+- Addition and subtraction

>> << Right and left bitwise shift

& Bitwise 'AND'

15 Unit 2: Data ,expressions, Statements by C.Vijayalakshmi, AP, CSE


^| Bitwise exclusive `OR' and regular `OR'

<= < > >= Comparison operators

<> == != Equality operators

= %= /= //= -= += *= **= Assignment operators

is is not Identity operators

in not in Membership operators

not or and Logical operators

12.Expressions:

 An expression is a combination of values, variables, and operators.


 A value all by itself is considered an expression, and also a variable.
 So the following are all legal expressions:

>>> 42
42
>>> a=2
>>> a+3+2
7
>>> z=("hi"+"friend")
>>> print(z)
hifriend

a=9-12/3+3*2-1 A=2*3+4%5-3/2+6
a=? A=6+4%5-3/2+6 find m=?
a=9-4+3*2-1 A=6+4-3/2+6 m=-43||8&&0||-2
a=9-4+6-1 A=6+4-1+6 m=-43||0||-2
a=5+6-1 A=10-1+6 m=1||-2
a=11-1 A=9+6 m=1
a=10 A=15
a=2,b=12,c=1 a=2*3+4%5-3//2+6
d=a<b>c a=2,b=12,c=1 a=6+4-1+6
d=2<12>1 d=a<b>c-1 a=10-1+6
d=1>1 d=2<12>1-1 a=15
d=0 d=2<12>0
d=1>0
d=1

16 Unit 2: Data ,expressions, Statements by C.Vijayalakshmi, AP, CSE


13.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.
TYPES OF FUNCTION:
1. Built in function
2. user defined function
13.1.BUILT IN FUNCTION
 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.
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

17 Unit 2: Data ,expressions, Statements by C.Vijayalakshmi, AP, CSE


>>>input("enter ur name: ") # reads and returns the given string
enter ur name : George

13.2.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:
 The programmer can write their own functions which are known as user defined
function. These functions can create by using def keyword.
Example:
add(), sub()

ELEMENTS OF USER DEFINED FUNCTIONS


There are two elements in user defined function.
1. function definition
2. function call
13.3.FUNCTION DEFINITION
A function definition specifies the name of a new function and the sequence of
statements that execute when the function is called.
Syntax:

 def is a keyword that indicates that this is a function definition.


 The rules for function names are the same as for variable names
 The first line of the function definition is called the header; the rest is called body
of function.
 The header has to end with a colon and the body has to be indented. The function
contains any number of statements.
 parameter list contains list of values used inside the function.

example:
def add():
a=eval(input(“enter a value”))
b=eval(input(“enter a value”))
c=a+b
print(c)

18 Unit 2: Data ,expressions, Statements by C.Vijayalakshmi, AP, CSE


Function call()

 A function is called by using the function name followed by parenthesis().


 Argument is a list of values provided to the function when the function is called
 The statements inside the function does not executed until the function is called.
 Function can be called n number of times

Syntax:
Function name(argument list)
Example:
add()

13.4.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.

14.FUNCTION PROTOTYPES:
Based on arguments and return type functions are classified into 4 types.
1. Function without arguments and without return type
2. Function with arguments and without return type
3. Function without arguments and with return type
4. Function with arguments and with return type

1. 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

2. Function with arguments and without return type


Arguments are passed through the function call but output is not return to the
main function

3. 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.

4. 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

19 Unit 2: Data ,expressions, Statements by C.Vijayalakshmi, AP, CSE


without return type
Without argument With argument
def add(): def add(a,b):
a=int(input("enter a")) c=a+b
b=int(input("enter b")) print(c)
c=a+b a=int(input("enter a"))
print(c) b=int(input("enter b"))
add() add(a,b)
OUTPUT: OUTPUT:
enter a 5 enter a 5
enter b 10 enter b 10
15 15

with return type


Without argument With argument
def add(): def add(a,b):
a=int(input("enter a")) c=a+b
b=int(input("enter b")) return c
c=a+b a=int(input("enter a"))
return c b=int(input("enter b"))
c=add() c=add(a,b)
print(c) print(c)

OUTPUT: OUTPUT:
enter a 5 enter a 5
enter b 10 enter b 10
15 15

15.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 add(a,b):
Arguments :
 Arguments are the value(s) provided in function call 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: add(a,b)

20 Unit 2: Data ,expressions, Statements by C.Vijayalakshmi, AP, CSE


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: Example:

def add(a,b):
c=a+b
return variable return c
x=5
y=4
c=add(a,b)
print(c)

16.ARGUMENTS TYPES:
You can call a function by using the following types of formal arguments:
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
Required Arguments:
The number of arguments in the function call should match exactly with the function
definition.
Example Output:
def student( name, roll ): George
print(name,roll) 98
student("george",98)
def student( name, roll ): 101
print(name,roll) rithika
student(101,”rithika”)
def student( name, roll ): student() missing 1 required positional
print(name,roll) argument: 'name'
student(101)
def student( name, roll ): student() missing 2 required positional
print(name,roll) arguments: 'roll' and 'name'
student()

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.

Example Output:
def student( name, roll,mark): bala
print(name,roll,mark) 102
student (mark=90,roll=102,name="bala") 90

21 Unit 2: Data ,expressions, Statements by C.Vijayalakshmi, AP, CSE


def student( name, roll,mark): bala
print(name,roll,mark) 102
student (name="bala", roll=102,mark=90) 90

Default Arguments:
Assumes a default value if a value is not provided in the function call for that argument.
It allows us to miss one or more arguments or place out of order in function call.

Example Output:
def student( name="raja", roll=101,mark=50): bala 102 90
print(name,roll,mark)
student (mark=90,roll=102,name="bala")
def student( name="raja", roll=101,mark=50): bala 102 50
print(name,roll,mark)
student (name="bala", roll=102)
def student( name="raja", roll=101,mark=50): raja 101 50
print(name,roll,mark)
student ()

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.

Example Output:
def student( name,*mark): bala (90,)
print(name,mark)
student (“bala”,90)

def student( name, roll,*mark): raja 90 (70, 80)


print(name,roll,mark)
student ("raja",90,70,80)

17.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.
Two ways to import your module:
1. import keyword
2. form keyword

22 Unit 2: Data ,expressions, Statements by C.Vijayalakshmi, AP, CSE


import keyword
 import keyword is used to get all functions from the module.
 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)

Importing builtin module: importing user defined module:

import math import cal


x=math.sqrt(25) x=cal.add(5,4)
print(x) print(x)

from keyword:
from keyword is used to get only particular function from the module.

Syntax:
from module_name import function_name

Importing builtin module: Importing user defined module:

frommath importsqrt fromcal importadd


x=sqrt(25) x=add(5,4)
print(x) print(x)

1.math-mathematical module
math functions description
math.ceil(x) Return the ceiling of x, the smallest integer greater than or equal
to x
math.floor(x) Return the floor of x, the largest integer less than or equal to x.
math.factorial(x) Return x factorial
math.sqrt(x) Return the square root of x

math.log(x) return the natural logarithm of x

math.log10(x) returns the base-10 logarithms


math.log2(x) Return the base-2 logarithm of
math.sin(x) returns sin of x radians
math.cos(x) returns cosine of x radians

23 Unit 2: Data ,expressions, Statements by C.Vijayalakshmi, AP, CSE


math.tan(x) returns tangent of x radians

math.pi The mathematical constant π = 3.141592

math.gcd(x,y) the greatest common divisor of the integers x and y


math.e returns The mathematical constant e = 2.718281

2 .random-Generate pseudo-random numbers


random function description
random.randrange(stop) return random numbers from 0
random.randrange(start, stop[, step]) return the random numbers in a range
random.uniform(a, b) Return a random floating point number

ILLUSTRATIVE PROGRAMS
SWAPPING Output
a = int(input("Enter a value ")) Enter a value 5
b = int(input("Enter b value ")) Enter b value 8
c=a a=8
a=b b=5
b=c
print("a=",a,"b=",b,)

Program to find distance between two Output


points
import math enter x1 7
x1=int(input("enter x1")) enter y1 6
y1=int(input("enter y1")) enter x2 5
x2=int(input("enter x2")) enter y2 7
y2=int(input("enter y2")) 2.5
distance =math.sqrt((x2-x1)**2)+((y2-
y1)**2)
print(distance)

Program to circulate n numbers Output:

a=list(input("enter the list")) enter the list '1234'


print(a) ['1', '2', '3', '4']
for i in range(1,len(a),1): ['2', '3', '4', '1']
print(a[i:]+a[:i]) ['3', '4', '1', '2']
['4', '1', '2', '3']

24 Unit 2: Data ,expressions, Statements by C.Vijayalakshmi, AP, CSE


PART A
1. What is interpreter?
2. What are the two modes of python?
3. List the features of python.
4. List the applications of python
5. List the difference between interactive and script mode
6. What is value in python?
7. What is identifier? and list the rules to name identifier.
8. What is keyword?
9. How to get data types in compile time and runtime?
10. What is indexing and types of indexing?
11. List out the operations on strings.
12. Explain slicing?
13. Explain below operations with the example
(i)Concatenation (ii)Repetition
14. Give the difference between list and tuple
15. Differentiate Membership and Identity operators.
16. Compose the importance of indentation in python.
17. Evaluate the expression and find the result
(a+b)*c/d
a+b*c/d
18. Write a python program to print ‘n’ numbers.
19. Define function and its uses
20. Give the various data types in Python
21. Assess a program to assign and access variables.
22. Select and assign how an input operation was done in python.
23. Discover the difference between logical and bitwise operator.
24. Give the reserved words in Python.
25. Give the operator precedence in python.
26. Point out the uses of default arguments in python
27. Generalize the uses of python module.
28. Demonstrate how a function calls another function. Justify your answer.
29. List the syntax for function call with and without arguments.
30. What are the two parts of function definition? give the syntax.
31. Point out the difference between recursive and iterative technique.
34. Give the syntax for variable length arguments.

25 Unit 2: Data ,expressions, Statements by C.Vijayalakshmi, AP, CSE


Part B
1. Explain in detail about various data types in Python with an example?
2. Explain the different types of operators in python with an example.
3. Discuss the need and importance of function in python.
4. Explain in details about function prototypes in python.
5. Discuss about the various type of arguments in python.
6. Explain the flow of execution in user defined function with example.
7. Illustrate a program to display different data types using variables and literal
constants.
8. Show how an input and output function is performed in python with an example.
9. Explain in detail about the various operators in python with suitable examples.
10. Discuss the difference between tuples and list
11. Discuss the various operation that can be performed on a tuple and Lists
(minimum 5)with an example program
12. What is membership and identity operators.
13. Write a program to perform addition, subtraction, multiplication, integer
division, floor division and modulo division on two integer and float.
14. Write a program to convert degree Fahrenheit to Celsius
15. Discuss the need and importance of function in python.
16. Illustrate a program to exchange the value of two variables with temporary
variables
17. Briefly discuss in detail about function prototyping in python. With suitable
example program
18. Analyze the difference between local and global variables.
19. Explain with an example program to circulate the values of n variables
20. Analyze with a program to find out the distance between two points using
python.
21. Do the Case study and perform the following operation in tuples i) Maxima
minima iii)sum of two tuples iv) duplicate a tuple v)slicing operator vi) obtaining
a list from a tuple vii) Compare two tuples viii)printing two tuples of different
data types
22. Write a program to find out the square root of two numbers

26 Unit 2: Data ,expressions, Statements by C.Vijayalakshmi, AP, CSE

You might also like