Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
3 views31 pages

Python Module 1

Python

Uploaded by

nadafathima331
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)
3 views31 pages

Python Module 1

Python

Uploaded by

nadafathima331
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/ 31

Python Programming

Module 1
Python is a general-purpose interpreted, interactive, object-oriented, and high-level
programming language. It was developed by Guido van Rossum during 1985- 1990.
Features of Python:
a) Simple and easy to learn – Python is a simple language with few keywords, simple
structure, and a clearly defined syntax.
b) Interpreted − Python is processed at runtime by the interpreter. We need not compile
the program before executing it.
c) Interactive – The Python prompt interact with the interpreter directly to interpret the
programs that we have written. Python has support for an interactive mode which
allows interactive testing and debugging of snippets of code.
d) Python is Object-Oriented − Python supports Object-Oriented programming (OOP)
concepts that encapsulate code within objects. All concepts in OOPs like data hiding
operator overloading, inheritance etc, can be well written in Python. It supports
functional as well as structured programming.
e) Portable − Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
f) Scalable − Python provides a better structure and support for large programs than shell
scripting. It can be used as a scripting language or can be compiled to byte-code for
building large applications.
g) Extendable − You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.
h) Dynamic −It provides very high-level dynamic data types and supports dynamic type
checking. It also supports automatic garbage collection.
i) GUI Programming and Databases − Python supports GUI applications that can be
created and ported to many system calls, libraries and windows systems, such as
Windows MFC, Macintosh, and the X Window system of Unix. Python also provides
interfaces to all major commercial databases.
j) Broad standard library − Python's library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
Different ways to run Python Program

We can run our code in the Python programming language in the following ways

1. Using interactive mode

2. Using script mode

3. Using integrated Development Environment

Let us execute programs in different modes of programming.


Interactive Mode Programming
Invoking the interpreter without passing a script file as a parameter brings up the following
prompt −
Type the following text at the Python prompt and press the Enter −
>>> print("Hello, Python!")
this produces the following result −
Hello, Python!

Script Mode Programming


Script mode in Python is where we first write the Python program inside a script file and
execute it after that. We can execute the script of code using the command prompt .
Write a simple Python program in a script. Python files have extension .py. Type the following
source code in a test.py file −
print("Hello, Python!")
$ python test.py
This produces the following result −
Hello, Python
Integrated Development Environment programming
We can also execute the script of code using Python IDE installed in our system.
In the script mode, anytime we can view the code that we have written inside the file, and
we can modify it before executing it next time. That's why editing a Python code becomes
quite easy in script mode, and we can edit or view the code as many times as we want. We
can write long pieces of code with script mode, and that's why many expert programmers
prefer it over the interactive mode of execution. The Python file we create using the script
mode is usually saved by default inside the folder where our Python IDE is installed, and it
is saved with the Python file (".py") extension.
Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or other
object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or
more letters, underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers. Python is
a case sensitive programming language. Thus, Manpower and manpower are two different
identifiers in Python.
Here are naming conventions for Python identifiers −
• Class names start with an uppercase letter. All other identifiers start with a lowercase
letter.
• Starting an identifier with a single leading underscore indicates that the identifier is
private.
• Starting an identifier with two leading underscores indicates a strongly private
identifier.
• If the identifier also ends with two trailing underscores, the identifier is a language-
defined special name.
Reserved Words (Keywords)
Python keywords are unique words reserved with defined meanings and functions that we can
only apply for those functions.
The following list shows the Python keywords. These are reserved words and you cannot use
them as constant or variable or any other identifier names. All the Python keywords contain
lowercase letters only.
and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield

Lines and Indentation


