100% found this document useful (1 vote)
106 views32 pages

Python Unit 2: Data Types & Features

The document provides an introduction to Python programming language. It discusses that Python is an interpreted, interactive, object-oriented programming language. It then covers Python features like being easy to learn and maintain, portable, extensible, free and open source. It also lists some applications that use Python. The document further discusses Python interpreter modes of interactive and script mode. It defines values and data types in Python including numbers, sequences (strings, lists, tuples), mappings and dictionaries. Finally, it covers variables and keywords in Python.

Uploaded by

Raj Kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
106 views32 pages

Python Unit 2: Data Types & Features

The document provides an introduction to Python programming language. It discusses that Python is an interpreted, interactive, object-oriented programming language. It then covers Python features like being easy to learn and maintain, portable, extensible, free and open source. It also lists some applications that use Python. The document further discusses Python interpreter modes of interactive and script mode. It defines values and data types in Python including numbers, sequences (strings, lists, tuples), mappings and dictionaries. Finally, it covers variables and keywords in Python.

Uploaded by

Raj Kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Poriyaalan Lecturer Notes

UNIT -II
DATA TYPES, EXPRESSIONS, STATEMENTS

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

Poriyaalan Lecturer Notes
 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
 Facebook, Drop box

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.

MODES OF PYTHON INTERPRETER:


Poriyaalan Lecturer Notes

Python Interpreter is a program that reads and executes Python code. It uses 2 modes of
Execution.
1. Interactive mode
2. Script mode
1. 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.

Drawback:
We can’t 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
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!
This is an example of a print statement. It displays a result on the screen. In this case, the result is
the words.
Poriyaalan Lecturer Notes

2. 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 [Link] and run the interpreter in script mode to execute the script.
Poriyaalan Lecturer Notes

 Integrated Development Learning Environment (IDLE):


 Is a graphical user interface which is completely written in Python.
 It is bundled with the default implementation of the python language and also comes
with optional part of the Python packaging.

 Features of IDLE:
 Multi-window text editor with syntax highlighting.
 Auto completion with smart indentation.
 Python shell to display output with syntax highlighting.

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:
Poriyaalan Lecturer Notes
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.
 There are three types of sequence data type available in Python, they are

1. Strings
2. Lists
3. Tuples

1. Strings
 A String in Python consists of a series or sequence of characters -
letters, numbers, and special characters.
Poriyaalan Lecturer Notes
 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:

 Positive indexing helps in accessing the string from the beginning


 Negative subscript helps in accessing the string from the end.
 Subscript 0 or –ve n(where n is length of the string) displays the first
element.
Example: A[0] or A[-5] will display “H”
 Subscript 1 or –ve (n-1) displays the second element.
Example: A[1] or A[-4] will display “E”

Operations on string:
i. Indexing
ii. Slicing
iii. Concatenation
iv. Repetitions
v. Member ship
Poriyaalan Lecturer Notes

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
Poriyaalan Lecturer Notes
Repetitions
Updation, Insertion, Deletion
Poriyaalan Lecturer Notes
3. 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:
Poriyaalan Lecturer Notes
Altering the tuple data type leads to error. Following error occurs when
user tries to do.
>>> t[0]="a"
Trace back (most recent call last):
File "<stdin>", line 1, in <module>
Type Error: 'tuple' object does not support item assignment

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.
Poriyaalan Lecturer Notes

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'

VARIABLES:

 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.
Poriyaalan Lecturer Notes

Assigning value to variable:

Value should be given on the right side of assignment operator(=) and variable
on left side.
>>>counter =45
print(counter)
Assigning a single value to several variables simultaneously:
>>> a=b=c=100
Assigning multiple values to multiple variables:
>>> a,b,c=2,4,"ram"

KEYWORDS:

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

IDENTIFIERS:

Identifier is the name given to entities like class, functions, variables etc.
in Python.
Poriyaalan Lecturer Notes
 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 (_).
 all are valid example.
 An identifier cannot start with a digit.
 Keywords cannot be used as identifiers.
 Cannot use special symbols like !, @, #, $, % etc. in our identifier.
 Identifier can be of any length.
Example:
Names like myClass, var_1, and this_is_a_long_variable

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.

Expressions:
-An expression is a combination of values, variables, and operators.
-A value all by itself is considered an expression, and also a variable.
Poriyaalan Lecturer Notes
So the following are all legal expressions:
>>> 42
42
>>> a=2
>>> a+3+2
7
>>> z=("hi"+"friend")
>>> print(z)
Hifriend
INPUT AND OUTPUT

INPUT: Input is data entered by user (end user) in the program.


In python, input () function is available for input.
Syntax for input() is:
variable = input (“data”)
Example:
>>> x=input("enter the name:") enter the name: george
>>>y=int(input("enter the number"))
enter the number 3
#python accepts string as default data type. conversion is required for type.
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 :
Poriyaalan Lecturer Notes

Example:
# This is a comment.
# This is a comment, too.
# I said that already.

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.
>>> (a, b, c, d) = (1, 2, 3)
ValueError: need more than 3 values to unpack

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:
Poriyaalan Lecturer Notes

