0% found this document useful (0 votes)
1 views

Python_Unit1

Uploaded by

hishore.r
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Python_Unit1

Uploaded by

hishore.r
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

 Facebook, Drop box

UNIT II
DATA, EXPRESSIONS, STATEMENTS 1.3. Python interpreter:
Python interpreter and interactive mode; values and types: int, float, boolean, string, Interpreter: To execute a program in a high-level language by translating it one line at
and list; variables, expressions, statements, tuple assignment, precedence of operators, a time.
comments; Modules and functions, function definition and use, flow of execution, Compiler: To translate a program written in a high-level language into a low-level
parameters and arguments; Illustrative programs: exchange the values of two language all at once, in preparation for later execution.
variables, circulate the values of n variables, distance between two points.
Compiler Interpreter
1. INTRODUCTION TO PYTHON: Interpreter Takes Single instruction as
Python is a general-purpose interpreted, interactive, object-oriented, and high- Compiler Takes Entire program as input
input
level programming language. No Intermediate Object Code
It was created by Guido van Rossum during 1985- 1990. Intermediate Object Code is Generated
is Generated
Python got its name from “Monty Python’s flying circus”. Python was released in the Conditional Control Statements are Conditional Control Statements are
year 2000. Executes faster Executes slower
 Python is interpreted: Python is processed at runtime by the interpreter. You Memory Requirement is More(Since Object
do not need to compile your program before executing it. Memory Requirement is Less
Code is Generated)
 Python is Interactive: You can actually sit at a Python prompt and interact with Every time higher level program is
the interpreter directly to write your programs. Program need not be compiled every time
converted into lower level program
 Python is Object-Oriented: Python supports Object-Oriented style or technique Errors are displayed after entire Errors are displayed for every
of programming that encapsulates code within objects. program is checked instruction interpreted (if any)
 Python is a Beginner's Language: Python is a great language for the beginner- Example : C Compiler Example : PYTHON
level programmers and supports the development of a wide range of
applications. 1.4 MODES OF PYTHON INTERPRETER:
1.1. Python Features: Python Interpreter is a program that reads and executes Python code. It uses 2 modes
 Easy-to-learn: Python is clearly defined and easily readable. The structure of Execution.
of the program is very simple. It uses few keywords. 1. Interactive mode
 Easy-to-maintain: Python's source code is fairly easy-to-maintain. 2. Script mode
 Portable: Python can run on a wide variety of hardware platforms and has the Interactive mode:
same interface on all platforms.  Interactive Mode, as the name suggests, allows us to interact with OS.
 Interpreted: Python is processed at runtime by the interpreter. So, there is no  When we type Python statement, interpreter displays the result(s)
need to compile a program before executing it. You can simply run the program. immediately.
 Extensible: Programmers can embed python within their C,C++,Java script Advantages:
,ActiveX, etc.  Python, in interactive mode, is good enough to learn, experiment or explore.
 Free and Open Source: Anyone can freely distribute it, read the source code, and  Working in interactive mode is convenient for beginners and for testing small
edit it. pieces of code.
 High Level Language: When writing programs, programmers concentrate on Drawback:
solutions of the current problem, no need to worry about the low level details.  We cannot save the statements and have to retype all the statements once again to
 Scalable: Python provides a better structure and support for large programs re-run them.
than shell scripting. In interactive mode, you type Python programs and the interpreter displays the result:
1.2. Applications: >>> 1 + 1
 Bit Torrent file sharing 2
 Google search engine, Youtube The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready for you
 Intel, Cisco, HP, IBM to enter code. If you type 1 + 1, the interpreter replies 2.
 i–Robot >>> print ('Hello, World!')
 NASA Hello, World!

1 Unit 2: Data ,expressions, Statements 2 Unit 2: Data ,expressions, Statements


This is an example of a print statement. It displays a result on the screen. In this case,  Auto completion with smart indentation.
the result is the words.  Python shell to display output with syntax highlighting.

2.VALUES AND DATA TYPES

Value:
Value can be any letter ,number or string.
Eg, 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.
Python has four standard data types:

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.1Numbers:
 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,
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
2.2 Sequence:
comes with optional part of the Python packaging.
 A sequence is an ordered collection of items, indexed by positive integers.