Python provides no braces to indicate blocks of code for class and function definitions or flow
control. Blocks of code are denoted by line indentation.
The number of spaces in the indentation is variable, but all statements within the block must
be indented the same amount. For example −
if True:
print( "True")
else:
print( "False")
However, the following block generates an error −
if True:
print( "Answer")
print( "True")
else:
print ("Answer")
print ("False")
Thus, in Python all the continuous lines indented with same number of spaces would form a
block. The following example has various statement blocks −
You have to use the same number of spaces in the same block of code, otherwise Python will give you an
error:
Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
Multi-Line Statements
Statements in Python typically end with a new line. Python does, however, allow the use of the
line continuation character (\) to denote that the line should continue. For example −
total = item_one + \
item_two + \
item_three
Statements contained within the [], {}, or () brackets do not need to use the line continuation
character. For example −
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as
long as the same type of quote starts and ends the string.
The triple quotes are used to span the string across multiple lines. For example, all the
following are legal −
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
Comments in Python
A hash sign (#) that is not inside a string literal begins a comment. All characters after the #
and up to the end of the physical line are part of the comment and the Python interpreter
ignores them.
#!/usr/bin/python

# First comment
print( "Hello, Python!") # second comment
This produces the following result −
Hello, Python!
You can type a comment on the same line after a statement or expression −
name = "Krishna" # This is again comment
You can comment multiple lines as follows −
# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.
Following triple-quoted string is also ignored by Python interpreter and can be used as a
multiline comments:
'''
This is a multiline
comment.
'''
Using Blank Lines
A line containing only whitespace, possibly with a comment, is known as a blank line and
Python totally ignores it.
In an interactive interpreter session, you must enter an empty physical line to terminate a
multiline statement.
Waiting for the User
The following line of the program displays the prompt, the statement saying “Press the enter
key to exit”, and waits for the user to take action −
#!/usr/bin/python

raw_input("\n\nPress the enter key to exit.")


Here, "\n\n" is used to create two new lines before displaying the actual line. Once the user
presses the key, the program ends.
Multiple Statements on a Single Line
The semicolon ( ; ) allows multiple statements on the single line given that neither statement
starts a new code block. Here is a sample snip using the semicolon −
import sys; x = 'foo'; sys.stdout.write(x + '\n')
Multiple Statement Groups as Suites
A group of individual statements, which make a single code block are called suites in Python.
Compound or complex statements, such as if, while, def, and class require a header line and a
suite.
Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and are
followed by one or more lines which make up the suite. For example −
if expression :
suite
elif expression :
suite
else :
suite
Command Line Arguments
Many programs can be run to provide you with some basic information about how they should
be run. Python enables you to do this with -h −
$ python -h
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-c cmd : program passed in as string (terminates option list)
-d : debug output from parser (also PYTHONDEBUG=x)
-E : ignore environment variables (such as PYTHONPATH)
-h : print this help message and exit

[ etc. ]
Variables
Variables are nothing but reserved memory locations to store values. This means that when
you create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can
be stored in the reserved memory. Therefore, by assigning different data types to variables,
you can store integers, decimals or characters in these variables.

Assigning Values to Variables


Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used to
assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand to the
right of the = operator is the value stored in the variable. For example −
#!/usr/bin/python

counter = 100 # An integer assignment


miles = 1000.0 # A floating point
name = "John" # A string

print(counter)
print(miles)
print(name)
Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and name variables,
respectively. This produces the following result −
100
1000.0
John

Multiple Assignment
Python allows to assign a single value to several variables simultaneously. For example −
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned to the
same memory location. You can also assign multiple objects to multiple variables. For example

a,b,c = 1,2,"john"
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively,
and one string object with the value "john" is assigned to the variable c.

Standard Data Types


The data stored in memory can be of many types. For example, a person's age is stored as a
numeric value and his or her address is stored as alphanumeric characters. Python has
various standard data types that are used to define the operations possible on them and the
storage method for each of them.
Python has five standard data types −
• Numbers
• String
• List
• Tuple
• Dictionary
Numbers
Number data types store numeric values. Number objects are created when you assign a value
to them. For example −
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement. The syntax of
the del statement is −
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del statement. For example −
del var
del var_a, var_b
Python supports four different numerical types −
• int (signed integers)
• long (long integers, they can also be represented in octal and hexadecimal)
• float (floating point real values)
• complex (complex numbers)
Examples
Here are some examples of numbers −
int long float Complex
10 51924361L 0.0 3.14j
100 -0x19323L 15.20 45.j
-786 0122L -21.9 9.322e-36j
080 0xDEFABCECBDAECBFBAEl 32.3+e18 .876j
-0490 535633629843L -90. -.6545+0J
-0x260 -052318172735L -32.54e100 3e+26J
0x69 -4721885298529L 70.2-E12 4.53e-7j

• Python allows you to use a lowercase l with long, but it is recommended that you use
only an uppercase L to avoid confusion with the number 1. Python displays long
integers with an uppercase L.
• A complex number consists of an ordered pair of real floating-point numbers denoted
by x + yj, where x and y are the real numbers and j is the imaginary unit.
Strings
Strings in Python are identified as a contiguous set of characters represented in the quotation
marks. Python allows for either pairs of single or double quotes. Subsets of strings can be
taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the
string and working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator. For example −
#!/usr/bin/python

str = 'Hello World!'

print(str) # Prints complete string


print(str[0]) # Prints first character of the string
print(str[2:5]) # Prints characters starting from 3rd to 5th
print(str[2:]) # Prints string starting from 3rd character
print(str * 2) # Prints string two times
print(str + "TEST") # Prints concatenated string
This will produce the following result −
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

Python Collections
There are four collection data types in the Python programming language:

 List is a collection which is ordered and changeable. Allows duplicate


members.
 Tuple is a collection which is ordered and unchangeable. Allows duplicate
members.
 Set is a collection which is unordered, unchangeable*, and unindexed. No
duplicate members.
 Dictionary is a collection which is ordered** and changeable. No
duplicate members.

List
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data,
the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.
Lists are created using square brackets:
Example
Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has
index [1] etc.
Ordered
When we say that lists are ordered, it means that the items have a defined
order, and that order will not change.
If you add new items to a list, the new items will be placed at the end of the
list.
Note: There are some list methods that will change the order, but in general:
the order of the items will not change.
Changeable
The list is changeable, meaning that we can change, add, and remove items in
a list after it has been created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example
Lists allow duplicate values:
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
Lists are the most versatile of Python's compound data types. A list contains items separated
by commas and enclosed within square brackets ([]). To some extent, lists are similar to
arrays in C. One difference between them is that all the items belonging to a list can be of
different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes
starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is
the list concatenation operator, and the asterisk (*) is the repetition operator. For example −
#!/usr/bin/python

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]


