[go: up one dir, main page]

0% found this document useful (0 votes)
12 views76 pages

18mit14c U1

Wwwww

Uploaded by

zekulav1hos2
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
0% found this document useful (0 votes)
12 views76 pages

18mit14c U1

Wwwww

Uploaded by

zekulav1hos2
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
You are on page 1/ 76

prepared by S.

Radha Priya 1
PYTHON PROGRAMMING

prepared by S.Radha Priya 2


PYTHON PROGRAMMING

Introduction
• Python is a high-level, interpreted, general purpose, dynamic
programming language.
• Python Started in late 1980’s and its usage began in Dec 1989.
• Python has the property of code termed reusability
• Python can be used in multiple programming styles, including object-
oriented, functional programming, procedural programming.
• Python can be used on any OS.
• Python is free and open-source Software
Python Overview
The key features are
• The code written in python is automatically compiled to byte code and
executed.
• It can be used as a scripting language, for implementing web applications
• Extending python with C and C++ increase the performance and speed of
execution.

prepared by S.Radha Priya 3


• Python supports nested code block, functions, classes, modules and
packages.
• Python makes use of object-oriented programming approach.
Additional Features
• It has built in data types:
Strings, Lists, Tuples, Dictionaries
• It supports Control Statements
If, if-else, if-elif-else, while, iterative, etc.,
• Use of functions, classes, modules and packages.
Getting Started with Python
3-different ways of starting python.
1. Running a script written in python: we will create scripts and execute them
using the text editor.
2. Using a Graphical user interface(GUI): we require GUI application, that
comes with python installer itself.
3. Employing an interactive approach: This approach is used in the book
prepared by S.Radha Priya 4
3 types of Environments

• Text Editors
• Full IDEs(integrated Development Environment)
• Notebook Environments
Text Editors
• General editors for any text file
• Sublime text and atom(popular editors)
• Sublime text editor – www.sublimetext.com

Full IDEs
• Development environment designed specifically for python
• Larger programs
• Only Community editions are free
• Designed specifically for python, lots of extra functionality
• Most popular pycharm and spyder

prepared by S.Radha Priya 5


Notebook Environments
• Great for learning
• See input and output next to each other
• Support inline markdown notes, visualizations, videos and more
• Special file formats that are not in .py
• Most popular is jupyter notebook

prepared by S.Radha Priya 6


INSTALLING PYTHON INTERPRETER
1. Download the python installer from the link:
https://www/python.org/downloads/
2. Double click on the installer, installation begins
3. Choose install for all users and click next>
4. Choose the directory for installing python, click next>
5. Select the package click next>
6. If the installation process in complete, click on finish to exit the installer.
Steps to Run Python
1. Click START button
2. Go to All programs
3. Search for python 2.7 folder
4. Click python[command line]
Python interpreter prompt >>> (or)
Python cherron prompt

prepared by S.Radha Priya 7


https://repl.it/languages/python?v2=1 - python prompt

• >>> prompt indicates python interpreter is waiting for an expression or


command. This interactive interpreter is called console or command shell.
• Interacting with the interpreter by entering simple expression.
>>>8+9 → press enter key
17
>>> print “Hello”
Hello

PYTHON COMMENTS #
• Comments can be used to explain Python code.
• Comments can be used to make the code more readable.
• Comments can be used to prevent execution when testing code.
Comments starts with a #, and Python will ignore them:
Ex:
>>>#This is a comment
>>>print("Hello, World!")
Hello World!
>>>8+9#addition
17
prepared by S.Radha Priya 8
PYTHON IDENTIFIER
An identifier is a name given to entities like class, functions, variables, etc. It
helps to differentiate one entity from another.
Rules for writing identifiers
1. 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 _
2. An identifier cannot start with a digit.
3. Keywords cannot be used as identifiers.
4. We cannot use special symbols like !, @, #, $, % etc. in our identifier
Ex: Valid identifier
MyName
My_Name
Your_name
print_this_to_screen
Invalid identifier
1variable = invalid
a@=invalid

prepared by S.Radha Priya 9


RESERVED /KEYWORDS
Python Keywords
• Keywords are the reserved words in Python.
• We cannot use a keyword as a variable name, function name or any other
identifier. They are used to define the syntax and structure of the Python
language.
• In Python, keywords are case sensitive.

False await else import pass

None break except in raise

True class finally is return

and continue for lambda try

as def from nonlocal while