Features of IDLE:
 It is a combination of mutable (value can be changed) and immutable (values
 Multi-window text editor with syntax highlighting.
cannot be changed) data types.

3 Unit 2: Data ,expressions, Statements 4 Unit 2: Data ,expressions, Statements


 There are three types of sequence data type available in Python, they are Slice operator is >>> print(s[:4]) - Displaying items from 1st
1. Strings used to extract Good position till 3rd .
2. Lists part of a data
3. Tuples type
2.2.1 Strings: Concatenation >>>print(s+"friends") -Adding and printing the
 A String in Python consists of a series or sequence of characters - letters, good morningfriends characters of two strings.
numbers, and special characters.
 Strings are marked by quotes: Repetition >>>print(s*2) Creates new strings,
 single quotes (' ') Eg, 'This a string in single quotes' good morninggood concatenating multiple copies of
 double quotes (" ") Eg, "'This a string in double quotes'" morning the same string
 triple quotes(""" """) Eg, This is a paragraph. It is made up of in, not in >>> s="good morning" Using membership operators to
multiple lines and sentences.""" (membership >>>"m" in s check a particular character is in
 Individual character in a string is accessed using a subscript (index). operator) True string or not. Returns true if
 Characters can be accessed using indexing and slicing operations >>> "a" not in s present.
Strings are immutable i.e. the contents of the string cannot be changed after it is True
created.
Indexing: 2.2.2 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:
Indexing
Slicing
Concatenation
 Positive indexing helps in accessing the string from the beginning Repetitions
 Negative subscript helps in accessing the string from the end. Updation, Insertion, Deletion
 Subscript 0 or –ve n(where n is length of the string) displays the first element.
Example: A[0] or A[-5] will display “H” Creating a list >>>list1=["python", 7.79, 101, Creating the list with
 Subscript 1 or –ve (n-1) displays the second element. "hello”] elements of different data
Example: A[1] or A[-4] will display “E” >>>list2=["god",6.78,9] types.
Operations on string: Indexing >>>print(list1[0])  Accessing the item in
i. Indexing python the position 0
ii. Slicing >>> list1[2]  Accessing the item in
iii. Concatenation 101
iv. Repetitions the position 2
v. Member ship Slicing( ending >>> print(list1[1:3]) - Displaying items from 1st
Creating a string >>> s="good morning" Creating the list with elements of position -1) [7.79, 101] till 2nd.
different data types. Slice operator is >>>print(list1[1:]) - Displaying items from 1st
Indexing >>> print(s[2])  Accessing the item in the used to extract [7.79, 101, 'hello'] position till last.
o position 0 part of a string, or
>>> print(s[6])  Accessing the item in the some part of a list
O position 2 Python
Slicing( ending >>> print(s[2:]) - Displaying items from 2nd till Concatenation >>>print( list1+list2) -Adding and printing the
position -1) od morning last. ['python', 7.79, 101, 'hello', 'god', items of two lists.

5 Unit 2: Data ,expressions, Statements 6 Unit 2: Data ,expressions, Statements


6.78, 9] >>> t[0]="a"
Repetition >>> list2*3 Creates new strings, Trace back (most recent call last):
['god', 6.78, 9, 'god', 6.78, 9, 'god', concatenating multiple File "<stdin>", line 1, in <module>
6.78, 9] copies of the same string Type Error: 'tuple' object does not support item assignment
Updating the list >>> list1[2]=45 Updating the list using index
>>>print( list1) value 2.3 Mapping
[‘python’, 7.79, 45, ‘hello’] -This data type is unordered and mutable.
Inserting an >>> list1.insert(2,"program") Inserting an element in 2nd -Dictionaries fall under Mappings.
element >>> print(list1) position 2.3.1Dictionaries:
['python', 7.79, 'program', 45,  Lists are ordered sets of objects, whereas dictionaries are unordered sets.
'hello']  Dictionary is created by using curly brackets. i,e. {}
Removing an >>> list1.remove(45) Removing an element by  Dictionaries are accessed via keys and not via their position.
element >>> print(list1) giving the element directly  A dictionary is an associative array (also known as hashes). Any key of the
['python', 7.79, 'program', 'hello'] dictionary is associated (or mapped) to a value.
 The values of a dictionary can be any Python data type. So dictionaries are
2.2.4Tuple: unordered key-value-pairs(The association of a key and a value is called a key-
 A tuple is same as list, except that the set of elements is enclosed in parentheses value pair )
instead of square brackets. Dictionaries don't support the sequence operation of the sequence data types like
 A tuple is an immutable list. i.e. once a tuple has been created, you can't add strings, tuples and lists.
elements to a tuple or remove elements from the tuple.
 Benefit of Tuple: Creating a >>> food = {"ham":"yes", "egg" : Creating the dictionary with
 Tuples are faster than lists. dictionary "yes", "rate":450 } elements of different data
 If the user wants to protect the data from accidental changes, tuple can be used. >>>print(food) types.
 Tuples can be used as keys in dictionaries, while lists can't. {'rate': 450, 'egg': 'yes', 'ham':
'yes'}
Basic Operations: Indexing >>>> print(food["rate"]) Accessing the item with keys.
Creating a tuple >>>t=("python", 7.79, 101, Creating the tuple with elements 450
"hello”) of different data types. Slicing( ending >>>print(t[1:3]) Displaying items from 1st till
Indexing >>>print(t[0])  Accessing the item in the position -1) (7.79, 101) 2nd.
python position 0
>>> t[2]  Accessing the item in the
101 If you try to access a key which doesn't exist, you will get an error message:
position 2
>>> words = {"house" : "Haus", "cat":"Katze"}
Slicing( ending >>>print(t[1:3])  Displaying items from 1st >>> words["car"]
position -1) (7.79, 101) till 2nd. Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Concatenation >>> t+("ram", 67)  Adding tuple elements at KeyError: 'car'
('python', 7.79, 101, 'hello', 'ram', the end of another tuple
67) elements Data type Compile time Run time
Repetition >>>print(t*2)  Creates new strings, int a=10 a=int(input(“enter a”))
('python', 7.79, 101, 'hello', concatenating multiple copies of float a=10.5 a=float(input(“enter a”))
'python', 7.79, 101, 'hello') string a=”panimalar” a=input(“enter a string”)
the same 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”))
Altering the tuple data type leads to error. Following error occurs when user tries to
do.

7 Unit 2: Data ,expressions, Statements 8 Unit 2: Data ,expressions, Statements


3.Variables,Keywords Expressions, Statements, Comments, Docstring ,Lines And  all are valid example.
Indentation, Quotation In Python, Tuple Assignment:  An identifier cannot start with a digit.
 Keywords cannot be used as identifiers.
3.1VARIABLES:  Cannot use special symbols like !, @, #, $, % etc. in our identifier.
 A variable allows us to store a value by assigning it to a name, which can be used  Identifier can be of any length.
later. Example:
 Named memory locations to store values. Names like myClass, var_1, and this_is_a_long_variable
 Programmers generally choose names for their variables that are meaningful.
 It can be of any length. No space is allowed. Valid declarations Invalid declarations
 We don't need to declare a variable before using it. In Python, we simply assign a Num Number 1
value to a variable and it will exist. Num num 1
Num1 addition of program
Assigning value to variable: _NUM 1Num
Value should be given on the right side of assignment operator(=) and variable on left NUM_temp2 Num.no
side. IF if
>>>counter =45 Else else
print(counter)
3.4 STATEMENTS AND EXPRESSIONS:
Assigning a single value to several variables simultaneously: 3.4.1 Statements:
-Instructions that a Python interpreter can executes are called statements.
>>> a=b=c=100 -A statement is a unit of code like creating a variable or displaying a value.
Assigning multiple values to multiple variables: >>> n = 17
>>> print(n)
>>> a,b,c=2,4,"ram" 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.
3.4.2Expressions:
3.2KEYWORDS:
-An expression is a combination of values, variables, and operators.
 Keywords are the reserved words in Python.
- A value all by itself is considered an expression, and also a variable.
 We cannot use a keyword as variable name, function name or any other
- So the following are all legal expressions:
identifier.
>>> 42
 They are used to define the syntax and structure of the Python language.
42
 Keywords are case sensitive.
>>> a=2
>>> a+3+2
7
>>> z=("hi"+"friend")
>>> print(z)
hifriend

3.5 INPUT AND OUTPUT

INPUT: Input is data entered by user (end user) in the program.


3.3IDENTIFIERS: In python, input () function is available for input.
Identifier is the name given to entities like class, functions, variables etc. in Syntax for input() is:
Python. variable = input (“data”)
 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 (_).

9 Unit 2: Data ,expressions, Statements 10 Unit 2: Data ,expressions, Statements


Example: Example:
>>> x=input("enter the name:") a=3
enter the name: george b=1
>>>y=int(input("enter the number")) if a>b:
enter the number 3 print("a is greater")
#python accepts string as default data type. conversion is required for type. else:
print("b is greater")
OUTPUT: Output can be displayed to the user using Print statement .
Syntax: 3.9 QUOTATION IN PYTHON:
print (expression/constant/variable) Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals.
Example: Anything that is represented using quotations are considered as string.
>>> print ("Hello")
 single quotes (' ') Eg, 'This a string in single quotes'
Hello
 double quotes (" ") Eg, "'This a string in double quotes'"
 triple quotes(""" """) Eg, This is a paragraph. It is made up of multiple lines
3.6 COMMENTS: and sentences."""
 A hash sign (#) is the beginning of a comment.
 Anything written after # in a line is ignored by interpreter. 3.10 TUPLE ASSIGNMENT
Eg:percentage = (minute * 100) / 60 # calculating percentage of an hour
 Python does not have multiple-line commenting feature. You have to  An assignment to all of the elements in a tuple using a single assignment
comment each line individually as follows : statement.
Example:  Python has a very powerful tuple assignment feature that allows a tuple of
# This is a comment. variables on the left of an assignment to be assigned values from a tuple on the
# This is a comment, too. right of the assignment.
# I said that already.  The left side is a tuple of variables; the right side is a tuple of values.
 Each value is assigned to its respective variable.
3.7 DOCSTRING:  All the expressions on the right side are evaluated before any of the assignments.
 Docstring is short for documentation string. This feature makes tuple assignment quite versatile.
 It is a string that occurs as the first statement in a module, function, class, or  Naturally, the number of variables on the left and the number of values on the
method definition. We must write what a function/class does in the docstring. right have to be the same.
 Triple quotes are used while writing docstrings. >>> (a, b, c, d) = (1, 2, 3)
Syntax: ValueError: need more than 3 values to unpack
functionname__doc.__
Example: Example:
def double(num): -It is useful to swap the values of two variables. With conventional assignment
"""Function to double the value""" statements, we have to use a temporary variable. For example, to swap a and b:
return 2*num
>>> print(double.__doc__) Swap two numbers Output:
Function to double the value a=2;b=3
print(a,b) (2, 3)
3.8 LINES AND INDENTATION: temp = a (3, 2)
 Most of the programming languages like C, C++, Java use braces { } to define a a=b >>>
block of code. But, python uses indentation. b = temp
 Blocks of code are denoted by line indentation. print(a,b)
 It is a space given to the block of codes for class and function definitions or flow
control. 12 Unit 2: Data ,expressions, Statements

11 Unit 2: Data ,expressions, Statements


-Tuple assignment solves this problem neatly: 4.1 Arithmetic operators:
They are used to perform mathematical operations like addition, subtraction,
(a, b) = (b, a) multiplication etc. Assume, a=10 and b=5

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


Operator Description Example
In tuple packing, the values on the left are ‘packed’ together in a tuple:
+ Addition Adds values on either side of the operator. a + b = 30
>>> b = ("George", 25, "20000") # tuple packing
- Subtraction Subtracts right hand operand from left hand a – b = -10
-In tuple unpacking, the values in a tuple on the right are ‘unpacked’ into the operand.
variables/names on the right:
* Multiplies values on either side of the operator a * b = 200
>>> b = ("George", 25, "20000") # tuple packing Multiplication
>>> (name, age, salary) = b # tuple unpacking
>>> name / Division Divides left hand operand by right hand operand b/a=2
'George'
>>> age % Modulus Divides left hand operand by right hand operand b%a=0
25 and returns remainder
>>> salary
'20000' ** Exponent Performs exponential (power) calculation on a**b =10 to the
operators power 20
-The right side can be any kind of sequence (string,list,tuple)
Example: // Floor Division - The division of operands where the 5//2=2
-To split an email address in to user name and a domain result is the quotient in which the digits after the
decimal point are removed
>>> mailid='god@abc.org'
>>> name,domain=mailid.split('@')
>>> print name Examples Output:
god a=10 a+b= 15
>>> print (domain) b=5 a-b= 5
abc.org print("a+b=",a+b) a*b= 50
print("a-b=",a-b) a/b= 2.0
4.OPERATORS: print("a*b=",a*b) a%b= 0
 Operators are the constructs which can manipulate the value of operands. print("a/b=",a/b) a//b= 2
 Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is print("a%b=",a%b) a**b= 100000
called operator print("a//b=",a//b)
 Types of Operators: print("a**b=",a**b)
-Python language supports the following types of operators
 Arithmetic Operators 4.2 Comparison (Relational) Operators:
 Comparison (Relational) Operators  Comparison operators are used to compare values.
 Assignment Operators  It either returns True or False according to the condition. Assume, a=10 and b=5
 Logical Operators
 Bitwise Operators Operator Description Example
 Membership Operators
 Identity Operators == If the values of two operands are equal, then the condition (a == b) is
13 Unit 2: Data ,expressions, Statements 14 Unit 2: Data ,expressions, Statements
becomes true. not true. *= Multiply It multiplies right operand with the left operand and c *= a is
AND assign the result to left operand equivalent
!= If values of two operands are not equal, then condition (a!=b) is to c = c * a
becomes true. true
/= Divide It divides left operand with the right operand and c /= a is
> If the value of left operand is greater than the value of right (a > b) is AND assign the result to left operand equivalent
operand, then condition becomes true. not true. to c = c / ac
/= a is
< If the value of left operand is less than the value of right (a < b) is equivalent
operand, then condition becomes true. true. to c = c / a
>= If the value of left operand is greater than or equal to the (a >= b) is %= Modulus It takes modulus using two operands and assign the c %= a is
value of right operand, then condition becomes true. not true. AND result to left operand equivalent
to c = c % a
<= 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. **= Exponent Performs exponential (power) calculation on c **= a is
AND operators and assign value to the left operand equivalent
Example to c = c ** a
a=10 Output:
b=5 a>b=> True //= Floor It performs floor division on operators and assign c //= a is
print("a>b=>",a>b) a>b=> False Division value to the left operand equivalent
print("a>b=>",a<b) a==b=> False to c = c // a
print("a==b=>",a==b) a!=b=> True
print("a!=b=>",a!=b) a>=b=> False Example Output
print("a>=b=>",a<=b) a>=b=> True a = 21 Line 1 - Value of c is 31
print("a>=b=>",a>=b) b = 10 Line 2 - Value of c is 52
c=0 Line 3 - Value of c is 1092
4.3 Assignment Operators: c=a+b Line 4 - Value of c is 52.0
-Assignment operators are used in Python to assign values to variables. print("Line 1 - Value of c is ", c) Line 5 - Value of c is 2
Operator Description Example c += a Line 6 - Value of c is 2097152
print("Line 2 - Value of c is ", c) Line 7 - Value of c is 99864
= Assigns values from right side operands to left side c = a + b c *= a
operand assigns print("Line 3 - Value of c is ", c)
value of a + c /= a
b into c print("Line 4 - Value of c is ", c)
c =2
+= Add AND It adds right operand to the left operand and assign c += a is c %= a
the result to left operand equivalent print("Line 5 - Value of c is ", c)
to c = c + a c **= a
print("Line 6 - Value of c is ", c)
-= Subtract It subtracts right operand from the left operand and c -= a is c //= a
AND assign the result to left operand equivalent print("Line 7 - Value of c is ", c)
to c = c - a

15 Unit 2: Data ,expressions, Statements 16 Unit 2: Data ,expressions, Statements


4.4 Logical Operators: print "Line 4 - Value of c is ", c
-Logical operators are the and, or, not operators. c = a << 2; # 240 = 1111 0000
print "Line 5 - Value of c is ", c
c = a >> 2; # 15 = 0000 1111
print "Line 6 - Value of c is ", c

4.6 Membership Operators:

 Evaluates to find a value or a variable is in the specified sequence of string, list,


Example Output tuple, dictionary or not.
a = True x and y is False  Let, x=[5,3,6,4,1]. To check particular item in list or not, in and not in operators
b = False x or y is True are used.
print('a and b is',a and b) not x is False
print('a or b is',a or b)
print('not a is',not a)

4.5 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 Example:
y = 4 (0000 0100 in binary) x=[5,3,6,4,1]
>>> 5 in x
True
>>> 5 not in x
False

4.7 Identity Operators:


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

Example Output
a = 60 # 60 = 0011 1100 Line 1 - Value of c is 12
b = 13 # 13 = 0000 1101 Line 2 - Value of c is 61
c=0 Line 3 - Value of c is 49
c = a & b; # 12 = 0000 1100 Line 4 - Value of c is -61 Example
print "Line 1 - Value of c is ", c Line 5 - Value of c is 240 x=5 Output
c = a | b; # 61 = 0011 1101 Line 6 - Value of c is 15 y=5 False
print "Line 2 - Value of c is ", c x2 = 'Hello' True
c = a ^ b; # 49 = 0011 0001 y2 = 'Hello'
print "Line 3 - Value of c is ", c print(x1 is not y1)
c = ~a; # -61 = 1100 0011 print(x2 is y2)
17 Unit 2: Data ,expressions, Statements 18 Unit 2: Data ,expressions, Statements
5.OPERATOR PRECEDENCE: Example:
When an expression contains more than one operator, the order of evaluation a=9-12/3+3*2-1 A=2*3+4%5-3/2+6
depends on the order of operations. 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
Operator Description 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
** Exponentiation (raise to the power)
a=11-1 A=9+6 m=1
~+- Complement, unary plus and minus (method a=10 A=15
names for the last two are +@ and -@)
a=2,b=12,c=1 a=2*3+4%5-3//2+6
* / % // Multiply, divide, modulo and floor division 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
+- Addition and subtraction d=1>1 d=2<12>1-1 a=15
d=0 d=2<12>0
>> << Right and left bitwise shift d=1>0
d=1
& Bitwise 'AND'

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


6.Functions, Function Definition And Use, Function call, Flow Of Execution,
<= < > >= Comparison operators Function Prototypes, Parameters And Arguments, Return statement,
Argumentstypes,Modules
<> == != Equality operators
6.1 FUNCTIONS:
= %= /= //= -= += *= **= Assignment operators  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
is is not Identity operators blocks called function.
Need For Function:
in not in Membership operators
 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
not or and Logical operators
as function.
-For mathematical operators, Python follows mathematical convention.  Debugging, Testing and maintenance becomes easy when the program is divided
-The acronym PEMDAS (Parentheses, Exponentiation, Multiplication, Division, into subprograms.
Addition, Subtraction) is a useful way to remember the rules:  Functions are used to avoid rewriting same code again and again in a program.
 Parentheses have the highest precedence and can be used to force an expression  Function provides code re-usability
to evaluate in the order you want. Since expressions in parentheses are evaluated  The length of the program is reduced.
first, 2 * (3-1)is 4, and (1+1)**(5-2) is 8. Types of function:
 You can also use parentheses to make an expression easier to read, as in (minute Functions can be classified into two categories:
* 100) / 60, even if it doesn’t change the result. i) user defined function
 Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27, and 2 ii) Built in function
