24cse402 Unit II Notes 1
24cse402 Unit II Notes 1
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.
1.1. 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.
1.2. Applications:
❖ Bit Torrent file sharing
❖ Google search engine, Youtube
❖ Intel, Cisco, HP, IBM
❖ i–Robot
❖ NASA
❖ Facebook, Drop box
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
This is an example of a print statement. It displays a result on the screen. In this case, the
result is the words
2 24CSE402 - Unit 2: Data types, expressions, Statements
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.
Debugging
❖ Bug: An Error in a Program.
❖ Debugging: The Process of finding and removing any of the three kinds of
programming errors.
❖ Syntax: The Structure of a program
3 24CSE402 - Unit 2: Data types, expressions, Statements
❖ Syntax Error: An Error in a program that makes it impossible to parse (and
therefore impossible to 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.
2. VALUES AND DATA TYPES
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:
2.1 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,
2.2 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.
4 24CSE402 - Unit 2: Data types, expressions, Statements
❖ There are three types of sequence data type available in Python, they are
1. Strings
2. Lists
3. Tuples
2.2.1 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.
Indexing:
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
2.2.4Tuple:
❖ 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.
2.3 Mapping
-This data type is unordered and mutable.
-Dictionaries fall under Mappings.
2.3.1 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.
3.7 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
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)
+= 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)
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
Example:
x=[5,3,6,4,1]
>>> 5 in x
True
>>> 5 not in x
False
Example
x=5 Output
y=5 False
x2 = 'Hello' True
y2 = 'Hello'
print(x1 is not y1)
print(x2 is y2)
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