tinylist = [123, 'john']

print(list) # Prints complete list


print(list[0]) # Prints first element of the list
print(list[1:3]) # Prints elements starting from 2nd till 3rd
print(list[2:]) # Prints elements starting from 3rd element
print(tinylist * 2) # Prints list two times
print(list + tinylist) # Prints concatenated lists
This produce the following result −
['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
Tuples
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of
values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and
their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and
cannot be updated. Tuples can be thought of as read-only lists.
Example
Create a Tuple:
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')

print(tuple) # Prints the complete tuple


print(tuple[0]) # Prints first element of the tuple
print(tuple[1:3]) # Prints elements of the tuple starting from 2nd till 3rd
print(tuple[2:]) # Prints elements of the tuple starting from 3rd element
print(tinytuple * 2) # Prints the contents of the tuple twice
print(tuple + tinytuple) # Prints concatenated tuples
This produce the following result −
('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
The following code is invalid with tuple, because we attempted to update a tuple, which is not
allowed. Similar case is possible with lists −
#!/usr/bin/python

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list

Tuple items are ordered, unchangeable, and allow duplicate values.


Tuple items are indexed, the first item has index [0], the second item has
index [1] etc.
Ordered
When we say that tuples are ordered, it means that the items have a defined
order, and that order will not change.
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items
after the tuple has been created.
Allow Duplicates
Since tuples are indexed, they can have items with the same value:
Example
Tuples allow duplicate values:
thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)
Tuple Length
To determine how many items a tuple has, use the len() function:
Example
Print the number of items in the tuple:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
Create Tuple With One Item
To create a tuple with only one item, you have to add a comma after the item,
otherwise Python will not recognize it as a tuple.
Example
One item tuple, remember the comma:
thistuple = ("apple",)
print(type(thistuple))

#NOT a tuple
thistuple = ("apple")
print(type(thistuple))

Sets
Sets are used to store multiple items in a single variable.
Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List,
Tuple, and Dictionary, all with different qualities and usage.
A set is a collection which is unordered, unchangeable*, and unindexed.
* Note: Set items are unchangeable, but you can remove items and add new items.
Sets are written with curly brackets.
Example
Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)
Note: Sets are unordered, so you cannot be sure in which order the items will appear.