*3**2 is 18, not 36. i) Built in functions
 Multiplication and Division have higher precedence than Addition and  Built in functions are the functions that are already created and stored in python.
Subtraction. So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.  These built in functions are always available for usage and accessed by a
 Operators with the same precedence are evaluated from left to right (except programmer. It cannot be modified.
exponentiation). Built in function Description
19 Unit 2: Data ,expressions, Statements 20 Unit 2: Data ,expressions, Statements
>>>max(3,4) # returns largest element Syntax:
4 def fun_name(Parameter1,Parameter2…Parameter n):
>>>min(3,4) # returns smallest element statement1
3 statement2…
>>>len("hello") #returns length of an object statement n
5 return[expression]
>>>range(2,8,1) #returns range of given values Example:
[2, 3, 4, 5, 6, 7] def my_add(a,b):
>>>round(7.8) #returns rounded integer of the given number c=a+b
8.0 return c
>>>chr(5) #returns a character (a string) from an integer
\x05' 6.3Function Calling: (Main Function)
>>>float(5) #returns float number from string or integer  Once we have defined a function, we can call it from another function, program or
5.0 even the Python prompt.
>>>int(5.0) # returns integer from string or float  To call a function we simply type the function name with appropriate
5 arguments.
>>>pow(3,5) #returns power of given number Example:
243 x=5
>>>type( 5.6) #returns data type of object to which it belongs y=4
<type 'float'> my_add(x,y)
>>>t=tuple([4,6.0,7]) # to create tuple of items from list
(4, 6.0, 7) 6.4 Flow of Execution:
>>>print("good morning") # displays the given object
Good morning 
The order in which statements are executed is called the flow of execution
>>>input("enter name: ") # reads and returns the given string 
Execution always begins at the first statement of the program.
enter name : George 
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
ii)User Defined Functions: remember that statements inside the function are not executed until the function
 User defined functions are the functions that programmers create for their is called.
