0% found this document useful (0 votes)
26 views

Unit 2

Uploaded by

selvaprabhu.t
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Unit 2

Uploaded by

selvaprabhu.t
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 83

UNIT II

DATA TYPES, EXRESSIONS


AND STATEMENTS
Help in Python
>>> help()
Welcome to Python 3.6's help utility!

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/3.6/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, symbols, or topics, type


"modules", "keywords", "symbols", or "topics". Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".
Steps to learn python
• Constants ,variables and data types
• Identifiers and keywords , Operators
• Control flow and functions
• Lists , Tuples and Dictionaries
• Files , Modules and Packages
Introduction to PYTHON
• Python is a general-purpose interpreted,
interactive, object-oriented, and high-level
programming language.
• Python was developed by Guido Van Rossam in 1989
while working at National Research Institute at
Netherlands.
• Python got its name from “Monty Python’s flying
circus”.
• Python was released in the year 1991
• Python is recommended as first programming
language for beginners.
PYTHON NAME
• Monty Python’s Flying Circus is a
British sketch comedy series created by the
comedy group Monty Python and broadcast by
the BBC from 1969 to 1974.
Python and its applications
• Python is interpreted
• Python is Interactive
• Python is Object-Oriented
• Python is a Beginner's Language
Python Applications :
• Bit Torrent file sharing
• Google search engine, Youtube
• Top companies using python - Intel, Cisco,
HP, IBM , Google, microsoft, Yahoo
• i–Robot and NASA
Python Features:
• Easy-to-learn:
• Easy-to-maintain
• Portable
• Interpreted
• Extensible
• Free and Open Source
• High Level Language
• Scalable
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
• 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.
Drawback:
We cannot save the statements and have to
retype all the statements once again to re-run
them.
EG : In interactive mode, you type Python
programs and the interpreter displays the
result: >>> 1 + 1 2
>>> print ('Hello, World!') Hello, World!
Integrated Development Learning
Environment (IDLE):
• 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.
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.
Ex : Script mode
Interactive mode Script mode
• A way of using the • A way of using the
Python interpreter by Python interpreter to
typing commands and read and execute
expressions at the statements in a script.
prompt. • Can save and edit the
• Cant save and edit the code
code
• If we are very clear
• If we want to about the code, we can
experiment with the use script mode.
code, we can use
interactive mode. • We can’t see the code
and results
• We can see the results
immediately.
immediately.
• Debugging is the process of detecting and
removing of existing and potential errors (also
called as ‘bugs’) in a software code that can
cause it to behave unexpectedly or crash. To
prevent incorrect operation of a software or
system, debugging is used to find and resolve
bugs or defects.
• When various subsystems or modules are
tightly coupled, debugging becomes harder as
any change in one module may cause more
bugs to appear in another. Sometimes it takes
more time to debug a program than to code it.
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 data types.)

Data type
Every value in Python has a data type. It is a
set of values, and the allowable operations on
those values.
Data Types
>>>type('Hello, World!')
<type 'str'>

>>> type(17)
<type 'int'>

>>> type(3.2)
<type 'float‘>

>>>type(‘H')
<type 'str'>
Python has five standard data
types
Numbers
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
Variables, Expressions, Statements
• 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.
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.
• 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
and Logical and (3 == 4 )and (5==5)
or Logical or not True == False
not Logical not (3 == 4 )or(5==5)
break Stop this loop right now while true: break
continue Continue the loop while true: continue
def Define a function def a(): a= a+1
del Delete from dictionary del A[y]
If If condition if A: statements
elif Else if condition elif b: Statements
else Else condition else: statements
for For loop for A in B: print(a)
from Get specific parts from A import B
import Import a module import os
in Part of loops for X in Y
is Check for “==“ 1 is 1 == True
print Print the value or string print(‘XYZ’)
return Return value from a function def A(): return a
while While loop while A: a= a+1
IDENTIFIERS
• 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 (_)
• 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.
Identifiers :
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)
17
Expressions
• An expression is a combination of values,
variables, and operators.
• So the following are all legal expressions:
>>> 42
42
>>> a=2
>>> a+3+2 7
>>> z=("hi"+"friend")
>>> print(z) hifriend
INPUT
• Input is data entered by user in the
program.
• In python, input () function is available for
input.
• Syntax for input() is:
• variable = input (“data”)
• >>> x=input("enter the name:")
enter the name: george
• >>>y=int(input("enter the number"))
enter the number 3
OUTPUT
• Output can be displayed to the user using
Print statement .
• Syntax: print
(expression/constant/variable)
Example:
• >>> print ("Hello")
• Hello
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.
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.
Example :
a=3
b=1
if a>b:
print("a is greater")
else:
print("b is greater")
Docstring and Quotation
• Docstring is short for documentation string.
• Triple quotes(""" """) Eg- This is a paragraph. It is
made up of multiple lines and sentences.""“