Set Items
Set items are unordered, unchangeable, and do not allow duplicate values.
Unordered
Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them, and cannot be referred to by
index or key.
Unchangeable
Set items are unchangeable, meaning that we cannot change the items after the set has been
created.
Once a set is created, you cannot change its items, but you can remove items and add new
items.
Duplicates Not Allowed
Sets cannot have two items with the same value.
Example
Duplicate values will be ignored:
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)
Dictionary
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and do not allow
duplicates.
Dictionaries are written with curly brackets, and have keys and values:
Example
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Dictionary Items
Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by
using the key name.
Example
Print the "brand" value of the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])

Ordered
When we say that dictionaries are ordered, it means that the items have a
defined order, and that order will not change.
Unordered means that the items does not have a defined order, you cannot
refer to an item by using an index.
Changeable
Dictionaries are changeable, meaning that we can change, add or remove items
after the dictionary has been created.
Duplicates Not Allowed
Dictionaries cannot have two items with the same key:
Example
Duplicate values will overwrite existing values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
Dictionary Length
To determine how many items a dictionary has, use the len() function:
Example
Print the number of items in the dictionary:
print(len(thisdict))
Dictionary Items - Data Types
The values in dictionary items can be of any data type:
Example
String, int, boolean, and list data types:
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using
square braces ([]). For example −
#!/usr/bin/python

dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

print(dict['one']) # Prints value for 'one' key


print(dict[2]) # Prints value for 2 key
print(tinydict) # Prints complete dictionary
print(tinydict.keys()) # Prints all the keys
print(tinydict.values()) # Prints all the values
This produce the following result −
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
Dictionaries have no concept of order among elements. It is incorrect to say that the elements
are "out of order"; they are simply unordered.

Built-in methods :
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy()Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list

Python has a set of built-in methods that you can use on sets.
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy()Returns a copy of the set
difference() Returns a set containing the difference between two or more sets
difference_update() Removes the items in this set that are also included in another, specified
set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two or more sets
intersection_update() Removes the items in this set that are not present in other,
specified set(s)
isdisjoint() Returns whether two sets have a intersection or not
issubset() Returns whether another set contains this set or not
issuperset() Returns whether this set contains another set or not
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric differences of two sets
symmetric_difference_update() inserts the symmetric differences from this set and another
union() Return a set containing the union of sets
update() Update the set with another set, or any other iterable

Python has a set of built-in methods that you can use on dictionaries.
Method Description
clear() Removes all the elements from the dictionary
copy()Returns a copy of the dictionary
fromkeys()Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the key,
with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary

Python has two built-in methods that you can use on tuples.
Method Description
count() Returns the number of times a specified value occurs in a tuple
index() Searches the tuple for a specified value and returns the position of where it was
found
Data Type Conversion
Sometimes, you may need to perform conversions between the built-in types. To convert
between types, you simply use the type name as a function.
There are several built-in functions to perform conversion from one data type to another.
These functions return a new object representing the converted value.
Sr.No. Function & Description
1
int(x [,base])
Converts x to an integer. base specifies the base if x is a string.
2
long(x [,base] )
Converts x to a long integer. base specifies the base if x is a string.
3
float(x)
Converts x to a floating-point number.
4
complex(real [,imag])
Creates a complex number.
5
str(x)
Converts object x to a string representation.
6
repr(x)
Converts object x to an expression string.
7
eval(str)
Evaluates a string and returns an object.
8
tuple(s)
Converts s to a tuple.
9
list(s)
Converts s to a list.
10
set(s)
Converts s to a set.
11
dict(d)
Creates a dictionary. d must be a sequence of (key,value) tuples.
12
frozenset(s)
Converts s to a frozen set.
13
chr(x)
Converts an integer to a character.
14
unichr(x)
Converts an integer to a Unicode character.
15
ord(x)
Converts a single character to its integer value.
16
hex(x)
Converts an integer to a hexadecimal string.
17
oct(x)
Converts an integer to an octal string.

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 Operator
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
Arithmetic operators are used with numeric values to perform common mathematical
operations.
Assume variable a holds 10 and variable b holds 20, then −
Operator Description Example
+ Addition Adds values on either side of the operator. a + b = 30
- Subtraction Subtracts right hand operand from left hand operand. a – b = -10
* Multiplication Multiplies values on either side of the operator a * b = 200
/ Division Divides left hand operand by right hand operand b/a=2
% Modulus Divides left hand operand by right hand operand and returns b%a=0
remainder
** Exponent Performs exponential (power) calculation on operators a**b =10
to the
power 20
// Floor Division - The division of operands where the result is 9//2 = 4
the quotient in which the digits after the decimal point are and
removed. But if one of the operands is negative, the result is 9.0//2.0 =
floored, i.e., rounded away from zero (towards negative 4.0, -
infinity) − 11//3 = -
4, -
11.0//3 =
-4.0