requirement and use.  Function calls are like a bypass in the flow of execution. Instead of going to the
 These functions can then be combined to form module which can be used in next statement, the flow jumps to the first line of the called function, executes all
other programs by importing them. the statements there, and then comes back to pick up where it left off.
 Advantages of user defined functions: Note: When you read a program, don’t read from top to bottom. Instead, follow the flow
 Programmers working on large project can divide the workload by making of execution. This means that you will read the def statements as you are scanning from
different functions. top to bottom, but you should skip the statements of the function definition until you
 If repeated code occurs in a program, function can be used to include those reach a point where that function is called.
codes and execute when needed by calling that function.
6.2 Function definition: (Sub program) 6.5 Function Prototypes:
 def keyword is used to define a function.
 Give the function name after def keyword followed by parentheses in which i. Function without arguments and without return type
arguments are given. ii. Function with arguments and without return type
 End with colon (:) iii. Function without arguments and with return type
 Inside the function add the program statements to be executed iv. Function with arguments and with return type
 End with or without return statement
21 Unit 2: Data ,expressions, Statements 22 Unit 2: Data ,expressions, Statements
6.6 Parameters And Arguments:
i) Function without arguments and without return type Parameters:
o In this type no argument is passed through the function call and no output  Parameters are the value(s) provided in the parenthesis when we write function
is return to main function header.
o The sub function will read the input values perform the operation and print  These are the values required by function to work.
the result in the same block  If there is more than one value required, all of them will be listed in parameter
ii) Function with arguments and without return type list separated by comma.
o Arguments are passed through the function call but output is not return to  Example: def my_add(a,b):
the main function Arguments :
iii) Function without arguments and with return type
 Arguments are the value(s) provided in function call/invoke statement.