QUOTATION IN PYTHON:
• 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.""
Strings
• A String in Python consists of a series or sequence
of characters - letters, numbers, and special
characters.
• Strings are immutable i.e. the contents of the string
cannot be changed after it is created.
• Individual character in a string is accessed using a
subscript (index).
• Characters can be accessed using indexing and
slicing operations
• ‘ and “ – string in quotes
• ””” – paragraph in quotes
String indexing
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. List are mutable.
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 .
• once a tuple has been created, you can't add
elements to a tuple or remove elements
from the tuple.
Tuple assignment
• It is often useful to swap the values of two
variables. With conventional assignments,
youhave to use a temporary variable. For
example, to swap a and b :

• This solution is cumbersome; tuple


assignment is more elegant:
• >>a,b=b,a
Sequence Operations in Python
Dictionary
• A dictionary is like a list, but more general.

d={“Name”:“Python”, “Type”:“Programming”}
• Each key is separated from its value by a colon (:).
• The items are separated by commas.
• The whole thing is enclosed in curly braces.
• Dictionaries fall under Mappings.
• Keys must be unique within a dictionary.
• Dictionary is mutable.
• keys must be immutable.
Key-Value Pair
• A dictionary contains a collection of indices, which are called keys,
and a collection of values.
• Each key is associated with a single value. The association of a key
and a value is called a key-value pair or sometimes an item.
• Eg:
>>>days = {'Mo': 'Monday', 'Tu': 'Tuesday', 'We': 'Wednesday',
'Th': 'Thursday'}
>>>days.keys()
>>>dict_keys(['Mo', 'Tu', 'We', 'Th'])
>>> days['Mo']
>>>'Monday'
>>>print(days.items())
>>>dict_items([('Mo', 'Monday'), ('Tu', 'Tuesday'), ('We', 'Wednesday'),
('Th', 'Thursday')])
Class set
• Another built-in Python container type is the set class. The
set class has all the properties of a mathematical set.
• It is used to store an unordered collection of items, with
no duplicate items allowed.
• The items must be immutable objects.
• The set type supports operators that implement the classical
set operations: set membership, intersection, union,
symmetric difference, and so on.
• It is also useful for duplicate removal.
Representation
• A set is defined as a sequence of items separated by
commas and enclosed in curly braces: { }
• Eg: assign the set of three phone numbers (as strings) to
variable phonebook1:

>>> phonebook1 = {'123-45-67', '234-56-78', '345-67-89'}

>>> phonebook1

{'123-45-67', '234-56-78', '345-67-89'}

>>> type(phonebook1)

<class 'set'>
Duplicate Removal
• If we had defined a set with duplicate items, they
would be ignored:

>>> phonebook1={'123-45-67','234-56-78', '345-67-89',

'123-45-67', '345-67-89'}

>>> phonebook1

{'123-45-67', '234-56-78', '345-67-89'}


Lists with Sets
• Suppose we have a list with duplicates, such as this list of
ages of students in a class:
>>> ages = [23, 19, 18, 21, 18, 20, 21, 23, 22, 23, 19, 20]
• To remove duplicates from this list, we can convert the list
to a set, using the set constructor.
• By converting the set back to a list, we get a list with no
duplicates:
>>> ages = list(set(ages))
>>> ages
[18, 19, 20, 21, 22, 23]
OPERATORS
• Arithmetic Operators
• Relational Operators
• Equality Operators
• Logical operators
• Bitwise Operators
• Shift Operators
• Assignment Operators
• Special Operators (Membership and Identity)
• Ternary or conditional Operator
• Boolean Operators
1. ARITHMETIC OPERATOR 2. RELATIONAL OPERATOR
+ A+B
== X==Y True
- A-B != X!=Y False

* A*B > X>Y True


< X<Y False
/ A/B
>= X>=Y True
% A%B <= X<=Y False

** (POWER) 2**4 = 16
A**B

// (FLOOR DIVISION) 9//2 = 4


Returns only the Whole part 9.0//2 = 4.0
in the quotient and removes -11//3 = -3
the decimal part -11.0//3= 3.0
4. Logical Operators
7. Assignment Operator
and Logical AND (X and Y) True
Variable=Expression or Value
Or Logical OR (X or Y) True
= Z=X+Y
Not Logical NOT A=None
Not(A) True += Y+=X Y=Y+X
5. Bitwise Operators: -= Y-=X Y=Y-X
A bitwise operation operates on one
or more bit patterns at the level of *= Y*=X Y=Y*X
individual bits
/= Y/=X Y=Y/X

%= Y%=X Y=Y%X

**= Y**=X
Y=Y**X
//= Y//=X
Y=Y//X
9. Special Operators:
Membership Operator Identity Operator
>>> c a=['hello',95,'world',96]
['abc', 'xyz', 'mnl', 65,'hgf‘, c=['abc', 'xyz', 'mnl', 65,'hgf‘, 'znm']
'znm']

is
in >>> a is c
>>> 'abc' in c False
True

is not
not in
>>> a is not c
>>>'bgt' not in c
True
True
10. Boolean Operator

a=10, b=40

and a and b -> False