assert del global not with

async elif if or yield


prepared by S.Radha Priya 10
VARIABLES

• Variables are containers for storing data values.


• Unlike other programming languages, Python has no command for
declaring a variable.
• A variable is created the moment you first assign a value to it.
• Format: variable=expression
Ex:
>>>x = 5
>>>y = "John"
>>>x
5
>>>y
john
>>>z=y
>>>z
john

prepared by S.Radha Priya 11


STANDARD DATA TYPES
• A data type is the classification of the type of values that can be assigned to
variables.
• we don’t need to declare a variable with explicitly mentioning the data type,
but it’s still important to understand the different types of values that can be
assigned to variables in Python.
Python data types are categorized into two as follows:
Mutable Data Types: Data types in python where the value assigned to a
variable can be changed
Immutable Data Types: Data types in python where the value assigned to a
variable cannot be changed.

prepared by S.Radha Priya 12


• Numbers:The number data type in Python is used to store numerical values. It
is used to carry out the normal mathematical operations.

• Strings:Strings in Python are used to store textual information. They are used
to carry out operations that perform positional ordering among items.

• Lists:The list data type is the most generic Python data type. Lists can consist
of a collection of mixed data types, stored by relative positions.

• Tuples:Tuples are one among the immutable Python data types that can store
values of mixed data types. They are basically a list that cannot be changed.

• Sets:Sets in Python are a data type that can be considered as an unordered


collection of data without any duplicate items.

• Dictionaries:Dictionaries in Python can store multiple objects, but unlike lists,


in dictionaries, the objects are stored by keys and not by positions.
prepared by S.Radha Priya 13
CATEGORIES OF NUMBER DATA TYPE/NUMERIC

The number data type is divided into the following five data types:
• Integer
• Long Integer
• Octal and Hexadecimal
• Floating-point Numbers
• Complex Numbers
Integers in Python
Python integers are nothing but whole numbers, whose range dependents on
the hardware on which Python is run. Integers can be of different types such
as positive, negative, zero, and long.
Example:
I = 123 #Positive Integer
J = -20 #Negative Integer
K=0 #Zero Integer

prepared by S.Radha Priya 14


Long Integers
L suffix is used for the representation of long integers in Python. Long integers
are used to store large numbers without losing precision.
Ex: I = 99999999999L

Octal and Hexadecimal in Python


To represent the octal number which has base 8 in Python, add a preceding 0
(zero) so that the Python interpreter can recognize that we want the value to
be in base 8 and not in base 10.
Example:

#Then in Octal we will write –


I = 011
print (I)
Output: 9

prepared by S.Radha Priya 15


Floating-point Numbers in Python

Floating-point numbers symbolize the real numbers that are written with a
decimal point dividing the integer and fractional parts.
Floating-point numbers may also come with scientific notation with E or e,
indicating the power of 10.
Example:
5.6e2
I = 2.5
J = 7.5e4

prepared by S.Radha Priya 16


Example:
a = 3.5
b=2
c = -3.5
a = int(a)
print (a)
b = float(b)
print (b)
c = int(c)
print (c)
Output:
3
2.0
-3

prepared by S.Radha Priya 17


STRING
• Python string is an ordered collection of characters which is used to
represent and store the text-based information.
• Strings are stored as individual characters in a contiguous memory
location. It can be accessed from both directions: forward and backward.
• Characters are nothing but symbols.
• Strings are immutable Data Types in Python, which means that once a
string is created, they cannot be changed.
Creating a String in Python
In Python, strings are created using either single quotes or double quotes. We
can also use triple quotes, but usually triple quotes are used to create
docstrings or multi-line strings.
#creating a string with single quotes
Output: Python
String1 = ‘Python’
print (String1)
#creating a string with double quotes
String2 = “Programming” Output:Programming
Print (Strings2) prepared by S.Radha Priya 18
Accessing Python String Characters
In Python, the characters of string can be individually accessed using a method
called indexing.
Characters can be accessed from both directions: forward and backward. Forward
indexing starts form 0, 1, 2…. Whereas, backward indexing starts from −1, −2,
−3…, where −1 is the last element in a string, −2 is the second last, and so on.
The integer number type for indexing; otherwise, the Type Error will be raised.
Example:
String1 = ‘intelligent’
print (String1)
print (String1[0])
print (String1[1])
print (String1[-1])
Output: intelligent
i
n
t

prepared by S.Radha Priya 19


