Sie sind auf Seite 1von 46

GE 8151- PROBLEM SOLVING & PYTHON PROGRAMMING

UNIT 2 – DATA , EXPRESSIONS , STATEMENTS

2.1 Python Interpreter and Interactive Mode

2.2 Values and Types

Integer , Float, String , List

Variables, Expressions

Statements , Tuple Assignment

Precedence of operators

Comments

2.3 Modules and Functions`

Function definition and use

Flow of execution

Parameters and arguments

2.4 Illustrative Examples

Exchange the values of two variables

Circulate the values of n variables

Distance between two points

MZCET A.SANGEETHA
1
PYTHON

Python is a
 General-purpose
 Interpreted
 Powerful
 High-level
 Interactive
 Object-oriented programming language
It was created by Guido van Rosseum

FEATURES OF PYTHON PROGRAMMING

• Simple
• free and open-source
• Portability
• Extensible and Embeddable
• A high-level, interpreted language
• Large standard libraries
• Object-oriented
• Databases
• GUI Programming

APPLICATIONS OF PYTHON:

 Single Board Computer : Raspberry pi, Beagle Bone

 Web Development : Google app engine, Yahoo Maps, Yahoo Groups,


Zope corporation, Django, Pyramid

 Software Development: RedHat, NOKIA


MZCET A.SANGEETHA
2
 Business software : IBM

 Government : Central Intelligence Agency-USA

 Game : Battle field, Crystal space

 Graphics : Industrial Light and Music (MUMMY RETURNS), Walt Disney


feature Animation, Blender 3D

 Financial : Atlis Investment Management, Bellco credit union

 Science : NASA, Biosoft, National weather service

 Electronic design automation: Ciranova

 Testing : Honeywell, HP

PROBLEM SOLVING:

 Problem solving means the


 ability to formulate problems,
 think creatively about solutions and
 express a solution clearly and accurately.

PROGRAMMING LANGUAGE:
• High-level language
• A programming language like Python that is designed to be easy or
humans to read and write.
• Low-level languages
• A programming language that is designed to be easy or a computer
to execute.
• Also called MACHINE LANGUAGE or ASSEMBLY LANGUAGE.

MZCET A.SANGEETHA
3
ADVANTAGES OF HIGH-LEVEL LANGUAGE:
• Easier to program.
• High-level languages are portable ie., meaning that they can run on different
kinds of computers with few or no modifications.

TWO KINDS OF PROGRAMS PROCESS HIGH-LEVEL LANGUAGES INTO LOW-


LEVEL LANGUAGES:
• Interpreters
• An interpreter reads a high-level program and executes it.
• It execute line by line.
• Compilers
• A compiler reads the program and translates it completely before the
program starts running.
• High-level program is called the source code
• Translated program is called the object code or the executable.
COMPILER

 A compiler reads the program and translates it completely before the


program starts running.

 Source code is the High-level program


 Translated program is called the object code or the executable.
PYTHON INTERPRETER:

MZCET A.SANGEETHA
4
 An Interpreter is a program that read and execute the codes line by line.
 Python is an interpreted language because Python programs are executed
by an interpreter.
TWO WAYS TO USE THE INTERPRETER INTERACTIVE MODE / MODES OF
PROGRAMMING:

• Interactive mode
• Script mode
INTERACTIVE MODE

 Type Python programs and the interpreter displays the result

>>> 1 + 1

 The chevron, >>> is the prompt the interpreter uses to indicate that it is
ready

SCRIPT MODE
• Code is stored in a file and use the interpreter to execute the contents of
the file is called a SCRIPT.
• Python scripts have names that end with .py
• To execute / run the script in Windows
• Press 5 or Goto Run menu and press Run Module
• To execute / run the script in UNIX
• Type python filename.py
• Ex. python abc.py

PROGRAM:
• A program is a sequence of instructions that specifies how to perform a
computation.

MZCET A.SANGEETHA
5
INPUT:
• Get data rom the keyboard, a file, or some other device.

OUTPUT:
• Display data on the screen or send data to a file or other device.

DEBUGGING:

BUG:

An error in the program.

DEBUGGING:

The process of finding and removing the programming error is called


debugging.
TYPES OF ERROR:
 Syntax errors
 Runtime errors
 Semantic errors
SYNTAX:
The structure of a program and the rules about that structure.
SYNTAX ERROR:
An error in a program that makes it impossible to parse / interpret
EXCEPTION:
An error that is detected while the program is running.
SEMANTICS:
The meaning of a program.
SEMANTIC ERROR:
An error in a program that makes it do something other than what the
programmer intended.

MZCET A.SANGEETHA
6
PYTHON PROGRAM SAMPLE:

OUTPUT:
PROGRAM:
Hello World
print “Hello World”
'Hello, World!
print('Hello, World!')

VARIABLE

 Variables are reserved memory locations to OUTPUT:


PROGRAM:
store values 18 18
 A variable is a name that refers to a value. x = 12

 Values may be numbers, text or more y = 18


complicated types
x=y
 Declaration of variable is not required in
python y=x

 It happens automatically when a value is print(x,y)


assigned to a variable

• A variable is a name that refers to a value.


• An assignment statement creates new variables and gives them values

>>> message = ‘ANY WORDS'


>>> n = 17
>>> pi = 3.1415926535897931
VARIABLE NAME

• Variables names must start with a letter or an underscore

_a
a
a_
MZCET A.SANGEETHA
7
• Variable name may consist of letters, numbers and underscores.

password1
a12b
un_der_scores
• Names are case sensitive.

abc , ABC , aBc


KEYWORDS:
• The interpreter uses keywords to recognize the structure o the program.
• Keyword cannot be used as variable names.
• Python has 31 keywords
and del rom not while
as elif Global or with
assert else If pass yield
break except Import print
class exec In raise
continue finally Is return
def or Lambda try
STATEMENTS
• A statement is a unit of code that the Python interpreter can execute.
• A script contains a sequence of statements

Ex., OUTPUT
print 1 1 2
x=2
print x
ASSIGNMENT STATEMENTS:
PROGRAM – SINGLE ASSIGNMENT: OUTPUT:
a = 12
a = 12 b=4
b=4
print (“a = “,a)
Print (“b = “,b)

MZCET A.SANGEETHA
8
PROGRAM – MULTIPLE ASSIGNMENT: OUTPUT:
a,b = 12,4 a = 12
print("a = ",a) b=4
print("b = ",b)
PROGRAM- SWAP 2 VALUES USING TEMPORARY VARIABLE : OUTPUT:
a = 12 a=4
b=4
b = 12
t=a
a=b
b=t
print("a = ",a)
print("b = ",b)

PROGRAM- SWAP 2 VALUES WITHOUT USING TEMPORARY OUTPUT:


VARIABLE: a=4
a = 12 b = 12
b=4
a,b = b,a
print("a = ",a)
print("b = ",b)

OPERATORS AND OPERANDS:


• Operators are special symbols that represent computations like addition
and multiplication.
• The values the operator is applied to are called operands.
• The operators +, -, *, / and ** perform addition, subtraction,
multiplication, division and exponentiation.
• ex
x+y–c
num ** 2

MZCET A.SANGEETHA
9
EXPRESSIONS
• An expression is a combination of values, variables, and operators.

ex.

Avg = a + b + c

ORDER OF OPERATION / HIERARCHY OF OPERATORS / PRECEDENCE OF


OPERATION :
• When more than one operator appears in an expression, the order of
evaluation depends on the rules of precedence.

PEMDAS

P Parenthesis

E Exponentiation

M Multiplication

D Division

A Addition

S Subtraction

RULES OF PRECEDENCE
• Parentheses have the highest precedence.
2 * (3-1) = 4
• Exponentiation has the next highest precedence
2**1+1 = 3
• Multiplication and Division have the same precedence, which is higher
than Addition and Subtraction, which also have the same precedence.
2*3-1 = 5
• Operators with the same precedence are evaluated rom left to right.

MZCET A.SANGEETHA
10
VALUE AND TYPES:

VALUE:
• A value is one of the basic things a program works with, like a letter or a
number.
• Ex.
1
'Hello, World!‘
“abc”
“good”
7.4
100.567

STANDARD DATA TYPES:

• Python has 5 standard data types:


• Numbers (int, float)
• String
• List
• Tuple
• Dictionary
NUMBERS:

• Number data types store numeric values.


MZCET A.SANGEETHA
11
Example

Var1 = 1

Var2 = 10
• Python supports 4 different numerical types
• int (signed integers)- Whole numbers without decimal point
• long (long integers, they can also be represented in octal and
hexadecimal)
• float (floating point real values)
• complex (complex numbers)

INT LONG FLOAT COMPLEX

10 51924361L 0.0 3.14j

100 -0x19323L 15.20 45.J

-786 0122L -21.9 9.322e-36j

080 0xDEABCECBDAECBBAEl 32.3+e18 .876j

STRING:

• Set of characters represented in the quotation marks.


• Python allows or either pairs of single or double quotes.
S = ‘word’ / “word”

STRING - SLICE OPERATION:


• Subsets of strings can be taken using the slice operation ([ ] & [.] ) with
indexes starting at ‘0’ in the beginning of the string and working their way
from -1 at the end.

MZCET A.SANGEETHA
12
str = 'HELLO WORLD!’
HELLO WORLD!
print(str) #print complete string
H
print(str[0]) #print first character o
string
LLO
print(str[2:5]) #print character starting
rd th
rom 3 to 5
LLO WORLD!
print(str[2:]) #print string starting rom
rd
3 character
HELLO WORLD!HELLO WORLD!
print(str*2) #print string two times
#print concatenated string HELLO WORLD! TEST
print(str + 'TEST')

STRING – STRING OPERATOR


• Strings can be concatenated and repeated.
Concatenation operator
• Strings can be concatenated with the + operator

>>> S = Help OUTPUT:

>>> S+S HelpHelp

Repetition operator
• Strings can be repeated with the * operator

>>> S = Help OUTPUT:

>>> 3*S HelpHelpHelp

MZCET A.SANGEETHA
13
STRING – UNPACKED:

• Strings can be unpacked

>>> S = ab

>>> x,y = S

>>> print x

>>> print y

b
• The number of elements on both sides needs to be the same or else an error
is generated.
LISTS:
• Lists are compound data types
• A list is a sequence of data values called items or elements.
• An item can be of any type.
• A list contains items separated by commas and enclosed with square
brackets [ ]
• Each of the items in a list is ordered by position.
• Lists is similar to array in c.
• One difference between them is that all the items belonging to a list can be
of difference data types.

NESTED LIST:

Ex..
num = [1951, 1969, 1984]
# A list oƒ integers
fruits = ['apples', 'oranges', 'cherries']
# A list oƒ strings
emp = [ ]
# An empty list

MZCET A.SANGEETHA
14
newlist = [ 'spam', 2.0, 5, [10, 20] ]
• A list within another list is nested.
• A list that contains no elements is called an empty list. newlist = [ ]

>>>first=[1,2,3,4]

>>>second =list(range(1,5))

>>>first

[1,2,3,4]

>>>second

[1,2,3,4]

>>>

len operator

>>>len(first)

subscript / slicing operator []

>>>first[0]

>>>first[2:4]

[3,4]

>>>

MZCET A.SANGEETHA
15
Slice operation in LIST:
Examples:
list = ['abcd' , '786' , 2.23 , 'john' , 70.2]
tinylist = [123 , 'john']
print(list) #print complete ['abcd' , '786' , 2.23 , 'john' , 70.2]
list
print(list[0]) #print first abcd
elements of the
list
print(list[1:3]) #print elements ['786', 2.23]
starting from 2nd
till 3rd
print(list[2:]) #print elements [2.23, 'john', 70.2]
starting From 3rd
elements
print(tinylist * 2) #print list two [123, 'john', 123, 'john']
times
print(list + tinylist) #print ['abcd', '786', 2.23, 'john', 70.2, 123,
concatenated lists 'john']

TUPLE:

• A Tuple is sequence data type.


• Similar to the LIST.
• A Tuple is a sequence of immutable python objects
• It consists of a number of values separated by commas.
• Enclosed within parentheses.
• The main differences between lists and tuples are:
MZCET A.SANGEETHA
16
● Lists are enclosed in brackets ( [ ] ) and their elements and size can
be changed, while tuples are enclosed in parentheses ( ( ) ) and
cannot be updated. Tuples can be thought of as read-only lists.

IMMUTABLE OBJECT MUTABLE OBJECT


Objects whose value is unchangeable
Objects whose value can changes
called “IMMUTABLE”
called “MUTABLE”
TUPLE Example:
OUTPUT:
one = (3, 4, 5)
<class 'tuple'>
print(type(one))
Examples: Slice operation in TUPLE:

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )

tinytuple = (123, 'john')


print(tuple) # Prints complete list
print(tuple[0]) # Prints first element of the list
print(tuple[1:3]) # Prints elements starting from 2nd till 3rd
print(tuple[2:]) # Prints elements starting from 3rd element
print(tinytuple * 2) # Prints list two times
print(tuple + tinytuple ) # Prints concatenated lists
Output:

('abcd', 786, 2.23, 'john', 70.200000000000003)

abcd

(786, 2.23)

(2.23, 'john', 70.200000000000003)

(123, 'john', 123, 'john')

('abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john')


MZCET A.SANGEETHA
17
DICTIONARY:

• A dictionary is a mutable, associative data structure of variable length.

• Syntax :

daily 5 {'sun': 68.8, 'mon': 70.2, 'tue': 67.2, 'wed': 71.8,

'thur': 73.2, 'fri': 75.6, 'sat': 74.0}

• A dictionary is like a list.

• In a list, the indices have to be integers; in a dictionary they can be any type.

• Dictionary is a mapping between a set of indices called keys and a set of


values.

• Each key maps to a value.

• The association of a key and a value is called a key-value pair or an item.

• Python's dictionaries are kind of hash table type.


• They work like associative arrays or hashes round in Perl.
• It consist of key-value pairs.
• Key can be almost any type, but are usually numbers or strings.
• Values can be any arbitrary Python object.
• Dictionaries are enclosed by curly braces ( { } ) and values can be assigned
and accessed using square braces ( [ ] ).
DICTIONARY Example:

one = {} OUTPUT:
print(type(one))
<class 'dict'>

MZCET A.SANGEETHA
18
DICTIONARY Example

dict = {}

dict['one'] = "This is one"

dict[2] = "This is two“

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

print(dict['one']) # Prints value or 'one' key

print(dict[2]) # Prints value or 2 key

print(tinydict ) # Prints complete dictionary

print(tinydict.keys()) # Prints all the keys

print(tinydict.values()) # Prints all the values

OUTPUT:

This is one

This is two

{'dept': 'sales', 'code': 6734, 'name': 'john'}

['dept', 'code', 'name']

['sales', 6734, 'john‘]

MZCET A.SANGEETHA
19
BOOLEAN:

• Boolean values are the two constant objects


• False and True
• Used to represent truth values ie.,0 or 1

Boolean expression :
• An expression whose value is either true or false.
• The built-in function bool() can be used to cast any value to a Boolean, if the
value can be interpreted as a truth value They are written as False and True,
respectively.
BOOLEAN Strings:

>>>my_string = "Hello World"


>>>my_string.isalnum() #check if all char are numbers
>>> print(my_string.isalnum()) #false
>>>my_string.isalpha() #check if all char in the string are alphabetic
>>> print(my_string.isalpha()) #false
>>> my_string.isdigit() #test if string contains digits
>>> print(my_string.isdigit()) #false

>>> my_string.istitle() #test if string contains title words

>>> print(my_string.istitle()) #True

>>> my_string.isupper() #test if string contains upper case

>>> print(my_string.istitle()) #True

>>> my_string.islower() #test if string contains lower case

>>> print(my_string.islower()) #false

>>> my_string.isspace() #test if string contains spaces

MZCET A.SANGEETHA
20
>>> print(my_string.isspace()) #false

>>> my_string.endswith('d') #test if string ends with a d

>>> print(my_string.endswith('d')) #True


Example Program:
write the program to convert the string to lower, check islower in string.

s = "Hello there" OUTPUT:

a = s.islower()
Hello there
b = s.lower()
False
print(s)

print(a) hello there

print(b)

Find the output or the following list OUTPUT:

list1 = [2,4,6,8,10,12,14,16,18,20] [2] [12, 14]

print(list1[0:1],list1[5:7])

Find the output or the following list OUTPUT:

colors = ['Red', 'Black', 'White', 'Green'] 2

x = colors.index('White')

print(x)

Find the output or the following list OUTPUT:

my_list = ['apple pie', 'orange jam'] Apple Pie

print(my_list[0].title())

MZCET A.SANGEETHA
21
Program to know the ascii number or the character
# Program to find the ASCII value o the given character
c = input("Enter a character: ")
print("The ASCII value of '" + c + "' is",ord(c))

OUTPUT:

Enter a character: T

The ASCII value o 'T' is 84

Tuple Assignment:

• To swap the values of two variables. With normal assignments, use a


temporary variable.
• For example, to swap a and b:

>>> temp = a

>>> a = b

>>> b = temp
• In Tuple Assignment,

>>> a, b = b, a
• The left side is a tuple of variables
• The right side is a tuple of expressions.
• Each value is assigned to its respective variable.
• All the expressions on the right side are evaluated before any of the
assignments.
• The number of variables on the left and the number of values on the right
have to be the same.

MZCET A.SANGEETHA
22
COMMENTS:

• Comments are little texts that can be added in code.


• A comment is simply one or more lines of text that is not executed by the
computer.
• Used to obtain information about a program.
• Two ways to comment in Python:
• Single-line comments
• Multi-line comments

Single line comment


• A single line comment starts with the number sign (#) character:

# This is a comment

print('Hello')

Multiline comment
• Multiple lines can be created by repeating the number sign several times:

''' This is a multiline

Python comment example.'''

x=5

FUNCTION:
• A function is a block of reusable code that is used to perform a specific
action.
• Function is a group of related statements that perform a specific task.
• It is a named sequence of statements that performs a computation
• It helps the programmer to break the program into small manageable
units or modules
MZCET A.SANGEETHA
23
ADVANTAGES OF USING FUNCTIONS:

 Reducing duplication of code


 Decomposing complex problems into simpler pieces
 Improving clarity of the code
 Reuse of code
 Information hiding

FUNCTION TYPES:

• Built-in functions
• User defined functions

Built-in functions:

Python provides a number of important built-in functions.

• Math function
• Type conversion function

Ex.

max() min() len()

int() float() math.sqrt()

math.sin() math.cos()

MZCET A.SANGEETHA
24
FUNCTION TYPES:

There are two basic types of functions:

• Built-in functions
• User defined functions

Built-in functions :

ascii() Returns String Containing Printable Representation

float() returns floating point number from number, string

input() reads and returns a line of string

int() returns integer from a number or string

len() Returns Length of an Object

max() returns largest element

min() returns smallest element

pow() returns x to the power of y

slice() creates a slice object specified by range()

type() Returns Type of an Object

MZCET A.SANGEETHA
25
MATH FUNCTIONS

Function Description Function

abs(x) The absolute value of x: abs(-45) : 45

ceil(x) The ceiling of x math.ceil(-45.17) : -45

cmp(x, y) -1 if x < y, 0 if x == y, or 1 if
x > y.

exp(x) The exponential of x: e math.exp(100.12) :


X 3.0308436140742566e+43

floor(x) The floor of x: the largest math.floor(100.12) : 100


integer not greater than x.

max(x1, The largest of its max(80, 100, 1000) : 1000


x2,...) arguments:

min(x1, The smallest of its min(-80, -20, -10) : -80


x2,...) arguments:

pow(x, y) The value of x**y. math.pow(2, 4) : 16.0

sqrt(x) The square root of x for x > math.sqrt(100) : 10.0


0.

USER DEFINED FUNCTION:


SYNTAX

def name of function ( list of formal parameters) :

body of function

MZCET A.SANGEETHA
26
• Keyword def : Start of function header.
• Function name : Name of the function.
• Parameters : Arguments - pass values to a function.
They are optional.
• A colon (:) :End of function header
• The function body is any piece of Python code.
• An optional return statement to return a value from the function.
Example of a function
FUNCTION DEFINITION:
def first():
print("Hello, Good morning!")
Function Call
• To call a function, type the function name.
#function definition
def first():
print("Hello, Good morning!")
#main program
first() #function call
Example of a function
#FUNCTION DEFINITION
def add():
a = 11
b = 22
c=a+b
print(“sum =“, c)
#main program
add() #function call

MZCET A.SANGEETHA
27
RETURN STATEMENT
• The return statement is used to exit a function and go back to the place
from where it was called.
Syntax of return
Return [expression_list]

• This statement can contain expression which gets evaluated and the value
is returned.
Example of a function with return type

def add(): #function definition


a = 11

b=2

c=a+b

return c

#main program
sum = add() #function call

print("SUM = ",sum)

USER DEFINED FUNTION TYPES:

 Function with no argument and no return type


 Function with argument and no return type
 Function with return type and no argument
 Function with argument and return type

MZCET A.SANGEETHA
28
Function with no argument and no return type

 Function did not take any value from the main program and it does not
return any value to main function.
Example program
def add():
a = 11
b = 22
c=a+b
print(“Sum =“, c)

#main program

add()

Function with argument and no return type

 Function take some value from the main program and it does not return
value to main function.
def add(a,b):
c=a+b
print("sum = ",c)

#main program

x = 11
y=2
add(x, y)

Function with return type and no argument:

 Function did not take any value from the main program and it return
value to main function.

MZCET A.SANGEETHA
29
def add():

a = 11

b=2

c=a+b

return c

#main program

sum = add()

print("SUM = ",sum)

Function with return type and argument:

 Function take some value from the main program and it return value to
main function.

def add(a,b):

c=a+b

return c

#main program

x = 11

y=2

sum = add(x,y)

print("SUM = ",sum)

MZCET A.SANGEETHA
30
FLOW OF EXECUTION:

• Execution 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.

• Statements inside the function are not executed until the function is
called.

• A function call deviate the flow of execution.

• Instead of going to the next statement, the flow jumps to the body of the
function, executes all the statements there, and then comes back to the
next of function call statement.

PARAMETER AND ARGUMENTS

PARAMETER:

• A name used inside a function to refer to the value passed as an


argument.

MZCET A.SANGEETHA
31
• Inside the function, the arguments are assigned to variables called
parameters.

ARGUMENT:

• A value provided to a function when the function is called. This value is


assigned to the corresponding parameter in the function.

LOCAL VARIABLE:

• A variable defined inside a function. A local variable can only be used


inside its function.

def print_twice(bruce):
Parameter
print bruce

print bruce

>>> print_twice('Spam')

Spam

Spam

>>> print_twice(17)

17

17

LOCAL VARIABLE:

A variable defined inside a function. A local variable can only be used


inside its function.

MZCET A.SANGEETHA
32
def twice( b ):

a=5

print (“a is the local variable. The a value is”, a)

print (“b is not the local variable. The b value is”, b)

print(“main function starts here”)

twice(34)

OUTPUT:

a is the local variable. The a value is 5

b is not the local variable. The b value is 34

Scope and Life time of Variables & Examples

Scope of variable:

 It is a portion of a program where the variable is recognized.


 Variable defined inside a function body have a local scope and which
are defined outside have a global scope.
 Scope of variable determines the portion of the program where you
can access a particular identifier.
 There are two basic scope of variables in python:
o Local variables
o Global variables

Global Vs Local variable:

 Variables that are defined inside a function body have a local scope and
those defined outside have a global scope.

MZCET A.SANGEETHA
33
 The local variables can be accessed only inside the function in which
they declared, whereas global variables can be accessed throughout the
program body by all functions.
 When you call a function the variables declared inside it are brought into
scope.

Local variable:

 When you declare variables inside a function definition they are not
related to any other variables with the same names used outside the
function i.e. variable names local to the function.
 This is called scope of the variable.
 All the variables have the scope of the block they are declared in starting
from the point of definition of the name.

Life time of Variables:

 Lifetime of a variable is the liveliness of the variable exists in memory.


 As long as the function executes, the life time of the variable inside a
function live.
 It will be destroyed once returned from function.
MZCET A.SANGEETHA
34
Function Arguments

Types of formal arguments in python:

Required Arguments

 Required arguments are the arguments passed to the function in


correct positional order.
 The number of arguments passed in the function call should match
exactly with the function definition.

Keyword Arguments

 The caller identifies the arguments by the parameter name


 It skips arguments or placing them out of order. Because the python
interpreter uses the keywords to match the values with parameters.

MZCET A.SANGEETHA
35
Default Arguments

 It assumes default value if a value is not provided in the function call for
that argument.

Variable-length Arguments or Arbitrary Arguments


 Some case, no of arguments that will be passed in to a function is not
known in advance.
 Python allows us to handle this kind of situation through function
calls with arbitrary number of arguments.
 Use “*” symbol before parameter name to denote this kind of argument.

MZCET A.SANGEETHA
36
Lambda or Anonymous Functions

 These are not defined like normal functions by using the keyword def.
 It is defined using the keywords lambda

Syntax:

Lambda arguments: expression

Rules for anonymous function:

 It can take any number of arguments but return one value.


 It cannot contain commands or multiple expressions.

Uses of Lambda Function:

 Lambda functions are used along with built-in functions like filter(), map()
etc.

Filtering:

 The function is called with all the items in the list and a new list is
returned which contains items for the function evaluates True.
 The function filter (function, list) offers a easy way to filter out all the
elements of a list.
 The function filter (f, l) needs a function ‘f’ as its first argument. ‘f’
returns a Boolean value.

MZCET A.SANGEETHA
37
Map() Function:

 The function is called with all the items in the list and a new list is
returned which contains items returned by that function and a list.

Syntax: map (func, seq)

 The first argument func is the name of a function and the second one seq
is a sequence.

Modules :

 It is a file which contains python definitions and statements.


 It defines functions, classes and variables.
 It includes runnable code also.
 Functions are group of codes
 Modules are group of functions.

User defined Modules

Steps for creating modules:

 Create a python file with one or more functions and save it with .py
extension.
 Include the import statement.
 When the interpreter comes across an import statement, it imports
the module if the module is already present in the search path
 A search path is a list of directories that the interpreter searches
before importing modules.
 Module is loaded only once, even if multiple imports occur.
 Using the module name the function is accessed using dot (.) operation

MZCET A.SANGEETHA
38
For example,

Module creation:

Module name : sample.py

def add(a,b):

return a + b

python program to call add function in the module sample:

import sample

c = sample.add(5,8)

print("C=",c)

The From … import Statements

 Module involves hundreds of function, from … import statement is


recommended to save loading time.

MZCET A.SANGEETHA
39
 Multiple functions can be imported by separating their name with
commas

For example

Built in Modules

 There are plenty of built in modules


 Some of the useful built in modules are:

Random

 It generates random numbers.


 If a random integer is needed, use the randint functions.
 It accepts two parameters: lowest and highest
MZCET A.SANGEETHA
40
 If a random floating point number is needed, use the random function.

Math

 It accesses the mathematical constants and functions.


 Calendar and date-time
 It helps to track dates and times.
For example

Illustrative Problem:

Exchange a value of two variables

Program:

X=10

Y= 20

print (“Before Swapping”)

print(X)

print(Y)
MZCET A.SANGEETHA
41
X,Y = Y,X

print(“After Swapping”)

print(X)

print(Y)

PROGRAM TO CIRCULATE THE VALUES OF N VARIABLES

list1 = [1,2,3,4,5,6,7] OUTPUT:


The list elements
print("The list elements \n")
1
for i in range (len(list1)): 2
3
print(list1[i])
4
temp = list1[0] 5
6
for i in range(1, len(list1)):
7

list1[i-1] = list1[i] 2
3
list1[i] = temp 4
5
for i in range(len(list1)):
6
print(list1[i]) 7
1

MZCET A.SANGEETHA
42
Python program to find distance between two points

def pt(x1,y1,x2,y2):

x=x2-x1

y=y2-y1

x=x**2

y=y**2

d=(x+y)**(0.5)

return d

x1=int(input('Enter the coordinate x1: '))

x2=int(input('Enter the coordinate x2: '))

y1=int(input('Enter the coordinate y1: '))

y2=int(input('Enter the coordinate y2: '))

k=pt(x1,y1,x2,y2)

print ('Distance between two points is : ', k)

OUTPUT:

Enter the coordinate x1: 3

Enter the coordinate x2: 4

Enter the coordinate y1: 3

Enter the coordinate y2: 5

Distance between two points is : 2.23606797749979

MZCET A.SANGEETHA
43
Difference between Interpreter and Compiler.

Interpreter Compiler

Translates program one statement at Scans the entire program and


a time. translates it as a whole into machine
code.
Takes less amount of time to analyze Takes large amount of time to analyze
source Code source code.
Overall execution time is slower. Overall execution time is
comparatively faster.
Programming languages like Python, Programming languages like C,C++
Ruby use interpreters. use compilers.
Difference between program and script.

Program Script

A program is executed. A Script is interpreted.

A program is a set of instructions A Scripting language is nothing but a


written so that a computer can type of programming language in
perform certain task. which can code to control another
software application.

Simple Python Program :

# This program prints Hello, World!

prrint (‘Hello, World’)

 In python 2, “print” is not a function.


 It is invoked without parenthesis
 In python 3, it is a function.
 It must be invoked with parenthesis

MZCET A.SANGEETHA
44
Python Identifiers

 Identifiers are name for entities in program


 Entities – class, variables, functions and etc.
 Python is case sensitive language.
 i.e Variable and variable are not same.

Rules:

 It composed of uppercase, lowercase letter, underscore and digits


 It should start only with an alphabet or a underscore.
 It cannot start with digit
 Keywords cannot be used as identifiers
 It can be any length.
 No special symbols like !, @, #, $, % etc. are used.
 Example: sum, total, Average,_ab_, add_1,x1 – Valid
 1x, char x+y - invalid

Python Indentation:

 { } – used in C, C++ and Java to define block of codes.


 Python uses indentation.
 Block of codes starts with indentation and ends with unintended.
 4 whites space characters are used
 Consider the following example

MZCET A.SANGEETHA
45
In the above example, the block of statements inside the if statement
contains indentation (4 spaces)

Input/ Output Statements :


Output Statements :
 print() –function is used to output data to the standard output devices.

Example: print “Python is good Language”

Input Statements

 Python provides two built-in function to read a line of text from standard input
device, keyboard
 input()
If user enters integer input an integer will be returned, if user enters

string input, string is returned.

 raw_input()
It takes what user typed and passes it back as string.

For examples:

Output

MZCET A.SANGEETHA
46

Das könnte Ihnen auch gefallen