Swap two numbers


a=2;b=3
print(a,b)
temp = a
a=b
b = temp
print(a,b)

Output:
(2, 3)
(3, 2)
>>>
-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 packing
-In tuple unpacking, the values in a tuple on the right are ‘unpacked’ into
the variables/names on the right:
>>> b = ("George", 25, "20000") # tuple packing
>>> (name, age, salary) = b # tuple unpacking
>>> name
'George'
>>> age
25
>>> salary
'20000'
-The right side can be any kind of sequence (string,list,tuple)
Poriyaalan Lecturer Notes

Example:
-To split an email address in to user name and a domain
>>> mailid='god@[Link]'
>>> name,domain=[Link]('@')
>>> print name
god
print (domain)
[Link]

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
Poriyaalan Lecturer Notes

Examples
a=10
b=5
print("a+b=",a+b)
print("a-b=",a-b)
print("a*b=",a*b)
print("a/b=",a/b)
print("a%b=",a%b)
print("a//b=",a//b)
print("a**b=",a**b)
Poriyaalan Lecturer Notes

Output:
a+b= 15
a-b= 5
a*b= 50
a/b= 2.0
a%b= 0
a//b= 2
a**b= 100000

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
Poriyaalan Lecturer Notes

Example
a=10
b=5
print("a>b=>",a>b)
print("a>b=>",a<b)
print("a==b=>",a==b)
print("a!=b=>",a!=b)
print("a>=b=>",a<=b)
print("a>=b=>",a>=b)

Output:
a>b=> True
a>b=> False
a==b=> False
a!=b=> True
a>=b=> False
a>=b=> True

Assignment Operators:

-Assignment operators are used in Python to assign values to variables.


Poriyaalan Lecturer Notes

Example
a = 21
b = 10
Poriyaalan Lecturer Notes
c=0
c=a+b
print("Line 1 - Value of c is ", c)
c += a
print("Line 2 - Value of c is ", c)
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)

Output
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52.0
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864
Poriyaalan Lecturer Notes
Logical Operators:
-Logical operators are the and, or, not operators.

Example
a = True
b = False
print('a and b is',a and b)
print('a or b is',a or b)
print('not a is',not a)

Output
x and y is False
x or y is True
not x is False

Bitwise Operators:

A bitwise operation operates on one or more bit patterns at the level of


individual Bits

Example:
Poriyaalan Lecturer Notes
Let x = 10 (0000 1010 in binary) and
y = 4 (0000 0100 in binary)

Example
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c=0
c = a & b; # 12 = 0000 1100
print "Line 1 - Value of c is ", c
c = a | b; # 61 = 0011 1101
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
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
Poriyaalan Lecturer Notes

Output
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15

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.

Example:
x=[5,3,6,4,1]
>>> 5 in x
True
>>> 5 not in x
False
Poriyaalan Lecturer Notes
Identity Operators

They are used to check if two values (or variables) are located on the same
part of the memory.

Example
x=5
y=5
x2 = 'Hello'
y2 = 'Hello'
print(x1 is not y1)
print(x2 is y2)

Output
False
True
Poriyaalan Lecturer Notes
OPERATOR PRECEDENCE:

When an expression contains more than one operator, the order of


evaluation depends on the order of operations.

-For mathematical operators, Python follows mathematical convention.

-The acronym PEMDAS (Parentheses, Exponentiation, Multiplication, Division,


Addition, Subtraction) is a useful way to remember the rules:
Poriyaalan Lecturer Notes
 Parentheses have the highest precedence and can be used to force an
expression to evaluate in the order you want. Since expressions in
parentheses are evaluated first, 2 * (3-1)is 4, and (1+1)**(5-2) is 8.

 You can also use parentheses to make an expression easier to read, as in
(minute *100) / 60, even if it doesn’t change the result.

 Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27,


and 2 *3**2 is 18, not 36.

 Multiplication and Division have higher precedence than Addition and
Subtraction. So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.

 Operators with the same precedence are evaluated from left to right
(except exponentiation).

Example:
a=9-12/3+3*2-1
a=?
a=9-4+3*2-1
a=9-4+6-1
a=5+6-1
a=11-1
a=10

A=2*3+4%5-3/2+6
A=6+4%5-3/2+6
A=6+4-3/2+6
A=6+4-1+6
A=10-1+6
A=9+6
A=15
Poriyaalan Lecturer Notes

find m=?
m=-43||8&&0||-2
m=-43||0||-2
m=1||-2
m=1

a=2,b=12,c=1
d=a<b>c
d=2<12>1
d=1>1
d=0

a=2,b=12,c=1
d=a<b>c-1
d=2<12>1-1
d=2<12>0
d=1>0
d=1

a=2*3+4%5-3//2+6
a=6+4-1+6
a=10-1+6
a=15
Poriyaalan Lecturer Notes

OUTPUT: Output can be displayed to the user using Print statement .


Syntax:
print (expression/constant/variable)
Example:
print ("Hello") Hello

PROGRAMS:

Python program to swap two variables