Comparison Operators
Comparison operators are used to compare two values.
They are also called Relational operators.
Assume variable a holds 10 and variable b holds 20, then −
Operator Description Example
== If the values of two operands are equal, then the condition (a == b) is
becomes true. not true.
!= If values of two operands are not equal, then condition becomes (a != b) is
true. true.
<> If values of two operands are not equal, then condition becomes (a <> b) is
true. true. This
is similar
to !=
operator.
> If the value of left operand is greater than the value of right (a > b) is
operand, then condition becomes true. not true.
< If the value of left operand is less than the value of right operand, (a < b) is
then condition becomes true. true.
>= If the value of left operand is greater than or equal to the value of (a >= b) is
right operand, then condition becomes true. not true.
<= If the value of left operand is less than or equal to the value of right (a <= b) is
operand, then condition becomes true. true.
Assignment Operators
Assignment operators are used to assign values to variables.
Assume variable a holds 10 and variable b holds 20, then −
Operator Description Example
= Assigns values from right side c = a + b assigns value of a + b
operands to left side operand into c
+= It adds right operand to the left
operand and assign the result to left c += a is equivalent to c = c + a
operand
-= It subtracts right operand from the left
operand and assign the result to left c -= a is equivalent to c = c - a
operand
*= It multiplies right operand with the left
operand and assign the result to left c *= a is equivalent to c = c * a
operand
/= It divides left operand with the right
operand and assign the result to left c /= a is equivalent to c = c / a
operand
%= It takes modulus using two operands
c %= a is equivalent to c = c % a
and assign the result to left operand
**= Performs exponential (power)
calculation on operators and assign c **= a is equivalent to c = c ** a
value to the left operand
//= It performs floor division on operators
c //= a is equivalent to c = c // a
and assign value to the left operand
Bitwise Operators
Bitwise operators are used to compare (binary) numbers.
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.
Following table lists out the bitwise operators supported by Python language with an example
each in those, we use the above two variables (a and b) as operands −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011

There are following Bitwise operators supported by Python language


