0% found this document useful (0 votes)
3 views90 pages

python module 2

Uploaded by

arnav.24bsa10023
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
3 views90 pages

python module 2

Uploaded by

arnav.24bsa10023
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 90

Unit – 2

Python Data, Expressions and


Statements
Dr. Jothiaruna N
SCSE, VIT Bhopal.
Python interpreter and interactive mode
Python interpreter
It reads and interprets Python scripts or commands by converting them into
machine-readable instructions, so that the computer can execute.

It allows developers to interactively run Python code line by line (Interpreter takes
single instruction as input).
Python interpreter and interactive mode
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 takes entire program as input.


Python interpreter and interactive mode
Python interpreter and interactive mode
Python Interpreter is a program that reads and executes Python code. It uses 2 modes of
Execution.

Interactive mode

Script mode
Interactive Mode
Interactive Mode, as the name suggests, allows us to interact with OS.

When we type Python statement, interpreter displays the result(s) immediately.

Advantages:

Python, in interactive mode, is good enough to learn, experiment or explore.

Working in interactive mode is convenient for beginners and for testing small
pieces of code.
Interactive Mode
Drawback:
We cannot save the statements and have to retype all the statements once again
to re-run them.
In interactive mode, you type Python programs and the interpreter displays the
result:
>>>1 + 1
>>> 2
>>>print ('Hello, World!')
Hello, World!
Interactive Mode
• The chevron, >>>, is the prompt the interpreter uses to indicate that
it is ready for you to enter code.
• If you type 1 + 1, the interpreter replies 2.

>>> print ('Hello, World!')


Hello, World!
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.
• Save the code with filename.py and run the interpreter in script mode to execute
the script.
• Working in interactive mode is convenient for beginners
• For testing small pieces of code, as we can test them immediately, interactive
mode is good.
• But for coding more than few lines, we should always save our code so that we
may modify and reuse the code.
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.
VALUES AND DATA TYPES
Value
Value can be any letter ,number or string.
EX, 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.
VALUES AND DATA TYPES
VALUES AND 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,
STATEMENTS AND EXPRESSIONS:
Statements:
Instructions that a Python interpreter can
executes are called statements.

A statement is a unit of code like creating


a variable or displaying a value.

>>> n = 17
>>> print(n)

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.
COMMENTS:

