PRGN
PRGN
PRGN
Introduction to Python
Python Interpreter and its working
Syntax and Semantics
Lab 1:Python Numbers, List
Data Types
Assignments
Expressions
1. INTRODUCTION TO PYTHON:
Python is a general-purpose interpreted, interactive, object-oriented, and high-
level programming language.
It was created by Guido van Rossum during 1985- 1990.
Python got its name from “Monty Python’s flying circus”. Python was released in the
year 2000.
Python is interpreted: Python is processed at runtime by the interpreter. You
do not need to compile your program before executing it.
Python is Interactive: You can actually sit at a Python prompt and interact with
the interpreter directly to write your programs.
Python is Object-Oriented: Python supports Object-Oriented style or technique
of programming that encapsulates code within objects.
Python is a Beginner's Language: Python is a great language for the beginner-
level programmers and supports the development of a wide range of
applications.
Python Features:
Easy-to-learn: Python is clearly defined and easily readable. The structure
of the program is very simple. It uses few keywords.
Easy-to-maintain: Python's source code is fairly easy-to-maintain.
Portable: Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
Interpreted: Python is processed at runtime by the interpreter. So, there is no
need to compile a program before executing it. You can simply run the program.
Extensible: Programmers can embed python within their C,C++,Java script
,ActiveX, etc.
Free and Open Source: Anyone can freely distribute it, read the source code, and
edit it.
High Level Language: When writing programs, programmers concentrate on
solutions of the current problem, no need to worry about the low level details.
Scalable: Python provides a better structure and support for large programs
than shell scripting.
Applications:
Bit Torrent file sharing
Google search engine, Youtube
Intel, Cisco, HP, IBM
i–Robot
NASA
Python interpreter:
Interpreter: To execute a program in a high-level language by translating it one line at
a time.
Compiler: To translate a program written in a high-level language into a low-level
language all at once, in preparation for later execution.
Compiler Interpreter
Interpreter Takes Single instruction as
Compiler Takes Entire program as input
input
No Intermediate Object Code
Intermediate Object Code is Generated
is Generated
Conditional Control Statements are Conditional Control Statements are
Executes faster Executes slower
Memory Requirement is More(Since Object
Memory Requirement is Less
Code is Generated)
Every time higher level program is
Program need not be compiled every time
converted into lower level program
Errors are displayed after entire Errors are displayed for every
program is checked instruction interpreted (if any)
Example : C Compiler Example : PYTHON
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.
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:
Numbers:
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,
Sequence:
A sequence is an ordered collection of items, indexed by positive integers.
It is a combination of mutable (value can be changed) and immutable (values
cannot be changed) data types.
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
Repetitions
Updation, Insertion, Deletion
Tuple:
A tuple is same as list, except that the set of elements is enclosed in parentheses
instead of square brackets.
A tuple is an immutable list. i.e. once a tuple has been created, you can't add
elements to a tuple or remove elements from the tuple.
Benefit of Tuple:
Tuples are faster than lists.
If the user wants to protect the data from accidental changes, tuple can be used.
Tuples can be used as keys in dictionaries, while lists can't.
Basic Operations:
Creating a tuple >>>t=("python", 7.79, 101, Creating the tuple with elements
"hello”) of different data types.
Indexing >>>print(t[0]) Accessing the item in the
python position 0
>>> t[2] Accessing the item in the
101
position 2
Slicing( ending >>>print(t[1:3]) Displaying items from 1st
position -1) (7.79, 101) till 2nd.
Altering the tuple data type leads to error. Following error occurs when user tries to
do.
Mapping
-This data type is unordered and mutable.
-Dictionaries fall under Mappings.
Dictionaries:
Lists are ordered sets of objects, whereas dictionaries are unordered sets.
Dictionary is created by using curly brackets. i,e. {}
Dictionaries are accessed via keys and not via their position.
A dictionary is an associative array (also known as hashes). Any key of the
dictionary is associated (or mapped) to a value.
The values of a dictionary can be any Python data type. So dictionaries are
unordered key-value-pairs(The association of a key and a value is called a key-
value pair )
Dictionaries don't support the sequence operation of the sequence data types like
strings, tuples and lists.
If you try to access a key which doesn't exist, you will get an error message:
>>> words = {"house" : "Haus", "cat":"Katze"}
>>> words["car"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'car'
3.1VARIABLES:
A variable allows us to store a value by assigning it to a name, which can be used
later.
Named memory locations to store values.
Programmers generally choose names for their variables that are meaningful.
It can be of any length. No space is allowed.
We don't need to declare a variable before using it. In Python, we simply assign a
value to a variable and it will exist.
>>> a=b=c=100
Assigning multiple values to multiple variables:
>>> a,b,c=2,4,"ram"
3.2KEYWORDS:
Keywords are the reserved words in Python.
We cannot use a keyword as variable name, function name or any other
identifier.
They are used to define the syntax and structure of the Python language.
Keywords are case sensitive.
3.3IDENTIFIERS:
Identifier is the name given to entities like class, functions, variables etc. in
Python.
Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to
Z) or digits (0 to 9) or an underscore (_).
3.6 COMMENTS:
A hash sign (#) is the beginning of a comment.
Anything written after # in a line is ignored by interpreter.
Eg:percentage = (minute * 100) / 60 # calculating percentage of an hour
Python does not have multiple-line commenting feature. You have to
comment each line individually as follows :
Example:
# This is a comment.
# This is a comment, too.
# I said that already.
DOCSTRING:
Docstring is short for documentation string.
It is a string that occurs as the first statement in a module, function, class, or
method definition. We must write what a function/class does in the docstring.
Triple quotes are used while writing docstrings.
Syntax:
functionname__doc.__
Example:
def double(num):
"""Function to double the value"""
return 2*num
>>> print(double.__doc__)
Function to double the value
Example:
-It is useful to swap the values of two variables. With conventional assignment
statements, we have to use a temporary variable. For example, to swap a and b:
(a, b) = (b, a)
-In tuple unpacking, the values in a tuple on the right are ‘unpacked’ into the
variables/names on the right:
4.OPERATORS:
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is
called operator
Types of Operators:
-Python language supports the following types of operators
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
13 Unit 2: Data ,expressions, Statements
Arithmetic operators:
They are used to perform mathematical operations like addition, subtraction,
multiplication etc. Assume, a=10 and b=5
Examples Output:
a=10 a+b= 15
b=5 a-b= 5
print("a+b=",a+b) a*b= 50
print("a-b=",a-b) a/b= 2.0
print("a*b=",a*b) a%b= 0
print("a/b=",a/b) a//b= 2
print("a%b=",a%b) a**b= 100000
print("a//b=",a//b)
print("a**b=",a**b)
> If the value of left operand is greater than the value of right (a > b) is
operand, then condition becomes true. not true.
< If the value of left operand is less than the value of right (a < b) is
operand, then condition becomes true. true.
>= If the value of left operand is greater than or equal to the (a >= b) is
value of right operand, then condition becomes true. not true.
<= If the value of left operand is less than or equal to the value (a <= b) is
of right operand, then condition becomes true. true.
Example
a=10 Output:
b=5 a>b=> True
print("a>b=>",a>b) a>b=> False
print("a>b=>",a<b) a==b=> False
print("a==b=>",a==b) a!=b=> True
print("a!=b=>",a!=b) a>=b=> False
print("a>=b=>",a<=b) a>=b=> True
print("a>=b=>",a>=b)
Assignment Operators:
-Assignment operators are used in Python to assign values to variables.
Operator Description Example
+= Add AND It adds right operand to the left operand and assign c += a is
the result to left operand equivalent
to c = c + a
Example Output
a = 21 Line 1 - Value of c is 31
b = 10 Line 2 - Value of c is 52
c=0 Line 3 - Value of c is 1092
c=a+b Line 4 - Value of c is 52.0
print("Line 1 - Value of c is ", c) Line 5 - Value of c is 2
c += a Line 6 - Value of c is 2097152
print("Line 2 - Value of c is ", c) Line 7 - Value of c is 99864
c *= a
print("Line 3 - Value of c is ", c)
c /= a
print("Line 4 - Value of c is ", c)
c=2
c %= a
print("Line 5 - Value of c is ", c)
c **= a
print("Line 6 - Value of c is ", c)
c //= a
print("Line 7 - Value of c is ", c)
Example Output
a = True x and y is False
b = False x or y is True
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)
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
y = 4 (0000 0100 in binary)
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
print "Line 1 - Value of c is ", c Line 5 - Value of c is 240
c = a | b; # 61 = 0011 1101 Line 6 - Value of c is 15
print "Line 2 - Value of c is ", c
c = a ^ b; # 49 = 0011 0001
print "Line 3 - Value of c is ", c
c = ~a; # -61 = 1100 0011
17 Unit 2: Data ,expressions, Statements
print "Line 4 - Value of c is ", c
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
Membership Operators:
Example:
x=[5,3,6,4,1]
>>> 5 in x
True
>>> 5 not in x
False
Identity Operators:
They are used to check if two values (or variables) are located on the same part of
the
memory.
Example
x=5 Output
y=5 False
x2 = 'Hello' True
y2 = 'Hello'
print(x1 is not y1)
print(x2 is y2)
18 Unit 2: Data ,expressions, Statements
5.OPERATOR PRECEDENCE:
When an expression contains more than one operator, the order of evaluation
depends on the order of operations.
Operator Description
a=2,b=12,c=1 a=2*3+4%5-3//2+6
d=a<b>c a=2,b=12,c=1 a=6+4-1+6
d=2<12>1 d=a<b>c-1 a=10-1+6
d=1>1 d=2<12>1-1 a=15
d=0 d=2<12>0
d=1>0
d=1
6.1 FUNCTIONS:
Function is a sub program which consists of set of instructions used to
perform a specific task. A large program is divided into basic building blocks
called function.
Need For Function:
When the program is too complex and large they are divided into parts. Each part
is separately coded and combined into single program. Each subprogram is called
as function.
Debugging, Testing and maintenance becomes easy when the program is divided
into subprograms.
Functions are used to avoid rewriting same code again and again in a program.
Function provides code re-usability
The length of the program is reduced.
Types of function:
Functions can be classified into two categories:
i) user defined function
ii) Built in function
i) Built in functions
Built in functions are the functions that are already created and stored in python.
These built in functions are always available for usage and accessed by a
programmer. It cannot be modified.
Built in function Description
20 Unit 2: Data ,expressions, Statements
>>>max(3,4) # returns largest element
4
>>>min(3,4) # returns smallest element
3
>>>len("hello") #returns length of an object
5
>>>range(2,8,1) #returns range of given values
[2, 3, 4, 5, 6, 7]
>>>round(7.8) #returns rounded integer of the given number
8.0
>>>chr(5) #returns a character (a string) from an integer
\x05'
>>>float(5) #returns float number from string or integer
5.0
>>>int(5.0) # returns integer from string or float
5
>>>pow(3,5) #returns power of given number
243
>>>type( 5.6) #returns data type of object to which it belongs
<type 'float'>
>>>t=tuple([4,6.0,7]) # to create tuple of items from list
(4, 6.0, 7)
>>>print("good morning") # displays the given object
Good morning
>>>input("enter name: ") # reads and returns the given string
enter name : George
The order in which statements are executed is called the flow of execution
Execution always begins at the first statement of the program.
Statements are executed one at a time, in order, from top to bottom.
Function definitions do not alter the flow of execution of the program, but
remember that statements inside the function are not executed until the function
is called.
Function calls are like a bypass in the flow of execution. Instead of going to the next
statement, the flow jumps to the first line of the called function, executes all the
statements there, and then comes back to pick up where it left off.
Note: When you read a program, don’t read from top to bottom. Instead, follow the flow
of execution. This means that you will read the def statements as you are scanning from
top to bottom, but you should skip the statements of the function definition until you
reach a point where that function is called.
OUTPUT: OUTPUT:
enter a 5 enter a 5
enter b 10 enter b 10
15 15
Example:
def my_add(a,b):
c=a+b
return c
x=5
y=4
print(my_add(x,y))
Output:
9
ARGUMENTS TYPES:
1. Required Arguments
2. Keyword Arguments
3. Default Arguments
4. Variable length Arguments
Required Arguments: The number of arguments in the function call should
match exactly with the function definition.
def my_details( name, age ):
print("Name: ", name)
print("Age ", age)
return
my_details("george",56)
24 Unit 2: Data ,expressions, Statements
Output:
Name: george
Age 56
Keyword Arguments:
Python interpreter is able to use the keywords provided to match the values with
parameters even though if they are arranged in out of order.
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
MODULES:
A module is a file containing Python definitions ,functions, statements and
instructions.
Standard library of Python is extended as modules.
To use these modules in a program, programmer needs to import the
module.
ILLUSTRATIVE PROGRAMS
Program for SWAPPING(Exchanging )of Output
values
a = int(input("Enter a value ")) Enter a value 5
b = int(input("Enter b value ")) Enter b value 8
c=a a=8
a=b b=5
b=c
print("a=",a,"b=",b,)
Part A:
1. What is interpreter?
2. What are the two modes of python?
3. List the features of python.
4. List the applications of python
5. List the difference between interactive and script mode
6. What is value in python?
7. What is identifier? and list the rules to name identifier.
8. What is keyword?
9. How to get data types in compile time and runtime?
10. What is indexing and types of indexing?
11. List out the operations on strings.
12. Explain slicing?
13. Explain below operations with the example
(i)Concatenation (ii)Repetition
14. Give the difference between list and tuple
15. Differentiate Membership and Identity operators.
16. Compose the importance of indentation in python.
17. Evaluate the expression and find the result
(a+b)*c/d
a+b*c/d
18. Write a python program to print ‘n’ numbers.
19. Define function and its uses
20. Give the various data types in Python
21. Assess a program to assign and access variables.
22. Select and assign how an input operation was done in python.
23. Discover the difference between logical and bitwise operator.
24. Give the reserved words in Python.
25. Give the operator precedence in python.
26. Define the scope and lifetime of a variable in python.
27. Point out the uses of default arguments in python
28. Generalize the uses of python module.
29. Demonstrate how a function calls another function. Justify your answer.
30. List the syntax for function call with and without arguments.
31. Define recursive function.
32. What are the two parts of function definition? give the syntax.
33. Point out the difference between recursive and iterative technique.
34. Give the syntax for variable length arguments.
Python Lambda
What is Lambda Function in Python?
A Lambda Function in Python programming is an anonymous function or a function having no name. It is a
small and restricted function having no more than one line. Just like a normal function, a Lambda function
can have multiple arguments with one expression.
In Python, lambda expressions (or lambda forms) are utilized to construct anonymous functions. To do so,
you will use the lambda keyword (just as you use def to define normal functions). Every anonymous function
you define in Python will have 3 essential parts:
The lambda keyword.
The parameters (or bound variables), and
The function body.
A lambda function can have any number of parameters, but the function body can only
contain one expression. Moreover, a lambda is written in a single line of code and can also be invoked
immediately. You will see all this in action in the upcoming examples.
Here, p1 and p2 are the parameters which are passed to the lambda function. You can add as many or few
parameters as you need.
However, notice that we do not use brackets around the parameters as we do with regular functions. The
last part (expression) is any valid python expression that operates on the parameters you provide to the
function.
Example 1
Now that you know about lambdas let's try it with an example. So, open your IDLE and type in the following:
adder = lambda x, y: x + y
print (adder (1, 2))
Code Explanation
Here, we define a variable that will hold the result returned by the lambda function.
3. This is the body of the function, which adds the 2 parameters we passed. Notice that it is a single
expression. You cannot write multiple statements in the body of a lambda function.
Example 2
That was a basic example to understand the fundamentals and syntax of lambda. Let's now try to print out a
lambda and see the result. Again, open your IDLE and type in the following:
Now save your file and hit F5 to run the program. This is the output you should get.
Output:
<function <lambda> at 0x00000185C3BF81E0>
Code Explanation
But why doesn't the program print the string we pass? This is because the lambda itself returns a function
object. In this example, the lambda is not being called by the print function but simply returning the function
object and the memory location where it is stored. That's what gets printed at the console.
Example 3
Output:
Now, the lambda is being called, and the string we pass gets printed at the console. But what is that weird
syntax, and why is the lambda definition covered in brackets? Let's understand that now.
Code Explanation
Example 4
Let's look at a final example to understand how lambdas and regular functions are executed. So, open your
IDLE and in a new file, type in the following:
#A REGULAR FUNCTION
def guru( funct, *args ):
funct( *args )
def printer_one( arg ):
return print (arg)
def printer_two( arg ):
print(arg)
#CALL A REGULAR FUNCTION
guru( printer_one, 'printer 1 REGULAR CALL' )
guru( printer_two, 'printer 2 REGULAR CALL \n' )
#CALL A REGULAR FUNCTION THRU A LAMBDA
guru(lambda: printer_one('printer 1 LAMBDA CALL'))
guru(lambda: printer_two('printer 2 LAMBDA CALL'))
Now, save the file and hit F5 to run the program. If you didn't make any mistakes, the output should be
something like this.
Output:
Code Explanation
1. A function called guru that takes another function as the first parameter and any other arguments
following it.
2. printer_one is a simple function which prints the parameter passed to it and returns it.
3. printer_two is similar to printer_one but without the return statement.
4. In this part, we are calling the guru function and passing the printer functions and a string as
parameters.
5. This is the syntax to achieve the fourth step (i.e., calling the guru function) but using lambdas.
In the next section, you will learn how to use lambda functions with map(), reduce(), and filter() in Python.
IIFE stands for immediately invoked function execution. It means that a lambda function is callable as
soon as it is defined. Let's understand this with an example; fire up your IDLE and type in the following:
This ability of lambdas to be invoked immediately allows you to use them inside functions like map() and
reduce(). It is useful because you may not want to use these functions again.
lambdas in filter()
The filter function is used to select some particular elements from a sequence of elements. The sequence
can be any iterator like lists, sets, tuples, etc.
The elements which will be selected is based on some pre-defined constraint. It takes 2 parameters:
For example,
sequences = [10,2,8,7,5,4,3,11,0, 1]
filtered_result = filter (lambda x: x > 4, sequences)
print(list(filtered_result))
[10, 8, 7, 5, 11]
Code Explanation:
1. In the first statement, we define a list called sequences which contains some numbers.
2. Here, we declare a variable called filtered_result, which will store the filtered values returned by the filter()
function.
3. A lambda function which runs on each element of the list and returns true if it is greater than 4.
lambdas in map()
the map function is used to apply a particular operation to every element in a sequence. Like filter(), it also
takes 2 parameters:
For example, here is a program that prints the squares of numbers in a given list:
sequences = [10,2,8,7,5,4,3,11,0, 1]
filtered_result = map (lambda x: x*x, sequences)
print(list(filtered_result))
Output:
[KR1]
Code Explanation:
lambdas in reduce()
The reduce function, like map(), is used to apply an operation to every element in a sequence. However, it
differs from the map in its working. These are the steps followed by the reduce() function to compute an
output:
Step 1) Perform the defined operation on the first 2 elements of the sequence.
Step 3) Perform the operation with the saved result and the next element in the sequence.
120
Code Explanation:
However, you should know when it is a good idea to use lambdas and when to avoid them. In this section,
you will learn some of the design principles used by python developers when writing lambdas.
One of the most common use cases for lambdas is in functional programming as Python supports a
paradigm (or style) of programming known as functional programming.
It allows you to provide a function as a parameter to another function (for example, in map, filter, etc.). In
such cases, using lambdas offer an elegant way to create a one-time function and pass it as the parameter.
You should never write complicated lambda functions in a production environment. It will be very difficult for
coders who maintain your code to decrypt it. If you find yourself making complex one-liner expressions, it
would be a much superior practice to define a proper function. As a best practice, you need to remember
that simple code is always better than complex code.
Lambdas
Regular Functions
Syntax:
lambda x : x + x
Syntax:
def (x) :
return x + x
Regular functions can have multiple expressions and statements in their body.
Lambdas do not have a name associated with them. That's why they are also known as anonymous
functions.
Lambdas do not contain a return statement because the body is automatically returned.
The primary difference between a lambda and a regular function is that the lambda function evaluates only a
single expression and yields a function object. Consequently, we can name the result of the lambda function
and use it in our program as we did in the previous example.
A regular function for the above example would look like this:
Here, we have to define a name for the function which returns the result when we call it. A lambda function
doesn't contain a return statement because it will have only a single expression which is always returned by
default. You don't even have to assign a lambda either as it can be immediately invoked (see the next
section). As you will see in the following example, lambdas become particularly powerful when we use them
with Python's built-in functions.
However, you may still be wondering how lambdas are any different from a function that returns a single
expression (like the one above). At the interpreter level, there is not much difference. It may sound
surprising, but any lambda function that you define in Python is treated as a normal function by the
interpreter.