or a or b -> True
not not a -> False
Expressions
Syntax:
Variable=Expression
c=a+b
c=(a/b)*d
Expression is solved and stored in c RIGHT to
LEFT
ALGEBRIC EXPRESSION PYTHON EXPRESSION

A+B*C A+B*C

AX2+BX+C A * ( X ** 2 ) + B * X + C

4AC/2A (4 * A * C ) / 2 * A

(2X2/B)-C ((2 * (X **2) ) / B) - C


Precedence of operators:
• If multiple operators present then which
operator will be evaluated first is
decided by operator precedence.
Precedence of operators:
PRECEDENCE OPERATORS
HIGH * / %
LOW + -

PEMDAS (Parentheses, Exponentiation,


Multiplication, Division, Addition, Subtraction)

P - Parantheses first
E - Exponents (powers, Square roots……,)
MD - Multiplications and Divisions ( Left to Right)
AS - Addition and Subtraction ( Left to Right)
The following list describes operator precedence in
Python:
1) () - Parenthesis
2) ** - Exponential Operator
3) ~, - - Bitwise Complement Operator, Unary Minus Operator
4) *, /, %, // - Multiplication, Division, Modulo, Floor Division
5) +, - - Addition, Subtraction
6) <<, >> - Left and Right Shift
7) & - Bitwise And
8) ^ - Bitwise X-OR
9) | - Bitwise OR
10) >, >=, <, <=, ==, != - Relational OR Comparison Operators
11) =, +=, -=, *=... - Assignment Operators
12) is, is not - Identity Operators
13) in , not in - Membership operators
14) not - Logical not
15) and - Logical and
16) Or - Logical or
Example
X–Y/3+Z*3–1 3 - 9/3 + 77*3 - 1

X=3, Y=9, Z=77 3 231

S=3- 9 / 3 + 77 * 3 – 1 0

S=230 231

230
Examples
• A=2*3+4%5-3/2+6 True = 1
• A=6+4%5-3/2+6 False = 0
• A=6+4-3/2+6
• A=6+4-1+6 • a=2,b=12,c=1
• A=10-1+6 • d=a<b>c
• A=9+6 • d=2<12>1
• A=15 • d=1>1
• d=0
FUNCTIONS
Function
• A function is a block of organized, reusable code
that is used to perform a single, related action.
• Produces modularity.
Functions

User Defined Built-in Function /


Functions Library Function
Built In Functions
• Predefined library function that is not required to be
written by the programmer again:
• abs()  Produces only positive values
• input()  reads user input
• int()  converts to integer datatype
• str()  converts to string datatype
• pow()  computes exponentiation
• sum()  adds all values inside it
• print()  displays the result
• float()  converts to float datatype
Built In Functions – Examples
Function Syntax – User defined Function
Function Definition Syntax:
def function_name( parameters separated by commas):
Statement1
Statement2
...
return [expression or single variable]
Example:
#Function Definition #Function Call
def add(a): >>> add(5)
a=a+2 >>> 7
return a or within the same code:
print(add(5))
>>> Restart ….
>>> 7
Module
calci.py
def add(a,b): def sub(a,b): def pdt(a,b): def div(a,b):
c=a+b c=abs(a-b) c=a*b c=a/b
print(c) print(c) print(c) print(c)

def
def mod(a,b): def exp(a,b):
floordiv(a,b):
c=a%b c=a**b
c=a//b
print(c) print(c)
print(c)

• These functions are written together in a single


python program as calci.py
import calci
a=int(input(“Enter a number”)) inputfile.py – import
b=int(input(“Enter a number”))
statement
print(“1. add 2. sub 3.product 4.division 5. floor division 6. modulo 7. exponentiation”)
ch=int(input(“Enter your choice of operation:”))
if(ch==1):
calci.add(a,b)
elif(ch==2):
calci.sub(a,b)
elif(ch==3):
calci.pdt(a,b)
elif(ch==4):
calci.div(a,b)
elif(ch==5):
calci.floordiv(a,b)
else:
break
print(“Thanks for using our aplication.!!!”)
import calci
a=int(input(“Enter a number”))
b=int(input(“Enter a number”))
calci.add(a,b)
calci.sub(a,b)
calci.pdt(a,b)
calci.floordiv(a,b)
calci.mod(a,b)
calci.exp(a,b)
Illustrative Pbms
Program for SWAPPING(Exchanging )of values
a = int(input("Enter a value "))
b = int(input("Enter b value "))
c=a
a=b
b=c
print("a=",a,"b=",b,)
Illustrative Pbms
Program to find distance between two points
import math
x1=int(input("enterx1"))
y1=int(input("enter y1"))
x2=int(input("enter x2"))
y2=int(input("enter y2"))
distance =math.sqrt((x2-x1)**2)+((y2- y1)**2)
print(distance)
Illustrative Pbms
Program to circulate n numbers
a=[1,2,3,4]
print(a)
for i in range(1,len(a),1):
print(a[i:]+a[:i])

Output :
['1', '2', '3', '4']
['2', '3', '4', '1']
['3', '4', '1', '2']
['4', '1', '2', '3']

You might also like