Python Module 1
Python Module 1
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
# 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
[ 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.
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.
• 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
Python Collections
There are four collection data types in the Python programming language:
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
#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"
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
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
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.
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
Example of if...else
num = 3
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
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
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.
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 −
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
Immutable object – An immutable object is one in which the values can’t be changed or
altered.