Example:
#Python code to update an entire string
String1 = ‘Python Programming’
print (“original string: “)
print (String1)
String1 = ‘Welcome to the Class’
print (“Updated String: “)
print (String1)
Output:
Original String:
Python Programming
Updated String:
Welcome to the Class

prepared by S.Radha Priya 20


List in Python
• Lists are Python’s most flexible ordered collection object type.
• It can also be referred to as a sequence that is an ordered collection of
objects that can host objects of any data type, such as Python
Numbers, Python Strings and nested lists as well.
• Lists are one of the most used and versatile Python Data Types.
• A list can be created by putting the value inside the square bracket, and
values are separated by commas.
List_name = *value1, value2, …, value n+
Unlike strings, lists can contain any sort of objects: numbers, strings, and
even other lists.
Example:
list1 = [1,2,3,4,5]
list2 = *“hello”, “priya”+
One-dimensional Lists in Python:
init_list = [0]*3
print(init_list)
Output: [0, 0, 0]
prepared by S.Radha Priya 21
Two-dimensional Lists In Python:

two_dim_list = [ [0]*3 ] *3
print(two_dim_list)
Output: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
Three-dimensional Lists in Python:
two_dim_list = [[ [0]*3 ] *3]*3
print(two_dim_list)
Output:
[[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]]
Example
List = [1,2,3,4,5]
List1 = [ i for i in range(5)]
print(List1)
Output: [0, 1, 2, 3, 4]

prepared by S.Radha Priya 22