# To take input from the user
x = input('Enter value of x: ')
y = input('Enter value of y: ')
#x = 5
#y = 10
# create a temporary variable and swap the values
x=x+y
y=x-y
x=x+y
print 'The value of x after swapping:’,x
print 'The value of y after swapping:’,y

Output

The value of x after swapping: 10


The value of y after swapping: 5
Poriyaalan Lecturer Notes
Without Using Temporary Variable
In Python, there is a simple construct to swap variables. The following code does the same as
above but without the use of any temporary variable.

x = 5
y = 10

x, y = y, x
print("x =", x)
print("y =", y)

Distance between two points


import math
p1 = [4, 0]
p2 = [6, 6]
distance = [Link]( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2) )
print(distance)

Program to circulate the values of n variables


from collections import deque
lst=[1,2,3,4,5]
d=deque(lst)
print d
[Link](2)
print d
Output:[3,4,5,1,2]
(OR)
list=[10,20,30,40,50]
n=2 #Shift 2 location
list[n:]+list[:n]
Output: [30,40,50,10,20]

Common questions

Powered by AI

Python implements bitwise operations to work at the level of individual bits within integer data types. These operations include AND (`&`), OR (`|`), XOR (`^`), NOT (`~`), left shift (`<<`), and right shift (`>>`). They serve purposes such as low-level data manipulation, efficient performance optimization due to direct manipulation at the bit level, and specific algorithm implementations, like cryptography or network data packet handling that require bitwise precision .

Python uses the hash sign (`#`) to denote comments. Anything following the `#` on that line is ignored by the interpreter, which is useful for leaving human-readable explanations or disabling code. However, Python lacks built-in syntax for multi-line comments like those in other programming languages (e.g., `/* */` in C). Instead, each line must be individually commented. This can be cumbersome for lengthy documentation but it ensures that every part of a large block of code is explicitly considered during commenting .

Keywords in Python are reserved words that have special meaning and are used to define the language's structure and syntax, like `if`, `while`, `for`, etc. They cannot be used for variable names or identifiers. Identifiers, on the other hand, are names that programmers assign for variables, functions, classes, etc., and must adhere to Python's naming rules, such as not starting with a digit and avoiding special characters except the underscore. Identifiers are case sensitive and can vary in length .

Operator precedence affects the execution of code by determining the order in which operations are performed, which is particularly crucial when expressions involve multiple operators. In Python, parentheses have the highest precedence, followed by exponentiation, then multiplication and division, and finally addition and subtraction. For example, consider the expression `2 + 3 * 4`. The multiplication is performed before the addition, resulting in `2 + (3 * 4) = 14`, not `(2 + 3) * 4 = 20`. Correct understanding of precedence is critical for writing accurate expressions .

In Python, strings are immutable, meaning the contents cannot be changed after they are created. Thus, operations like concatenation and slicing result in the creation of new strings rather than modifying the existing one. This immutability facilitates memory optimization techniques like string interning that allow Python to use the same memory space for identical strings, enhancing performance and reducing memory usage. However, it also means operations that seem to modify strings need to handle the creation of new strings, which can impact performance if done excessively .

When attempting to access a non-existent key in a Python dictionary, a `KeyError` is raised. This exception can be managed using techniques such as the `try` and `except` blocks to catch the exception and handle it gracefully, for example, by providing a default value. Another approach is to use the dictionary's `get()` method, which returns `None` or a specified default value when a key is not found, thus avoiding the `KeyError`. These techniques help in writing robust code that can handle such errors efficiently .

The key differences between lists and tuples in Python are that lists are mutable, meaning their contents can be changed after creation, whereas tuples are immutable and cannot be altered once created. Lists are defined using square brackets, while tuples are created with parentheses. Tuples are generally faster than lists, and because they are immutable, they can be used as keys in dictionaries, unlike lists. This ensures data stability where required .

Operator precedence determines the order in which operations within an expression are evaluated, impacting the final output, while associativity decides the order operators of the same precedence level are processed. Python follows a standard precedence similar to mathematical convention with parentheses taking the highest precedence followed by exponentiation, etc. For instance, `3 + 2 ** 2` evaluates as `3 + 4` due to exponentiation precedence, yielding `7`. For operators of the same level, left-to-right associativity means `10 - 5 + 3` is evaluated as `(10 - 5) + 3`. Misunderstanding precedence and associativity can lead to incorrect results or logic errors in programs .

In Python, variable assignment allows a value to be stored in a name, which can later be used to reference that value. Variables in Python are dynamically typed, meaning that they do not require an explicit type declaration and can hold different data types over their lifetime. The language supports assignments like multiple variables being assigned a single value (e.g., `a = b = c = 100`) and multiple values to multiple variables simultaneously (e.g., `a, b, c = 1, 2, 'abc'`). This flexibility permits efficient memory use and versatile data manipulation .

Python defaults to certain data types, such as treating input data as strings. This behavior necessitates explicit type conversion for computations involving other types. Mechanisms such as `int()`, `float()`, and `str()` functions are provided for converting values to desired data types. For instance, to handle user input for arithmetic operations, developers must convert strings to integers or floats manually. This conversion process ensures that data is handled appropriately for the context, preventing common runtime errors like performing arithmetic on strings .

You might also like