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

Unit Ii Data, Expressions, Statements 9

The document summarizes key concepts in Python including values and types, variables, expressions, statements, functions, modules, and arguments. It discusses integers, floats, booleans, strings, and lists as basic data types in Python. It also defines variables as names that refer to values, expressions as combinations of values and operators, statements as instructions that perform actions, and functions as named sequences of statements that perform a computation. Modules are described as files that contain related functions. The document provides examples of built-in functions and the different types of arguments a function can take.

Uploaded by

Peter Parker
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

Unit Ii Data, Expressions, Statements 9

The document summarizes key concepts in Python including values and types, variables, expressions, statements, functions, modules, and arguments. It discusses integers, floats, booleans, strings, and lists as basic data types in Python. It also defines variables as names that refer to values, expressions as combinations of values and operators, statements as instructions that perform actions, and functions as named sequences of statements that perform a computation. Modules are described as files that contain related functions. The document provides examples of built-in functions and the different types of arguments a function can take.

Uploaded by

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

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

1.Define values and types

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

Here n is a variable name. The value of that variable is 176.


ST

3.Define Boolean Operators.

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

A string is a sequence of characters. We can access the character one at a time.

>>> fruit=’banana’
>>> letter = fruit[0]

>>> print letter

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

[10,20,30,40] number List

[‘a’,’b’,’c’,’d’]-> Character List

M
O
[‘a’,20,5,25.5,[20,30]]-> Nested List C
S.
[]-> Empty List
U
C

6.What do you mean by mutable list.


FO

The values in the list are changed . So it is called mutable list.


TS

>>> n=[17,35]
EN
D

>>> n[0]=5
U
ST

>>>n=[5,35]-> n[0] is changed as 5.

7. Define Expression

An expression is a combination of values , variables and operators. A value all by itself is


considered an expression.

8. Define Tuples

A Tuple is a sequence of values. The values can be of any type, They are indexed by integers.

Tuples are immutable. A tuple is a comma separated list of values.

>>> t=(‘a’,’b’,’c’)

9. What is the function of slice in tuple?

It prints the values from starting to end-1.

>>> t[1:3]
>>(‘a’,’b’)

10. Write a program for swapping of two numbers?

a=5

b=6

a,b=b,a

print (a,b)

11. What are different Membership Operators in python?

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

A module is a file that contains a collection of related functions.


ST

>>> import math

>>> print math

< module ‘math’ (built-in)>

14.What are the different types of arguments?

1.Function arguments

2.keyword arguments

3.Default arguments

4.variable length arguments.

PART-B (16 marks)


1. Define Operators. What are the different types of Operators in python? Explain in
detail.

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

Python language supports the following types of operators.

 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

Operator Description Example


FO

Adds values on either side of the


+ Addition a + b = 30
operator.
TS

Subtracts right hand operand from left


- Subtraction a – b = -10
EN

hand operand.
D

* Multiplies values on either side of the


a * b = 200
U

Multiplication operator
ST

Divides left hand operand by right


/ Division b/a=2
hand operand
Divides left hand operand by right
% Modulus b%a=0
hand operand and returns remainder
Performs exponential (power)
** Exponent a**b =10 to the power 20
calculation on operators
Floor Division - The division of
operands where the result is the
quotient in which the digits after the
9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4,
// decimal point are removed. But if one
-11.0//3 = -4.0
of the operands is negative, the result
is floored, i.e., rounded away from
zero (towards negative infinity):

Python Comparison Operators

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 −

Operator Description Example


If the values of two operands are equal,
== (a == b) is not true.
then the condition becomes true.
If values of two operands are not equal,
!=
then condition becomes true.
If the value of left operand is greater
> than the value of right operand, then (a > b) is not true.
condition becomes true.
If the value of left operand is less than
< the value of right operand, then (a < b) is true.
condition becomes true.
If the value of left operand is greater
>= than or equal to the value of right (a >= b) is not true.
operand, then condition becomes true.
If the value of left operand is less than

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

Assume variable a holds 10 and variable b holds 20, then −


FO

Operator Description Example


TS

Assigns values from right side operands


EN

= c = a + b assigns value of a + b into c


to left side operand
D

+= Add It adds right operand to the left operand


c += a is equivalent to c = c + a
U

AND and assign the result to left operand


ST

-= It subtracts right operand from the left