o In this type no argument is passed through the function call but output is
 List of arguments should be supplied in same way as parameters are listed.
return to the main function.
 Bounding of parameters to arguments is done 1:1, and so there should be same
iv) Function with arguments and with return type
number and type of arguments as mentioned in parameter list.
o In this type arguments are passed through the function call and output is
return to the main function  Example: my_add(x,y)
Without Return Type 6.7 RETURN STATEMENT:
Without argument With argument  The return statement is used to exit a function and go back to the place from
where it was called.
def add(): def add(a,b):  If the return statement has no arguments, then it will not return any values. But
a=int(input("enter a")) c=a+b exits from function.
b=int(input("enter b")) print(c) Syntax:
c=a+b a=int(input("enter a"))
return[expression]
print(c) b=int(input("enter b"))
add() add(a,b)
Example:
OUTPUT: OUTPUT: def my_add(a,b):
enter a 5 enter a 5 c=a+b
enter b 10 enter b 10
return c
15 15
x=5
y=4
print(my_add(x,y))
With return type Output:
Without argument With argument 9
def add(): def add(a,b): 6.8 ARGUMENTS TYPES:
a=int(input("enter a")) c=a+b 1. Required Arguments
b=int(input("enter b")) return c 2. Keyword Arguments
c=a+b a=int(input("enter a")) 3. Default Arguments
return c b=int(input("enter b")) 4. Variable length Arguments
c=add() c=add(a,b)  Required Arguments: The number of arguments in the function call should
print(c) print(c) match exactly with the function definition.
def my_details( name, age ):
OUTPUT: OUTPUT: print("Name: ", name)
enter a 5 enter a 5 print("Age ", age)
enter b 10 enter b 10 return
15 15 my_details("george",56)