Operator Description Example
& Operator copies a bit to the result if it (a & b) (means
(Binary AND) exists in both operands 0000 1100)
| It copies a bit if it exists in either operand. (a | b) = 61 (means
(Binary OR) 0011 1101)
^ It copies the bit if it is set in one operand (a ^ b) = 49 (means
(Binary XOR) but not both. 0011 0001)
~ (~a ) = -61 (means
(Binary Ones 1100 0011 in 2's
It is unary and has the effect of 'flipping'
Complement) complement form
bits.
due to a signed
binary number.
<< The left operands value is moved left by a << 2 = 240
(Binary Left Shift) the number of bits specified by the right (means 1111
operand. 0000)
>> The left operands value is moved right by
a >> 2 = 15 (means
(Binary Right Shift) the number of bits specified by the right
0000 1111)
operand.

Logical Operators
Logical operators are used to combine conditional statements.
There are following logical operators supported by Python language. Assume variable a holds
10 and variable b holds 20 then
Operator Description Example
and If both the operands are true then condition (a and b) is true.
(Logical AND) becomes true.
or If any of the two operands are non-zero then (a or b) is true.
( Logical OR) condition becomes true.
not Used to reverse the logical state of its operand. Not(a and b) is
(Logical NOT) false.

Membership Operators
Membership operators are used to test if a sequence is present in an object.
Python’s membership operators test for membership in a sequence, such as strings, lists, or
tuples. There are two membership operators as explained below −
Operator Description Example
in Evaluates to true if it finds a variable in
x in y, here in results in a 1 if x is a
the specified sequence and false
member of sequence y.
otherwise.
not in Evaluates to true if it does not finds a x not in y, here not in results in a 1 if
variable in the specified sequence and x is not a member of sequence y.
false otherwise.
Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:
Identity operators compare the memory locations of two objects. There are two Identity
operators explained below −
Operator Description Example

is Evaluates to true if the variables on either side


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

is not Evaluates to false if the variables on either x is not y, here is


side of the operator point to the same object not results in 1 if id(x)
and true otherwise. is not equal to id(y).

Python Operators Precedence


The following table lists all operators from highest precedence to lowest.
Sr.No. Operator & Description
1 **
Exponentiation (raise to the power)
2 ~+-
Complement, unary plus and minus (method names for the last two are +@
and -@)
3 * / % //
Multiply, divide, modulo and floor division
4 +-
Addition and subtraction
5
>> <<
Right and left bitwise shift
6 &
Bitwise 'AND'
7 ^|
Bitwise exclusive `OR' and regular `OR'
8 <= < > >=
Comparison operators
9 <> == !=
Equality operators
10 = %= /= //= -= += *= **=
Assignment operators
11 is is not
Identity operators
12 in not in
Membership operators
13 not or and
Logical operators

if...else statement in Python

Decision making is required when we want to execute a code only if a certain condition is
satisfied.
The if…elif…else statement is used in Python for decision making.
Python if Statement Syntax
if test expression:
statement(s)
Here, the program evaluates the test expression and will execute statement(s) only if the
test expression is True.
If the test expression is False, the statement(s) is not executed.
In Python, the body of the if statement is indicated by the indentation. The body starts with
an indentation and the first unindented line marks the end.
Python interprets non-zero values as True. None and 0 are interpreted as False.

Python if Statement Flowchart

Flowchart of if statement in Python programming


Example: Python if Statement

# If the number is positive, we print an appropriate message

num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")

num = -1
if num > 0:
print(num, "is a positive number.")
print("This is also always printed.")
the output will be:

3 is a positive number
This is always printed
This is also always printed.
In the above example, num > 0 is the test expression.
The body of if is executed only if this evaluates to True.
When the variable num is equal to 3, test expression is true and statements inside the body
of if are executed.
If the variable num is equal to -1, test expression is false and statements inside the body
of if are skipped.
The print() statement falls outside of the if block (unindented). Hence, it is executed
regardless of the test expression.
Python if...else Statement

Syntax of if...else
if test expression:
Body of if
else:
Body of else

The if..else statement evaluates test expression and will execute the body of if only when
the test condition is True.
If the condition is False, the body of else is executed. Indentation is used to separate the
blocks.
Python if..else Flowchart

Flowchart of if...else statement in Python

Example of if...else

# Program checks if the number is positive or negative


# And displays an appropriate message

num = 3

# Try these two variations as well.


# num = -5
# num = 0

if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
Output
Positive or Zero
In the above example, when num is equal to 3, the test expression is true and the body
of if is executed and the body of else is skipped.
If num is equal to -5, the test expression is false and the body of else is executed and the
body of if is skipped.
If num is equal to 0, the test expression is true and body of if is executed and body of else is
skipped.
Python if...elif...else Statement

Syntax of if...elif...else
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
The elif is short for else if. It allows us to check for multiple expressions.
If the condition for if is False, it checks the condition of the next elif block and so on.
If all the conditions are False, the body of else is executed.
Only one block among the several if...elif...else blocks is executed according to the
condition.
The if block can have only one else block. But it can have multiple elif blocks.
Flowchart of if...elif...else

Flowchart of if...elif....else statement in Python

Example of if...elif...else
'''In this program,
we check if the number is positive or
negative or zero and
display an appropriate message'''

num = 3.4

# Try these two variations as well:


# num = 0
# num = -4.5

if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
When variable num is positive, Positive number is printed.
If num is equal to 0, Zero is printed.
If num is negative, Negative number is printed.

Python Nested if statements


We can have a if...elif...else statement inside another if...elif...else statement. This
is called nesting in computer programming.
Any number of these statements can be nested inside one another. Indentation is the only
way to figure out the level of nesting. They can get confusing, so they must be avoided
unless necessary.
Python Nested if Example
'''In this program, we input a number
check if the number is positive or
negative or zero and display
an appropriate message
This time we use nested if statement'''

num = float(input("Enter a number: "))


if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
Output 1

Enter a number: 5
Positive number
Output 2
Enter a number: -1
Negative number
Output 3

Enter a number: 0
Zero
Loops
In general, statements are executed sequentially: The first statement in a function is executed
first, followed by the second, and so on. 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 −

Python programming language provides following types of loops to handle looping


requirements.
Sr.No. Loop Type & Description
1 while loop
Repeats a statement or group of statements while a given condition is TRUE. It tests
the condition before executing the loop body.
2 for loop
Executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
3 nested loops
You can use one or more loop inside any another while, for or do..while loop.

while Loop
With the while loop we can execute a set of statements as long as a condition is true.
Example
Print i as long as i is less than 6:
i=1
while i < 6:
print(i)
i += 1
Note: remember to increment i, or else the loop will continue forever.
The while loop requires relevant variables to be ready, in this example we need to define an
indexing variable, i, which we set to 1.
The break Statement
With the break statement we can stop the loop even if the while condition is true:
Example
Exit the loop when i is 3:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
The continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
Example
Continue to the next iteration if i is 3:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
The else Statement
With the else statement we can run a block of code once when the condition no longer is true:
Example
Print a message once the condition is false:
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")

For Loop
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set,
or a string).
This is less like the for keyword in other programming languages, and works more like an
iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
Example
Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
The for loop does not require an indexing variable to set beforehand.
Looping Through a String
Even strings are iterable objects, they contain a sequence of characters:
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
The range() Function
To loop through a set of code a specified number of times, we can use the range() function,
The range() function returns a sequence of numbers, starting from 0 by default, and increments
by 1 (by default), and ends at a specified number.
Example
Using the range() function:
for x in range(6):
print(x)
Note that range(6) is not the values of 0 to 6, but the values 0 to 5.
The range() function defaults to 0 as a starting value, however it is possible to specify the
starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not
including 6):
Example
Using the start parameter:
for x in range(2, 6):
print(x)
The range() function defaults to increment the sequence by 1, however it is possible to specify
the increment value by adding a third parameter: range(2, 30, 3):
Example
Increment the sequence with 3 (default is 1):
for x in range(2, 30, 3):
print(x)
Else in For Loop
The else keyword in a for loop specifies a block of code to be executed when the loop is
finished:
Example
Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
Note: The else block will NOT be executed if the loop is stopped by a break statement.
Example
Break the loop when x is 3, and see what happens with the else block:
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
Nested Loops
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":
Example
Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.
Python supports the following control statements.
Sr.No. Control Statement & Description

1 break statement

Terminates the loop statement and transfers execution to the statement


immediately following the loop.
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating.
3 pass statement
The pass statement in Python is used when a statement is required syntactically
but you do not want any command or code to execute.
The break Statement
With the break statement we can stop the loop before it has looped through all the items:
Example
Exit the loop when x is "banana":
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
Example
Exit the loop when x is "banana", but this time the break comes before the print:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
The continue Statement
With the continue statement we can stop the current iteration of the loop, and continue with
the next:
Example
Do not print banana:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
The pass Statement
for loops cannot be empty, but if you for some reason have a for loop with no content, put in
the pass statement to avoid getting an error.
Example
for x in [0, 1, 2]:
pass
Mutable and Immutable Objects in Python
Every variable in python holds an instance of an object. There are two types of objects in python i.e.
Mutable and Immutable objects. Whenever an object is instantiated, it is assigned a unique object
id. The type of the object is defined at the runtime and it can’t be changed afterwards. However, it’s
state can be changed if it is a mutable object.

 Mutable object – A mutable object is one whose values can be changed.

 Example: List, Dictionaries, and Set

 Immutable object – An immutable object is one in which the values can’t be changed or
altered.

 Example: Numbers, String and Tuples

You might also like