Example
print ([a+b for a in ‘mug’ for b in ‘lid’+)
Output:
*‘ml’, ‘mi’, ‘md’, ‘ul’, ‘ui’, ‘ud’, ‘gl’, ‘gi’, ‘gd’+
Example
list_fruit = *“Apple”,”Mango”,”Banana”,”Avocado”+
first_letters = [ fruits[0] for fruits in list_fruit ]
print(first_letters)
Output:
*‘A’, ‘M’, ‘B’, ‘A’+
TUPLE
• Tuple data type in Python is a collection of various immutable Python
objects separated by commas
• A Python tuple is created using parentheses around the elements in the
tuple

prepared by S.Radha Priya 23


• Elements in the tuple can be of different data types or of the same data
type
• A tuple in Python can have any number of elements.
Example
tup1 = (‘Intelligent’, ‘ Python’, ‘Programming’)
tup2 = 1,2,3,4
Print (tup1)
print (tup2)
Output:
(‘Intelligent’, ‘ Python’, ‘Programming’)
(1,2,3,4)
Ex:
tup1 = (‘Intelligent’, ‘Python’, ‘programming’)
print (tup1[0])
Output:
Intelligent

prepared by S.Radha Priya 24


Dictionary in Python
• Python dictionary is yet another unordered collection of elements.
• Python dictionaries can also be changed and modified
• Dictionaries are accessed using keys and not by their positions. All the
keys in a dictionary are mapped to their respective values. The value can
be of any data type in Python.
Create a Dictionary in Python-Rules
• The keys are separated from their respective values by a colon (:) between
them, and each key–value pair is separated using commas (,).
• All items are enclosed in curly braces.
• While the values in dictionaries may repeat, the keys are always unique.
• The value can be of any data type, but the keys should be of immutable
data type, that is, (Python Strings, Python Numbers, Python Tuples).
Example
dict1 =,“Brand”:”gucci”,”Industry”:”fashion”,”year”:1921-
print (dict1)
Output:
,‘Brand’: ‘gucci’, ‘Industry’: ‘fashion’, ‘year’: 1921-

prepared by S.Radha Priya 25


SETS
A set in Python is mutable, iterable, and does not have any duplicate
elements.
It is an unordered collection of elements which means that a set is a
collection that stores elements of different Python Data Types.
Sets in Python are usually used to perform some mathematical functions such
as union, intersection, etc.
• In Python sets, elements don’t have a specific order.
• Sets in Python can’t have duplicates. Each item is unique.
Using commas to separate and curly braces to group elements
myset = ,“apple”, “banana”, “cherry”-
print(myset)
Output:
,‘cherry’, ‘banana’, ‘apple’-
Intersection: Elements two sets have in common.
Union: All the elements from both sets.
Difference: Elements present on one set, but not on the other.
Symmetric Difference: Elements from both sets, that are not present on the
other. prepared by S.Radha Priya 26
OPERATORS
Operators are constructs used to modify the values of operands.
Ex: 3+4=7
Seven types of operators:
1. Arithmetic operator
2. Comparison operator
3. Logical operator
4. Bitwise operator
5. Membership operator
6. Identity operator
7. Assignment operator

Arithmetic Operators
These operators are used to perform arithmetic operations such as
addition, subtraction, multiplication and division. Arithmetic operators are:

prepared by S.Radha Priya 27


Operator Description Example
+ Addition Adds values on either side of the operator. 10+20 = 30

- Subtraction Subtracts right hand operand from left hand a – b = -10


operand.
* Multiplies values on either side of the a * b = 200
Multiplication operator

/ Division Divides left hand operand by right hand b/a=2


operand
% Modulus Divides left hand operand by right hand b%a=0
operand and returns remainder

** Exponent Performs exponential (power) calculation on a**b =10 to the power 20


operators
// Floor Division - The division of operands 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3
where the result is the quotient in which the = -4.0
digits after the decimal point are removed.
But if one of the operands is negative, the
result is floored, i.e., rounded away from
zero (towards negative infinity) −
prepared by S.Radha Priya 28
a = 21
b = 10
c=0
c=a+b
print "Line 1 - Value of c is ", c
c=a-b
print "Line 2 - Value of c is ", c
c=a*b
print "Line 3 - Value of c is ", c
c=a/b
print "Line 4 - Value of c is ", c
c=a%b
print "Line 5 - Value of c is ", c
a=2
b=3
c = a**b
print "Line 6 - Value of c is ", c
a = 10
b=5
c = a//b
print "Line 7 - Value of c is ", c

prepared by S.Radha Priya 29


Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 8
Line 7 - Value of c is 2
2. Comparison Operators/Relational Operators
These operators compare the values on either sides of them and decide the
relation among them. They are also called Relational operators.
The result of these operators is always a boolean value either true/false.

prepared by S.Radha Priya 30


Operator Description Example

== If the values of two operands are equal, then the (a == b) is not true.
condition becomes true.

!= If values of two operands are not equal, then (a != b) is true.


condition becomes true.

<> If values of two operands are not equal, then (a <> b) is true. This is similar to != operator.
condition becomes true.

> If the value of left operand is greater than the value (a > b) is not true.
of right operand, then condition becomes true.

< If the value of left operand is less than the value of (a < b) is true.
right operand, then condition becomes true.

>= If the value of left operand is greater than or equal (a >= b) is not true.
to the value of right operand, then condition
becomes true.

<= If the value of left operand is less than or equal to (a <= b) is true.
the value of right operand, then condition becomes
true.
prepared by S.Radha Priya 31
a = 21
b= 10
c=0
if ( a == b ):
print "Line 1 - a is equal to b"
else:
print "Line 1 - a is not equal to b“
if ( a != b ):
print "Line 2 - a is not equal to b"
else:
print "Line 2 - a is equal to b"
if ( a <> b ):
print "Line 3 - a is not equal to b“
else:
print "Line 3 - a is equal to b"
if ( a < b ):
print "Line 4 - a is less than b“
else:
print "Line 4 - a is not less than b"
prepared by S.Radha Priya 32
if ( a > b ):
print "Line 5 - a is greater than b"
else:
print "Line 5 - a is not greater than b"
a = 5;
b = 20;
if ( a <= b ):
print "Line 6 - a is either less than or equal to b“
else:
print "Line 6 - a is neither less than nor equal to b"
if ( b >= a ):
print "Line 7 - b is either greater than or equal to b“
else:
print "Line 7 - b is neither greater than nor equal to b"

prepared by S.Radha Priya 33


Line 1 - a is not equal to b
Line 2 - a is not equal to b
Line 3 - a is not equal to b
Line 4 - a is not less than b
Line 5 - a is greater than b
Line 6 - a is either less than or equal to b
Line 7 - b is either greater than or equal to b
Python Assignment Operators
The operator is used to store right side operand in the left side operand.

prepared by S.Radha Priya 34


Operator Description Example

= Assigns values from right side operands to


left side operand c = a + b assigns value of a + b into c

+= Add It adds right operand to the left operand and


AND assign the result to left operand c += a is equivalent to c = c + a

-= It subtracts right operand from the left


Subtract operand and assign the result to left operand c -= a is equivalent to c = c - a
AND
*= It multiplies right operand with the left
Multiply operand and assign the result to left operand c *= a is equivalent to c = c * a
AND
/= Divide It divides left operand with the right operand
AND and assign the result to left operand c /= a is equivalent to c = c / a

%= It takes modulus using two operands and


Modulus assign the result to left operand c %= a is equivalent to c = c % a
AND
**= Performs exponential (power) calculation on
Exponent operators and assign value to the left c **= a is equivalent to c = c ** a
AND operand
//= Floor It performs floor division on operators and
c //= a is equivalent to c = c // a
Division assign value to the left operand prepared by S.Radha Priya 35
a = 21
b = 10
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

prepared by S.Radha Priya 36


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
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Python Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation. Assume if a =
60; and b = 13; Now in the binary format their values will be 0011 1100 and 0000
1101 respectively.
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
~a = 1100 0011
prepared by S.Radha Priya 37
Operator Description Example
& Binary Operator copies a bit to the result if
AND it exists in both operands (a & b) (means 0000 1100)

| Binary It copies a bit if it exists in either


(a | b) = 61 (means 0011 1101)
OR operand.
^ Binary It copies the bit if it is set in one
(a ^ b) = 49 (means 0011 0001)
XOR operand but not both.
~ Binary
Ones (~a ) = -61 (means 1100 0011 in 2's
It is unary and has the effect of
Complem 'flipping' bits. complement form due to a signed
ent binary number.

<< Binary The left operands value is moved


Left Shift left by the number of bits specified a << 2 = 240 (means 1111 0000)
by the right operand.
>> Binary The left operands value is moved
Right Shift right by the number of bits a >> 2 = 15 (means 0000 1111)
specified by the right operand.
prepared by S.Radha Priya 38
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

prepared by S.Radha Priya 39


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
Python Logical Operators
There are following logical operators supported by Python language.

prepared by S.Radha Priya 40


Operat Description Example
or

and If both the operands are true then (a and b) is true.


Logical condition becomes true.
AND

or If any of the two operands are non- (a or b) is true.


Logical zero then condition becomes true.
OR

not Used to reverse the logical state of Not(a and b) is false.


Logical its operand.
NOT

prepared by S.Radha Priya 41


Python Membership Operators
Opera Description Example
tor
in Evaluates to true if it finds a
x in y, here in results in a 1 if x is a
variable in the specified sequence
member of sequence y.
and false otherwise.
not in Evaluates to true if it does not x not in y, here not in results in a 1 if x
finds a variable in the specified is not a member of sequence y.
sequence and false otherwise.

prepared by S.Radha Priya 42


a = 10
b = 20
list = [1, 2, 3, 4, 5 ];
if ( a in list ):
print "Line 1 - a is available in the given list"
else:
print "Line 1 - a is not available in the given list"
if ( b not in list ):
print "Line 2 - b is not available in the given list"
else: print "Line 2 - b is available in the given list"
a=2
if ( a in list ):
print "Line 3 - a is available in the given list"
else:
print "Line 3 - a is not available in the given list"
prepared by S.Radha Priya 43
Line 1 - a is not available in the given list
Line 2 - b is not available in the given list
Line 3 - a is available in the given list
Python Identity Operators
Identity operators compare the memory locations of two objects. There are
two Identity operators explained below −

Opera Description Example


tor

is Evaluates to true if the variables


on either side of the operator x is y, here is results in 1 if id(x) equals
point to the same object and false id(y).
otherwise.

is not Evaluates to false if the variables


on either side of the operator x is not y, here is not results in 1 if id(x)
point to the same object and true is not equal to id(y).
otherwise.
prepared by S.Radha Priya 44
a = 20
b = 20
if ( a is b ):
print "Line 1 - a and b have same identity"
else:
print "Line 1 - a and b do not have same identity"
if ( id(a) == id(b) ):
print "Line 2 - a and b have same identity"
else:
print "Line 2 - a and b do not have same identity"
b = 30
if ( a is b ):
print "Line 3 - a and b have same identity"
else: print "Line 3 - a and b do not have same identity“
if ( a is not b ):
print "Line 4 - a and b do not have same identity“
else:
print "Line 4 - a and b have same identity"
prepared by S.Radha Priya 45
Line 1 - a and b have same identity
Line 2 - a and b have same identity
Line 3 - a and b do not have same identity
Line 4 - a and b do not have same identity

Python Operators Precedence


The following table lists all operators from highest precedence to lowest.
Associativity
• Many operators are having the same precedence. The associativity decides
the order in which the operators with the same precedence are executed.
• Left-to-right Associativity.
>>> 5 – 7
-2
# Parentheses () has higher precedence
>>> (10 - 4) * 2
12

prepared by S.Radha Priya 46


Operator Description
** Exponentiation (raise to the power)

~+- Complement, unary plus and minus (method names for the last two are +@ and
-@)

* / % // Multiply, divide, modulo and floor division

+- Addition and subtraction


>> << Right and left bitwise shift
& Bitwise 'AND'
^| Bitwise exclusive `OR' and regular `OR'

<=, <, > ,>= Comparison operators


<> ,== ,!= Equality operators
= %= /= //= -= += *= Assignment operators
**=
is ,is not Identity operators
In, not in Membership operators
not ,or ,and Logical operators prepared by S.Radha Priya 47
Operators are classified in to 1.Unary Operators 2. Binary Operators
1. Unary operator: Unary operators with only one operand. These operators
are used basically used to provide sign to operand.
Format
Operator Operand
Unary Operators are
+
-
~
Ex:
>>>x=12
>>>+x
12
>>>-x
-12
>>>~x
~12

prepared by S.Radha Priya 48


Binary Operators
Operators with two operands that are manipulated to get the result. They are
used to compare numeric values and string values.
Format
Operand1 operator operand2
Binary operators are
**, *, /,%,+,-,<<,>>,&,<,>,<=,>=,==,!=,<>

STATEMENTS AND EXPRESSIONS


STATEMENT
Statement can be thought as an instruction that can be interpreted by the
python interpreter.
Ex: print an Assignment Statement
>>>message =“Hello world”
>>>print message
>>>x=2
Print x
2
prepared by S.Radha Priya 49
EXPRESSION
Expression is a combination of variables, operators, values and reserved
keyword.
>>>1+1
2
>>>program=“hello python”
>>>program
‘hello python’
>>> print program
hello python
STRING OPERATIONS
• The continuous set of characters kept within quotation marks
• Either Single quotes/double quotes
• Operations Performed on string
(* +)→Slicing operator
(+)→Concatenation Operator
(*)→repetition operator

prepared by S.Radha Priya 50


a. Concatenation(+)
Joining the string by linking the last end of the string with the first
end of the second string.
>>>test=“test string”
>>>”hello”+test
>>>”hello test string”
b. Repetition(*)
The repetition operation is performed on the strings in order to
repeat the string several times.
>>>’spam’*3
Spamspamspam
c. Get particular character[ ]
To access single item of the string[ ] is used.
Ex: to access the third element of the string the string name is typed followed
by the [2].
>>>test=“test string”
>>>test[3]
prepared by S.Radha Priya 51
‘t’
d. slicing[:]
Extract a substring by using a colon inside the square bracket[:]
>>>test=“test string”
>>test[1:7]
‘est st’
>>>test[:3]
‘tes’
>>>test[2: ]
‘st string’
Built-in commands or methods for string operation
Method Description
.lower() Convert all upper to lower case
.upper() Convert lower case into upper case
.isapha() Return true if string contain only alphabetical
characters
prepared by S.Radha Priya 52
.isdigit() Return true if string contain only digits
.isspace() Return true if string contain space
.find(“string”) Return of the first index of search string

.replace(“old,””new”) Replace the string with new string


.count(“characters”) Return the occurrence of particular character in string
len(“string”) Return the length of string

>>>s=“hello python”
>>>print s.lower()
hello python
>>>print s.upper()
HELLO PYTHON
>>>print s.find(“l”)
2
>>>print s.replace(“l”,”p”)
Heppo python
>>>print s.count(“o”) prepared by S.Radha Priya 53
2
>>>print len(s)
12
>>>s=“Hello”
>>>print s.isalpha() #string contain alphabets
True
>>>print s.isdigit() #string does not contain digits
False

Control Statements
• There may be a situation when you need to execute a block of code
several number of times.
• Programming languages provide various control structures that allow for
more complicated execution paths.
• A loop statement allows us to execute a statement or group of statements
multiple times. The following diagram illustrates a loop statement −

prepared by S.Radha Priya 54


For loop
Python for loop is a iterator-based
Syntax
>>>for x in y:
block 1
else #optional
block 2
If a sequence contains an expression list,
it is evaluated first. Then, the first item in
the sequence is assigned to the iterating
variable iterating_var. Next, the
statements block is executed. Each item
in the list is assigned to iterating_var,
and the statement(s) block is executed
until the entire sequence is exhausted.

prepared by S.Radha Priya 55


example
for letter in 'Python': # First Example
print 'Current Letter :', letter
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # Second Example
print 'Current fruit :', fruit
print "Good bye!“
output
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
prepared by S.Radha Priya 56
example

fruits = ['banana', 'apple', 'mango']


for index in range(len(fruits)):
print 'Current fruit :', fruits[index]
print "Good bye!“
Output
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
Using else Statement with For Loop
• Python supports to have an else statement associated with a loop
statement
• If the else statement is used with a for loop, the else statement is
executed when the loop has exhausted iterating the list.
• The following example illustrates the combination of an else statement
with a for statement that searches for prime numbers from 10 through 20.
prepared by S.Radha Priya 57
example

for num in range(10,20): #to iterate between 10 to 20


for i in range(2,num): #to iterate on the factors of the number
if num%i == 0: #to determine the first factor
j=num/i #to calculate the second factor
print '%d equals %d * %d' , (num,i,j)
break #to move to the next number, the #first FOR
else: # else part of the loop
print num, 'is a prime number'
break
10 equals 2 * 5
11 is a prime number
12 equals 2 * 6
13 is a prime number
14 equals 2 * 7
15 equals 3 * 5 16 equals 2 * 8 17 is a prime number 18 equals 2 * 9 19 is a
prime number prepared by S.Radha Priya 58
16 equals 2 * 8
17 is a prime number
18 equals 2 * 9
19 is a prime number

range() function
It is a built-in function in python that helps us to iterate over a sequence of
numbers.
>>>range(8)
[0,1,2,3,4,5,6,7] #range starts from 0 and ends n-1.
>>>range(3,9)
[3,4,5,6,7,8] #begin index 3 end index 9(9-1=8)
>>>range[3,40,5]
[3,8,13,18,23,28,33,38]

prepared by S.Radha Priya 59


While Statement

A while loop statement in Python programming language repeatedly executes


a target statement as long as a given condition is true.
Syntax
while expression/condition:
block
else: #optional
statement(s)

• Here, statement(s) may be a single statement or a block of statements.


The condition may be any expression, and true is any non-zero value. The
loop iterates while the condition is true.
• When the condition becomes false, program control passes to the line
immediately following the loop.

prepared by S.Radha Priya 60


>>count=0
>>while count<6:
print count
count=count+1
o/p: 0 1 2 3 4 5
Factorial of a number:
Num =int(input(“enter the number:”))
fact=1
ans=1
While fact<=num:
ans=ans*fact
fact=fact+1
Print(“factorial of”,num,”is”:”,ans)
Output
Enter the number :6
Factorial of 6 is 720

prepared by S.Radha Priya 61


count=0
Sum=0
>>while count<10:
sum=sum+count
count=count+1
print(“sum of first 10 numbers=“,sum)
o/p: sum of first 10 numbers=55

Break and Continue Statement


• Break and continue statements are useful in while loop and for loop
• The break statements exits from the loop and transfers the execution from
the loop to the statement that is immediately following the loop.
• The continue statement causes execution to immediately continue at the
start of the loop, it skips the execution of the remaining body part of the
loop.

prepared by S.Radha Priya 62


Ex:Print first 5 even numbers
Count=2
While true:
print count
count=count+2
if count>=12:
break
Output:
2 4 6 8 10
Ex:Print first 4 even numbers
for I in range(1,10):
if i%2 !=0: #if condition becomes true, it skips the print part
continue
print i
Output:
2 4 6 8
prepared by S.Radha Priya 63
If statement-conditional statement
If statement is known as the decision-making statement in programming
languages.
a. If statements
Syntax:
If condition:
statement(s)
(or)
If condition:
block

If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if
statement is executed. If boolean expression evaluates to FALSE, then the first set of code
after the end of the if statement(s) is executed.

prepared by S.Radha Priya 64


Ex:
n1=int(input(“enter the first number”))
n2=int(input(“enter the second number’))
If n1-n2==0:
print(“both the numbers entered are equal”)

Output
Enter the first number 12
Enter the second number 12
Both the numbers entered are equal

prepared by S.Radha Priya 65


b. if-else statements
If-else statements takes care of a true as well as a false condition.
Syntax:
If condition:
statements(s)
else:
statements(s)
(or)
If condition:
if-block
else:
else-block

An else statement can be combined with an if statement. An else statement


contains the block of code that executes if the conditional expression in the if
statement resolves to 0 or a FALSE value.

prepared by S.Radha Priya 66


var1 = 100
if var1:
print "1 - Got a true expression value"
print var1
else:
print "1 - Got a false expression value"
print var1
var2 = 0
if var2:
print "2 - Got a true expression value“
print var2
else:
print "2 - Got a false expression value"
print var2
print "Good bye!"
prepared by S.Radha Priya 67
output
1 - Got a true expression value
100
2 - Got a false expression value
0
Good bye!

Ex:
n1=int(input(“enter the first number”))
n2=int(input(“enter the second number’))
If n1>n2:
print(n1, “ is greater than”,n2)
Else:
print(n2,” is greater than”,n1)

prepared by S.Radha Priya 68


num=int(input(‘enter the number’))
Print(‘entered number is ‘,num)
If(num%5==0 and num%10==0):
print(num, ‘is divisible by both 5 and 10’)
If(num%5==0 or num%10==0):
print(num,’is not divisible by 5 or 10’)
Else:
print(num,’is not divisible either by 5 or 10’)

Output
Enter the number 45
Entered number is 45
45 is divisible by 5 or 10

prepared by S.Radha Priya 69


Nested if statement
When a programmer writes one if statement inside another if statements then it is
called a nested if statements.
Syntax:
If boolean-expression1:
if boolean-expression2:
statement1
else:
statement 2
else:
statement 3

prepared by S.Radha Priya 70


If exp-1 and exp-2 are true statement-1 will execute. If exp-1 is correct and exp-2
is false then st-2 will execute. If both exp-1 and exp-2 are incorrect then st-3 will
execute.
Ex:
N1=int(input(“enter the number”))
N2=int(input(“enter the number”))
N3=int(input(“enter the number”))
If n1>n2:
if n2>n3:
print(n1,”is greater than”,n2,”and”,n3)
else:
print(n1,”is less than”,n2,”and”,n3)
Print(“end of nested if”)
Output:
Enter the number:12
Enter the number:34
Enter the numer:56
12 is less than 34 and 56
End of nested if prepared by S.Radha Priya 71
If elif else statement

• There may be a situation when you want to check for another condition
after a condition resolves to true. In such a situation, you can use the
nested if construct.
• In a nested if construct, you can have an if...elif...else construct inside
another if...elif...else construct.
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
elif expression4:
statement(s)
else:
statement(s)

prepared by S.Radha Priya 72


var = 100
if var < 200:
print "Expression value is less than 200"
if var == 150:
print "Which is 150"
elif var == 100:
print "Which is 100“
elif var == 50:
print "Which is 50"
elif var < 50:
print "Expression value is less than 50“
else:
print "Could not find true expression"
print "Good bye!“
output
Expression value is less than 200
Which is 100
Good bye! prepared by S.Radha Priya 73
Input from keyboard

a. Input() function:
• Input() function has an optional parameter, which is a prompt string.
• When the input() function is called, in order to take input from the user
then the execution of program halts and waits for the user to provide an
input.
• The input given by user through keyboard and it is ended by return key.
• If the input is integer it will return integer value. If the input is string it will
return string value.
Ex:
name=input(“what is your name”)
Print(“hello”+name+”!”)
Output
What is your name? rama
Hello rama!

prepared by S.Radha Priya 74


Raw-input() function
Raw-input() takes input from the user. It returns the input of user without
doing any change. i.e.,raw
Ex:
#no casting
Age=raw-input(“what is your name”)
What is your age 20
Type(age)
<type ‘str’> # input stored as string
#using casting function to convert input to integer
Age=int(raw-input(“what is your age”))
What is your age 20
type(age)
<type ‘int’> #input is stored as integer

prepared by S.Radha Priya 75


• Bit-wise operators 0000 1010
0001 0100
>>>x=10 0000 1010 z=x<<2 0010 1000
>>>y=12 0000 1100 40
>>>z=0 z=x>>2 0000 1010
>>>z=x&y 0000 1000 2 0000 0101
>>>print z 0000 0010
8
>>>z=x/y 0000 1110
Print z
14
>>>z=x^y 0000 0110
Print z
6
>>.z=~x 1111 0101
Print z
-11

prepared by S.Radha Priya 76

You might also like