23 Unit 2: Data ,expressions, Statements 24 Unit 2: Data ,expressions, Statements


Output:  Once we import a module, we can reference or use to any of its functions or
Name: george variables in our code.
Age 56 o There is large number of standard modules also available in python.
 Keyword Arguments: o Standard modules can be imported the same way as we import our user-
Python interpreter is able to use the keywords provided to match the values with defined modules.
parameters even though if they are arranged in out of order. o Every module contains many function.
o To access one of the function , you have to specify the name of the module and
def my_details( name, age ): the name of the function separated by dot . This format is called dot
print("Name: ", name) notation.
print("Age ", age) Syntax:
return import module_name
my_details(age=56,name="george") module_name.function_name(variable)
Output: Importing Builtin Module: Importing User Defined Module:
Name: george import math import cal
Age 56 x=math.sqrt(25) x=cal.add(5,4)
print(x) print(x)
 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

6.9 MODULES:
 A module is a file containing Python definitions ,functions, statements and
instructions. Built-in python modules are,
 Standard library of Python is extended as modules. 1.math – mathematical functions:
 To use these modules in a program, programmer needs to import the some of the functions in math module is,
module. math.ceil(x) - Return the ceiling of x, the smallest integer greater
25 Unit 2: Data ,expressions, Statements 26 Unit 2: Data ,expressions, Statements
than or equal to x print(a) ['1', '2', '3', '4']
math.floor(x) - Return the floor of x, the largest integer less than or for i in range(1,len(a),1): ['2', '3', '4', '1']
equal to x. print(a[i:]+a[:i]) ['3', '4', '1', '2']
math.factorial(x) -Return x factorial. math.gcd(x,y)- Return the ['4', '1', '2', '3']
greatest common divisor of the integers a and b
math.sqrt(x)- Return the square root of x
math.log(x)- return the natural logarithm of x Part A:
math.log10(x) – returns the base-10 logarithms 1. What is interpreter?
math.log2(x) - Return the base-2 logarithm of x. 2. What are the two modes of python?
math.sin(x) – returns sin of x radians 3. List the features of python.
math.cos(x)- returns cosine of x radians 4. List the applications of python
math.tan(x)-returns tangent of x radians 5. List the difference between interactive and script mode
math.pi - The mathematical constant π = 3.141592 6. What is value in python?
math.e – returns The mathematical constant e = 2.718281 7. What is identifier? and list the rules to name identifier.
8. What is keyword?
2 .random-Generate pseudo-random numbers 9. How to get data types in compile time and runtime?
random.randrange(stop) 10. What is indexing and types of indexing?
random.randrange(start, stop[, step]) 11. List out the operations on strings.
random.uniform(a, b) 12. Explain slicing?
-Return a random floating point number 13. Explain below operations with the example
(i)Concatenation (ii)Repetition
ILLUSTRATIVE PROGRAMS 14. Give the difference between list and tuple
Program for SWAPPING(Exchanging )of Output 15. Differentiate Membership and Identity operators.
values 16. Compose the importance of indentation in python.
a = int(input("Enter a value ")) Enter a value 5 17. Evaluate the expression and find the result
b = int(input("Enter b value ")) Enter b value 8 (a+b)*c/d
c=a a=8 a+b*c/d
a=b b=5 18. Write a python program to print ‘n’ numbers.
b=c 19. Define function and its uses
print("a=",a,"b=",b,) 20. Give the various data types in Python
21. Assess a program to assign and access variables.
Program to find distance between two Output 22. Select and assign how an input operation was done in python.
points 23. Discover the difference between logical and bitwise operator.
import math enter x1 7 24. Give the reserved words in Python.
x1=int(input("enter x1")) enter y1 6 25. Give the operator precedence in python.
y1=int(input("enter y1")) enter x2 5 26. Define the scope and lifetime of a variable in python.
x2=int(input("enter x2")) enter y2 7 27. Point out the uses of default arguments in python
y2=int(input("enter y2")) 2.5 28. Generalize the uses of python module.
distance =math.sqrt((x2-x1)**2)+((y2- 29. Demonstrate how a function calls another function. Justify your answer.
y1)**2) 30. List the syntax for function call with and without arguments.
print(distance) 31. Define recursive function.
32. What are the two parts of function definition? give the syntax.
Program to circulate n numbers Output: 33. Point out the difference between recursive and iterative technique.
a=list(input("enter the list")) enter the list '1234' 34. Give the syntax for variable length arguments.

27 Unit 2: Data ,expressions, Statements 28 Unit 2: Data ,expressions, Statements


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.

29 Unit 2: Data ,expressions, Statements

You might also like