A hash sign (#) is the beginning of a comment.

Anything written after # in a line is ignored by


interpreter.

Python does not have multiple-line commenting


feature. You have to comment each line
individually as follows :

Eg: # This is a comment. Eg: percentage = (minute * 100) / 60


# This is a comment, too. # calculating percentage of an hour
# I said that already.
DOCSTRING

Docstring is short for documentation string.


Syntax:
Functionname.__doc__

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.


LINES AND INDENTATION
Most of the programming languages like C, C++, Java use braces { } to define a
block of code. But, python uses indentation.
Blocks of code are denoted by line
indentation.
It is a space given to the block of codes for class and function definitions or
flow control.
TUPLE ASSIGNMENT

• An assignment to all of the elements in a tuple using a single assignment statement.

• Python has a very powerful tuple assignment feature that allows a tuple of variables on
the left of an assignment to be assigned values from a tuple on the right of the
assignment.

• The left side is a tuple of variables; the right side is a tuple of values.

• Each value is assigned to its respective variable.


• All the expressions on the right side are evaluated before any of the assignments. This
feature makes tuple assignment quite versatile.
• Naturally, the number of variables on the left and the number of values on the right have
to be the same.
TUPLE ASSIGNMENT

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:
TUPLE ASSIGNMENT
• Tuple assignment solves this problem neatly:

(a, b) = (b, a)

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


• In tuple packing, the values on the left are ‘packed’ together in a tuple:
>>> b = ("George", 25, "20000") # tuple

• In tuple unpacking, the values in a tuple on the right are ‘unpacked’ into
the variables/names on the right:
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.
❖ There are three types of sequence data type available in Python, they are

• Strings
• Lists
• Tuples
STRINGS
A String in Python consists of a series or sequence of characters - letters,
▪ numbers, and special characters.
Strings are marked by quotes:
∙ single quotes (' '), Eg, 'This a string in single quotes'
∙ double quotes (" "), Eg, "This a string in double quotes“
∙ triple quotes (""“ """), Eg, This is a paragraph. It is made up of
€ multiple lines and sentences."""
▪ Individual character in a string is accessed using a subscript (index).
Characters can be accessed using indexing and slicing operations
Strings are immutable i.e. the contents of the string cannot be changed
after it is created.
STRINGS

Strings and Operations

Indexing
Concatenation
Slicing
Repetition
Membership

Live Examples …….


LISTS
• A list in Python is used to store the sequence of various types of data.
L1 = ["John", 102, "USA"]
L2 = [1, 2, 3, 4, 5, 6]
• The items in the list are separated with the comma (,) and enclosed with
the square brackets [].
• Python lists are mutable type it means that we can modify its element after
it created.
• However, Python consists of six data-types
• They are capable to store the sequences.
• But the most common and reliable type is the list.
• print(type(L1))

• print(type(L2))

• <class ‘list’>
Characteristics of Lists

• The lists are ordered.


a = [1,2,"Peter",4.50,"Ricky",5,6]
b = [1,2,5,"Peter",4.50,"Ricky",6]
a ==b This results in False. Why?
• The element of the list can access by index.
• The lists are the mutable type.
• A list can store the number of various elements.
LISTS
Lists and Operations
Indexing
Concatenation
Slicing
Repetition
Membership
Updation-Deletion and Insertion

Live Examples …….


• list_varible(start:stop:step)
• The start denotes the starting index position of the list.
• The stop denotes the last index position of the list.
• The step is used to skip the nth element within a start:stop
list = [1,2,3,4,5,6,7]
print(list[0])
print(list[1])
print(list[2])
print(list[3])
# Slicing the elements
print(list[0:6])
print(list[:])
print(list[2:5])
print(list[1:6:2])
• Unlike other languages, Python provides the flexibility to use the
negative indexing also.
• The negative indices are counted from the right.
• The last element (rightmost) of the list has the index -1;
• its adjacent left element is present at the index -2 and so on until the
left-most elements are encountered.
Updating List values
• Lists are the most versatile data structures in Python since they are
mutable, and their values can be updated by using the slice and
assignment operator.
list = [1, 2, 3, 4, 5, 6]
print(list)
[1, 2, 3, 4, 5, 6]
list[2] = 10 [1, 2, 10, 4, 5, 6]
print(list) [1, 89, 78, 4, 5, 6]
list[1:3] = [89, 78] [1, 89, 78, 4, 5, 25]
print(list)
list[-1] = 25
print(list)
l1 = [1, 2, 3, 4] l2 = [5, 6, 7, 8]
TUPLES
❖ A tuple is same as list, except that the set of elements is enclosed in
▪ parentheses instead of square brackets.
❖ 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.
TUPLES

Tuples and Operations

Indexing
Concatenation
Slicing
Repetition

Live Examples …….


T1 = (101, "Peter", 22)
T2 = ("Apple", "Banana", "Orange")
T3 = 10,20,30,40,50

print(type(T1)) <class 'tuple'>


print(type(T2)) <class 'tuple'>
print(type(T3)) <class 'tuple'>
• Empty Tuple
T4 = ()
• Creating a tuple with single element is slightly different. We will need
to put comma after the element to declare the tuple.
tup1 = ("JavaTpoint")
print(type(tup1)) <class 'str'>
#Creating a tuple with single element
tup2 = ("JavaTpoint",)
print(type(tup2)) <class 'tuple'>
tuple1 = (10, 20, 30, 40, 50, 60)
print(tuple1)
(10, 20, 30, 40, 50, 60)
count = 0
for i in tuple1:
tuple1[0] = 10
print("tuple1[%d] = %d"%(count, i)) tuple1[1] = 20
count = count+1 tuple1[2] = 30
tuple1[3] = 40
tuple1[4] = 50
tuple1[5] = 60
tuple1 = tuple(input("Enter the tuple elements ..."))
print(tuple1) Enter the tuple elements ...
count = 0 123456
for i in tuple1: ('1', '2', '3', '4', '5', '6')
print("tuple1[%d] = %s"%(count, i)) tuple1[0] = 1
count = count+1 tuple1[1] = 2
tuple1[2] = 3
tuple1[3] = 4
tuple1[4] = 5
tuple1[5] = 6
Tuple indexing and slicing

• The indexing and slicing in the tuple are similar to lists. The indexing
in the tuple starts from 0 and goes to length(tuple) - 1.
• The items in the tuple can be accessed by using the index [] operator.
• Python also allows us to use the colon operator to access multiple
items in the tuple.
tuple = (1,2,3,4,5,6,7)
#element 1 to end
print(tuple[1:]) (2, 3, 4, 5, 6, 7)
#element 0 to 3 element (1, 2, 3, 4)
print(tuple[:4]) (1, 2, 3, 4)
#element 1 to 4 element (1, 3, 5)
print(tuple[1:5])
# element 0 to 6 and take step of 2
• print(tuple[0:6:2])
tuple1 = (1, 2, 3, 4, 5)
print(tuple1[-1]) 5
print(tuple1[-4])
2
print(tuple1[-3:-1])
print(tuple1[:-1])
(3, 4)
print(tuple1[-2:]) (1, 2, 3, 4)
(4, 5)
Deleting Tuple

• Unlike lists, the tuple items cannot be deleted by using the del keyword as
tuples are immutable.
• To delete an entire tuple, we can use the del keyword with the tuple name
tuple1 = (1, 2, 3, 4, 5, 6)
print(tuple1) (1, 2, 3, 4, 5, 6)
del tuple1[0] Traceback (most recent call last):
print(tuple1) File "tuple.py",
del tuple1 line 4, in <module> print(tuple1)
print(tuple1) NameError: name 'tuple1' is not defined
t = (1, 2, 3, 4, 5)
t1 = (6, 7, 8, 9)
Mapping and Dictionaries
❖ Unordered and Mutable data type

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.
DICTIONARIES

Operations

Indexing
Creating a Dictionary

Live Examples …….


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
Arithmetic operators
• They are used to perform mathematical operations like addition,
subtraction, multiplication etc. Assume, a=10 and b=5
Comparison (Relational) Operators:
• Comparison operators are used to compare values.

• It either returns True or False according to the condition. Assume, a=10 and
b=5
Comparison (Relational) Operators:
• Comparison operators are used to compare values.

• It either returns True or False according to the condition. Assume, a=10 and
b=5
Assignment Operators
• Assignment operators are used in Python to assign values to variables.
Assignment Operators
Assignment Operators
Logical Operators
• Logical operators are the and, or, not operators.
Bitwise Operators:
• A bitwise operation operates on one or more bit patterns at the level of individual bits
Dr. Jothiaruna N, VIT Bhopal University
Bitwise Operators
As the name suggests, bitwise operators perform operations at the bit level. These operators include bitwise AND,
bitwise OR, bitwise XOR, and shift operators. Bitwise operators expect their operands to be of integers and treat them
as a sequence of bits.
The truth tables of these bitwise operators are given below.

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


64
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)
Shift Operators
Python supports two bitwise shift operators. They are shift left (<<) and shift right (>>). These operations are used to
shift bits to the left or to the right. The syntax for a shift operation can be given as follows:

Examples:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


66
Membership Operators
• Evaluates to find a value or a variable is in the specified sequence of string, list, tuple,
dictionary or not.

• Let, x=[5,3,6,4,1]. To check particular item in list or not, in and not in operators are used.
Identity Operators
• They are used to check if two values (or variables) are located on the same part of the
memory
Expressions- Operator Precedence

© Oxford University Press 2017. All rights reserved. 69


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.
Functions
• user defined function
• Built in function
• 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.
Functions
Built in function Description
>>>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
User Defined Functions
• User defined functions are the functions that programmers create for
their requirement and use.
• These functions can then be combined to form module which can be
used in other programs by importing them.
• Advantages of user defined functions:
• Programmers working on large project can divide the workload by making
different functions.
• If repeated code occurs in a program, function can be used to include those
codes and execute when needed by calling that function.
Function definition: (Sub program)
• def keyword is used to define a function.
• Give the function name after def keyword followed by parentheses in
which arguments are given.
• End with colon (:)
• Inside the function add the program statements to be executed
• End with or without return statement
Function definition: (Sub program)
Syntax:
• def fun_name(Parameter1,Parameter2…Parameter n):
• statement1
• statement2…

• statement n
• return[expression]
Example:
• def my_add(a,b):
• c=a+b
• return c
Function Calling: (Main Function)
• Once we have defined a function, we can call it from another function, program
or even the Python prompt.
• To call a function we simply type the function name with appropriate
arguments.
Example:
• x=5
• y=4
• my_add(x,y)
Flow of Execution:
• 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.
Function Prototypes:
i) Function without arguments and without return type
• In this type no argument is passed through the function call and no output is return to main
function
• The sub function will read the input values perform the operation and print the result in the same
block
ii) Function with arguments and without return type
• Arguments are passed through the function call but output is not return to the main function
iii) Function without arguments and with return type
• In this type no argument is passed through the function call but output is return to the main
function.
iv) Function with arguments and with return type
• In this type arguments are passed through the function call and output is return to the main
function
Parameters and Arguments:
Parameters:
• Parameters are the value(s) provided in the parenthesis when we write function header.
• These are the values required by function to work.
• If there is more than one value required, all of them will be listed in parameter list
separated by comma.
• Example: def my_add(a,b):
Arguments:
• Arguments are the value(s) provided in function call/invoke statement.
• List of arguments should be supplied in same way as parameters are listed.
• Bounding of parameters to arguments is done 1:1, and so there should be same number
and type of arguments as mentioned in parameter list.
• Example: my_add(x,y)
RETURN STATEMENT
• The return statement is used to exit a function and go back to the place from where it was called.
• If the return statement has no arguments, then it will not return any values. But exits from function.
Syntax:
• return[expression]
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 Argument
Required Arguments: The number of arguments in the function call should match exactly
with the function definition.

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.
• def my_details( name, age ):
print("Name: ", name)
print("Age ", age)
return
my_details(age=56,name="george")
Output:
• Name: george
• Age 56
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“,age)
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
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.
• Once we import a module, we can reference or use to any of its functions or
variables in our code.
• There is large number of standard modules also available in python.
• Standard modules can be imported the same way as we import our user-defined
modules.
• Every module contains many function.
• To access one of the function , you have to specify the name of the module and the
name of the function separated by dot . This format is called dot notation.
Syntax
• import module_name
• module_name.function_name(variable)
Four Ways to Import Module

You might also like