Unit Ii Data, Expressions, Statements 9
Unit Ii Data, Expressions, Statements 9
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.
Unit-II
Two Marks
A value is one of the basic things ina programs like a letter or a number. The values are
belonging to different types. For example
>>> type(‘Hello’)
<type ‘str’>
>>> type(17)
M
<type ‘float’>
O
C
S.
2. Define variables.
U
C
A variable is a name that refers to a value. They can contain both letters and numbers but
FO
they do not begin with a letter. The underscore ‘_’ can appear in a name.
TS
Example:
EN
>>> n=176
D
U
A Boolean expression is an expression that is either true (or) false. The Operator == which
compares two operands and produces True if they are equal otherwise it is false.
>>> 5==5
True
>>> 5==6
False
4. Define String
>>> fruit=’banana’
>>> letter = fruit[0]
Output:
5.Define List.
A List is a sequence of values. The values are characters in a list they can be of any type. The
values in a list are called elements.
Examples
M
O
[‘a’,20,5,25.5,[20,30]]-> Nested List C
S.
[]-> Empty List
U
C
>>> n=[17,35]
EN
D
>>> n[0]=5
U
ST
7. Define Expression
8. Define Tuples
A Tuple is a sequence of values. The values can be of any type, They are indexed by integers.
>>> t=(‘a’,’b’,’c’)
>>> t[1:3]
>>(‘a’,’b’)
a=5
b=6
a,b=b,a
print (a,b)
In – Evaluates to true, if it finds a variable in the specified sequence and false otherwise.
Not in- Evaluates to true, if it does not finds a variable in the specified sequence and false
otherwise.
12.Define Functions
M
O
A function is a named sequence of statements that performs a computation. A function takes
C
an argument and returns a result. The result is called the return value.
S.
U
Example
C
FO
def print_1():
TS
print (“welcome”)
EN
13.Define Module
D
U
1.Function arguments
2.keyword arguments
3.Default arguments
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 Operator
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
M
Python Arithmetic Operators
O
C
Assume variable a holds 10 and variable b holds 20, then −
S.
U
C
hand operand.
D
Multiplication operator
ST
These operators compare the values on either sides of them and decide the relation among
them. They are also called Relational operators.
Assume variable a holds 10 and variable b holds 20, then −
M
<= or equal to the value of right operand, (a <= b) is true.
O
then condition becomes true.
C
S.
Python Assignment Operators
U
C
Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b =
13; Now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
~a = 1100 0011
M
There are following Bitwise operators supported by Python language
O
C
S.
Operator Description Example
U
There are following logical operators supported by Python language. Assume variable a holds
10 and variable b holds 20 then
Identity operators compare the memory locations of two objects. There are two Identity
operators explained below:
M
Operator Description Example
O
Evaluates to true if the variables on C
x is y, here is results in 1 if id(x) equals
is either side of the operator point to the
S.
id(y).
same object and false otherwise.
U
C
The following table lists all operators from highest precedence to lowest.
U
ST
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'
^| 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
A function is a block of organized, reusable code that is used to perform a single, related
action. Functions provide better modularity for application and a high degree of code reusing.
Defining a Function
Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
Any input parameters or arguments should be placed within these parentheses. You
can also define parameters inside these parentheses.
The first statement of a function can be an optional statement - the documentation
string of the function or docstring.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as return
M
None.
O
C
S.
Syntax
U
C
"function_docstring"
function_suite
TS
return [expression]
EN
By default, parameters have a positional behavior and you need to inform them in the same
D
Example
The following function takes a string as input parameter and prints it on standard screen.
Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be included in
the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from
another function or directly from the Python prompt. Following is the example to call
printme() function −
#!/usr/bin/python
def printme( str ):
"This prints a passed string into this function"
print str
return;
All parameters (arguments) in the Python language are passed by reference. It means if you
change what a parameter refers to within a function, the change also reflects back in the
calling function. For example −
M
def changeme( mylist ):
O
"This changes a passed list into this function" C
mylist.append([1,2,3,4]);
S.
print "Values inside the function: ", mylist
U
return
C
FO
mylist = [10,20,30];
TS
changeme( mylist );
print "Values outside the function: ", mylist
EN
Function Arguments
You can call a function by using the following types of formal arguments:
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
Required arguments
Required arguments are the arguments passed to a function in correct positional order. Here,
the number of arguments in the function call should match exactly with the function
definition.
Keyword arguments
Keyword arguments are related to the function calls. When you use keyword arguments in a
function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter
is able to use the keywords provided to match the values with parameters. You can also make
keyword calls to the printme() function in the following ways −
M
O
#!/usr/bin/python C
S.
# Function definition is here
U
print str
TS
return;
EN
My string
U
ST
Default arguments
A default argument is an argument that assumes a default value if a value is not provided in
the function call for that argument.
You may need to process a function for more arguments than you specified while defining
the function. These arguments are called variable-length arguments and are not named in the
function definition, unlike required and default arguments.
An asterisk (*) is placed before the variable name that holds the values of all nonkeyword
variable arguments. This tuple remains empty if no additional arguments are specified during
the function call. Following is a simple example −
M
def printinfo( arg1, *vartuple ):
O
"This prints a variable passed arguments" C
print "Output is: "
S.
print arg1
U
print var
FO
return;
TS
printinfo( 10 )
printinfo( 70, 60, 50 )
D
Output is:
U
ST
10
Output is:
70
60
50
1.Simple Calculator Program
def sum(a,b):
return a+b
def sub(a,b):
return a-b
def mul(a,b):
return a*b
def div(a,b):
return(a//b)
print ("Subtraction",sub(8,4))
print ("Multiplication",mul(8,4))
print ("Division",div(8,2))
Output:
Addition 11
Subtraction 4
Multiplication 32
Division 4
M
2.Circulate n values in a List
O
def rotate(l,y=1): C
S.
U
if(len(l)==0):
C
FO
return 1
TS
y=y%len(l)
EN
return l[y:]+l[:y]
D
print(rotate([1,2,3,4]))
U
ST
print(rotate([2,3,4,1]))
print(rotate([3,4,1,2]))
print(rotate([3,2,1,4]))
Output:
[2, 3, 4, 1]
[3, 4, 1, 2]
[4, 1, 2, 3]
[2, 1, 4, 3]
def swap(a,b):
print("Values before swapping", a,b)
a,b=b,a
swap(4,5)
Output:
import math
p1 = [4, 0]
M
p2 = [6, 6]
O
C
distance = math.sqrt( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2) )
S.
U
print(distance)
C
FO
Output:
TS
6.324555320336759
D
5.Sum of n numbers
U
ST
def sum(n):
s=0
for i in range(1,n):
s=s+i
return s
n=int(n)
Output:
def sumofevenodd(n):
se=0
so=0
for i in range(1,n):
if i%2==0:
se=se+i
else:
so=so+i
M
return se,so
O
n=input("Enter the input value of n") C
S.
U
n=int(n)
C
FO
Output:
EN
def sum(farg,*args):
s=0
for i in args:
s=s+i
sum(1,4,5,6)
Output:
def someFunction(**kwargs):
if 'text' in kwargs:
print (kwargs['text'])
someFunction(text='welcome')
Output:
Welcome
9. Keyword arguments
def print_info(name,age=25):
print ("Name:",name)
print("Age",age)
print_info(name='Uma',age=35)
M
print_info(name='Reka')
O
Output: C
S.
U
Name: Uma
C
FO
Age 35
TS
Name: Reka
EN
Age 25
D
U
ST