Unit 2
Unit 2
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".
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 :
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
>>> type(phonebook1)
<class 'set'>
Duplicate Removal
• If we had defined a set with duplicate items, they
would be ignored:
'123-45-67', '345-67-89'}
>>> phonebook1
** (POWER) 2**4 = 16
A**B
%= 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
A+B*C A+B*C
AX2+BX+C A * ( X ** 2 ) + B * X + C
4AC/2A (4 * A * C ) / 2 * A
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
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
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)
Output :
['1', '2', '3', '4']
['2', '3', '4', '1']
['3', '4', '1', '2']
['4', '1', '2', '3']