Subtract operand and assign the result to left c -= a is equivalent to c = c - a
AND operand
*= It multiplies right operand with the left
Multiply operand and assign the result to left c *= a is equivalent to c = c * a
AND operand
It divides left operand with the right
/= Divide c /= a is equivalent to c = c / ac /= a is
operand and assign the result to left
AND equivalent to c = c / a
operand
%=
It takes modulus using two operands
Modulus c %= a is equivalent to c = c % a
and assign the result to left operand
AND
**= Performs exponential (power)
Exponent calculation on operators and assign c **= a is equivalent to c = c ** a
AND value to the left operand
//= Floor It performs floor division on operators
c //= a is equivalent to c = c // a
Division and assign value to the left operand
Python Bitwise Operators

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&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a = 1100 0011

M
There are following Bitwise operators supported by Python language

O
C
S.
Operator Description Example
U

& Binary Operator copies a bit to the result if it


(a & b) (means 0000 1100)
C

AND exists in both operands


FO

It copies a bit if it exists in either


| Binary OR (a | b) = 61 (means 0011 1101)
operand.
TS

^ Binary It copies the bit if it is set in one


(a ^ b) = 49 (means 0011 0001)
EN

XOR operand but not both.


~ Binary (~a ) = -61 (means 1100 0011 in 2's
D

It is unary and has the effect of


U

Ones complement form due to a signed


'flipping' bits.
ST

Complement binary number.


The left operands value is moved left
<< Binary
by the number of bits specified by the a << = 240 (means 1111 0000)
Left Shift
right operand.
The left operands value is moved right
>> Binary
by the number of bits specified by the a >> = 15 (means 0000 1111)
Right Shift
right operand.

Python Logical Operators

There are following logical operators supported by Python language. Assume variable a holds
10 and variable b holds 20 then

Used to reverse the logical state of its operand.

Python Membership Operators


Python’s membership operators test for membership in a sequence, such as strings, lists, or
tuples. There are two membership operators as explained below

Operator Description Example


Evaluates to true if it finds a variable in
x in y, here in results in a 1 if x is a
in the specified sequence and false
member of sequence y.
otherwise.
Evaluates to true if it does not finds a
x not in y, here not in results in a 1 if x is
not in variable in the specified sequence and
not a member of sequence y.
false otherwise.

Python Identity Operators

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

Evaluates to false if the variables on


x is not y, here is not results in 1 if id(x)
FO

is not either side of the operator point to the


is not equal to id(y).
same object and true otherwise.
TS
EN

Python Operators Precedence


D

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

1. Define function?.What are the different types of arguments in python

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

def functionname( parameters ):


FO

"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

order that they were defined.


U
ST

Example

The following function takes a string as input parameter and prints it on standard screen.

def printme( str ):


"This prints a passed string into this function"
print str
return

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;

printme("I'm first call to user defined function!")


printme("Again second call to the same function")

I'm first call to user defined function!


Again second call to the same function

Pass by reference vs value

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

Values inside the function: [10, 20, 30, [1, 2, 3, 4]]


Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
D
U
ST

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.

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print str
return;
printme()

When the above code is executed, it produces the following result:

Traceback (most recent call last):


File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)

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

def printme( str ):


C

"This prints a passed string into this function"


FO

print str
TS

return;
EN

# Now you can call printme function


printme( str = "My string")
D

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.

def printinfo( name, age = 35 ):


"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;

printinfo( age=50, name="miki" )


printinfo( name="miki" )
Name: miki
Age 50
Name: miki
Age 35
Variable-length arguments

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.

Syntax for a function with non-keyword variable arguments is this −

def functionname([formal_args,] *var_args_tuple ):


"function_docstring"
function_suite
return [expression]

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 −

# Function definition is here

M
def printinfo( arg1, *vartuple ):

O
"This prints a variable passed arguments" C
print "Output is: "
S.
print arg1
U

for var in vartuple:


C

print var
FO

return;
TS

# Now you can call printinfo function


EN

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 ("Addition", sum(5,6))

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]

3. Swapping of two variables

def swap(a,b):
print("Values before swapping", a,b)

a,b=b,a

print("Values after swapping", a,b)

swap(4,5)

Output:

Values before swapping 4 5

Values after swapping 5 4

4. Distance between two points

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

Distance between two points


EN

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=input("Enter the input value of n")

n=int(n)

print("Sum of n numbers", sum(n))

Output:

Enter the input value of n 10


Sum of n numbers 45

6. Sum of odd and even numbers

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

print("Sum of n numbers", sumofevenodd(n))


TS

Output:
EN

Enter the input value of n 10


D

Sum of n numbers (20, 25)


U
ST

7. Variable Length arguments

def sum(farg,*args):

s=0

for i in args:

s=s+i

print ("Sum of three numbers",s)

sum(1,4,5,6)

Output:

Sum of three numbers 15

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

You might also like