Python Material
Python Material
Why Python?
1. Simple syntax
2. Length of code is very small
3. Complex problems can be solved in a simple manner.
Features of Python:
1. Simple to learn
2. It is a open source
3. Portability
4. High level interpreter-automatic memory management
5. Object oriented programming
6. Supports nearly 200+ standard libraries.
Applications of Python:
1. Web & Internet development
2. Desktop GUI Applications
3. Artificial Intelligence
4. Machine Learning
5. Image processing Applications
6. Games and 3D graphics
7. Network programming
8. Data base access
9. Business Applications
Python Environments:
1. Anaconda ----- www.anaconda.com
2. IDLE-priginal---- www.python.org
3. Jupyter
4. Spyder
5. Pycharm
6. eRic
7. Th
8. Atom
History of Python
1. Python is created by Dutch Guido van Rossum around 1991.
2. Python is an open-source project.
3. The mother site is www.python.org.
Versions of Python:
1. Python 1: the initial version.
Python Statement:
Python Syntax:
print(“Hello Python”)
Python Comments:
Creating a Comment:
#This is a comment
print("Hello, World!")
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
As long as the string is not assigned to a variable, Python will read the code,
but then ignore it, and you have made a multiline comment.
Identifiers:
1. Starting letter should be an alphabet or _
2. Other than _ , no other symbols are not allowed within the identifier.
3. Identifier name should not be keyword.
4. Length of an identifier is unlimited.
5. It is case sensitive.
Example: Name=”Suresh”
NAME=”suresh”
name=”suresh” these three are different variables.
Variables:
Variable is a container for storing data. Or named memory location.
There is no syntax for declaring variable in python.
Assigning value to a variable is itself both declaration and initialization.
Example: a=5
Example2:
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
Example3:
x = y = z = "Orange"
print(x)
print(y)
print(z)
Example4:
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
Example5:
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
Example6:
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
Example7:
x = 5
y = 10
print(x + y)
There are various data types in Python. Some of the important types are
listed below.
Python Numbers
Integers, floating point numbers and complex numbers fall under Python
numbers category. They are defined as int , float and complex classes in
Python.
We can use the type() function to know which class a variable or a value
belongs to. Similarly, the isinstance() function is used to check if an object
belongs to a particular class.
a = 5
print(a, "is of type", type(a))
a = 2.0
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
Output
>>> a = 1234567890123456789
>>> a
1234567890123456789
>>> b = 0.1234567890123456789
>>> b
0.12345678901234568
>>> c = 1+2j
>>> c
(1+2j)
a = [5,10,15,20,25,30,35,40]
# a[2] = 15
print("a[2] = ", a[2])
Output
a[2] = 15
a[0:3] = [5, 10, 15]
a[5:] = [30, 35, 40]
Lists are mutable, meaning, the value of elements of a list can be altered.
a = [1, 2, 3]
a[2] = 4
print(a)
Output
[1, 2, 4]
Python Tuple
t = (5,'program', 1+3j)
We can use the slicing operator [] to extract items but we cannot change
its value.
t = (5,'program', 1+3j)
# t[1] = 'program'
print("t[1] = ", t[1])
# Generates error
# Tuples are immutable
t[0] = 10
Output
t[1] = program
t[0:3] = (5, 'program', (1+3j))
Traceback (most recent call last):
File "test.py", line 11, in <module>
t[0] = 10
TypeError: 'tuple' object does not support item assignment
Python Strings
String is sequence of Unicode characters. We can use single quotes or
double quotes to represent strings. Multi-line strings can be denoted using
triple quotes, ''' or """ .
s = "This is a string"
print(s)
s = '''A multiline
string'''
print(s)
Output
This is a string
A multiline
string
Just like a list and tuple, the slicing operator [ ] can be used with strings.
Strings, however, are immutable.
s = 'Hello world!'
# s[4] = 'o'
print("s[4] = ", s[4])
# s[6:11] = 'world'
print("s[6:11] = ", s[6:11])
# Generates error
# Strings are immutable in Python
s[5] ='d'
Output
s[4] = o
s[6:11] = world
Traceback (most recent call last):
File "<string>", line 11, in <module>
TypeError: 'str' object does not support item assignment
Python Set
a = {5,2,3,1,4}
Output
a = {1, 2, 3, 4, 5}
<class 'set'>
We can perform set operations like union, intersection on two sets. Sets
have unique values. They eliminate duplicates.
a = {1,2,2,3,3,3}
print(a)
Output
{1, 2, 3}
Since, set are unordered collection, indexing has no meaning. Hence, the
slicing operator [] does not work.
>>> a = {1,2,3}
>>> a[1]
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
TypeError: 'set' object does not support indexing
Python Dictionary
Dictionary is an unordered collection of key-value pairs.
It is generally used when we have a huge amount of data. Dictionaries are
optimized for retrieving data. We must know the key to retrieve the value.
In Python, dictionaries are defined within braces {} with each item being a
pair in the form key:value . Key and value can be of any type.
>>> d = {1:'value','key':2}
>>> type(d)
<class 'dict'>
We use key to retrieve the respective value. But not the other way around.
d = {1:'value','key':2}
print(type(d))
# Generates error
print("d[2] = ", d[2])
Output
<class 'dict'>
d[1] = value
d['key'] = 2
Traceback (most recent call last):
File "<string>", line 9, in <module>
KeyError: 2
Boolean
Boolean type provides two built-in values, True and False. These values are used to
determine the given statement true or false. It denotes by the class bool. True can be
represented by any non-zero value or 'T' whereas false can be represented by the 0
or 'F'. Consider the following example.
print(type(True))
print(type(False))
print(false)
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
>>> float(5)
5.0
Conversion from float to int will truncate the value (make it closer to zero).
>>> int(10.6)
10
>>> int(-10.6)
-10
>>> float('2.5')
2.5
>>> str(25)
'25'
>>> int('1p')
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1p'
>>> set([1,2,3])
{1, 2, 3}
>>> tuple({5,6,7})
(5, 6, 7)
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
>>> dict([[1,2],[3,4]])
{1: 2, 3: 4}
>>> dict([(3,26),(4,44)])
{3: 26, 4: 44}
For example:
>>> 2+3
5
Here, + is the operator that performs addition. 2 and 3 are the operands
and 5 is the output of the operation.
Arithmetic operators
Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication, etc.
x**y (x to the
** Exponent - left operand raised to the power of right
power y)
x = 15
y = 4
# Output: x + y = 19
print('x + y =',x+y)
# Output: x - y = 11
print('x - y =',x-y)
# Output: x * y = 60
print('x * y =',x*y)
# Output: x / y = 3.75
print('x / y =',x/y)
# Output: x // y = 3
print('x // y =',x//y)
# Output: x ** y = 50625
print('x ** y =',x**y)
Output
x + y = 19
x - y = 11
x * y = 60
x / y = 3.75
x // y = 3
x ** y = 50625
Comparison operators
Comparison operators are used to compare values. It returns
either True or False according to the condition.
Operator Meaning Example
> Greater than - True if left operand is greater than the right x>y
< Less than - True if left operand is less than the right x<y
x = 10
y = 12
# Output: x == y is False
print('x == y is',x==y)
# Output: x != y is True
print('x != y is',x!=y)
Output
x > y is False
x < y is True
x == y is False
x != y is True
x >= y is False
x <= y is True
Logical operators
Logical operators are the and , or , not operators.
Operator Meaning Example
x = True
y = False
print('x or y is',x or y)
print('not x is',not x)
Output
x and y is False
x or y is True
not x is False
Bitwise operators
Bitwise operators act on operands as if they were strings of binary digits.
They operate bit by bit, hence the name.
In the table below: Let x = 10 ( 0000 1010 in binary) and y = 4 ( 0000 0100 in
binary)
Operator Meaning Example
Assignment operators
Assignment operators are used in Python to assign values to variables.
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
Special operators
Python language offers some special types of operators like the identity
operator or the membership operator. They are described below with
examples.
Identity operators
is and is not are the identity operators in Python. They are used to check if
two values (or variables) are located on the same part of the memory. Two
variables that are equal does not imply that they are identical.
Operator Meaning Example
Is True if the operands are identical (refer to the same object) x is True
True if the operands are not identical (do not refer to the x is not
is not
same object) True
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]
# Output: False
print(x1 is not y1)
# Output: True
print(x2 is y2)
# Output: False
print(x3 is y3)
Output
False
True
False
Here, we see that x1 and y1 are integers of the same values, so they are
equal as well as identical. Same is the case with x2 and y2 (strings).
But x3 and y3 are lists. They are equal but not identical. It is because the
interpreter locates them separately in memory although they are equal.
Membership operators
in and not in are the membership operators in Python. They are used to
test whether a value or variable is found in a sequence
(string, list, tuple, set and dictionary).
In a dictionary we can only test for presence of key, not the value.
x = 'Hello world'
y = {1:'a',2:'b'}
# Output: True
print('H' in x)
# Output: True
print('hello' not in x)
# Output: True
print(1 in y)
# Output: False
print('a' in y)
Output
True
True
True
False
in y returns False .
Strings can be indexed (subscripted), with the first character having index 0. There is
no separate character type; a character is simply a string of size one:
>>>
>>> word = 'Python'
>>> word[0] # character in position 0
'P'
>>> word[5] # character in position 5
'n'
Indices may also be negative numbers, to start counting from the right:
>>>
>>> word[-1] # last character
'n'
>>> word[-2] # second-last character
'o'
>>> word[-6]
'P'
Note that since -0 is the same as 0, negative indices start from -1.
>>>
>>> word[0:2] # characters from position 0 (included) to 2
(excluded)
'Py'
Slice indices have useful defaults; an omitted first index defaults to zero, an omitted
second index defaults to the size of the string being sliced.
>>>
>>> word[:2] # character from the beginning to position 2
(excluded)
'Py'
>>> word[4:] # characters from position 4 (included) to the end
'on'
>>> word[-2:] # characters from the second-last (included) to
the end
'on'
Note how the start is always included, and the end always excluded. This makes
sure that s[:i] + s[i:] is always equal to s:
>>>
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
The first row of numbers gives the position of the indices 0…6 in the string; the
second row gives the corresponding negative indices. The slice from i to j consists of
all characters between the edges labeled i and j, respectively.
For non-negative indices, the length of a slice is the difference of the indices, if both
are within bounds. For example, the length of word[1:3] is 2.
>>>
However, out of range slice indexes are handled gracefully when used for slicing:
Lambda functions can have any number of arguments but only one
expression. The expression is evaluated and returned. Lambda functions
can be used wherever function objects are required.
print(double(5))
Output
10
double = lambda x: x * 2
def double(x):
return x * 2
Here is an example use of filter() function to filter out only even numbers
from a list.
# Program to filter out only the even items from a list
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
print(new_list)
Run Code
Output
[4, 6, 8, 12]
Here is an example use of map() function to double all the items in a list.
# Program to double each item in a list using map()
print(new_list)
Run Code
Output
What is a Module?
Consider a module to be the same as a code library.
Create a Module
To create a module just save the code you want in a file with the file
extension .py:
Example
Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
def sum1(a,b):
c=a+b
print(“sum is”,c)
Use a Module
Now we can use the module we just created, by using the import statement:
Example
Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("Suresh")
Run Example »
Variables in Module
The module can contain functions, as already described, but also variables of
all types (arrays, dictionaries, objects etc):
Example
Save this code in the file mymodule.py
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Example
Import the module named mymodule, and access the person1 dictionary:
import mymodule
a = mymodule.person1["age"]
print(a)
O/P: 36
Naming a Module
You can name the module file whatever you like, but it must have the file
extension .py
Re-naming a Module
You can create an alias when you import a module, by using the as keyword:
Example
Create an alias for mymodule called mx:
import mymodule as mx
a = mx.person1["age"]
print(a)
O/P: 36
Built-in Modules
There are several built-in modules in Python, which you can import whenever
you like.
Example
Import and use the platform module:
import platform
x = platform.system()
print(x)
Python datetime
Python has a module named datetime to work with dates and times.
import datetime
datetime_object = datetime.datetime.now()
print(datetime_object)
When you run the program, the output will be something like:
2018-12-19 09:26:03.478039
date_object = date.today()
print(date_object)
When you run the program, the output will be something like:
2018-12-19
In this program, we have used today() method defined in the date class to
get a date object containing the current local date.
What's inside datetime?
We can use dir() function to get a list containing all attributes of a module.
import datetime
print(dir(datetime))
date Class
time Class
datetime Class
timedelta Class
datetime.date Class
You can instantiate date objects from the date class. A date object
represents a date (year, month and day).
Example 3: Date object to represent a date
import datetime
d = datetime.date(2019, 4, 13)
print(d)
2019-04-13
a = date(2019, 4, 13)
print(a)
You can create a date object containing the current date by using a
classmethod named today() . Here's how:
today = date.today()
timestamp = date.fromtimestamp(1326244364)
print("Date =", timestamp)
Date = 2012-01-11
datetime.time
A time object instantiated from the time class represents the local time.
Example 7: Time object to represent time
a = 00:00:00
b = 11:34:56
c = 11:34:56
d = 11:34:56.234566
hour = 11
minute = 34
second = 56
microsecond = 0
datetime.datetime
The datetime module has a class named datetime that can contain
information from both date and time objects.
Example 9: Python datetime object
2018-11-28 00:00:00
2017-11-28 23:55:59.342380
The first three arguments year , month and day in the datetime() constructor are
mandatory.
Example 10: Print year, month, hour, minute and timestamp
year = 2017
month = 11
day = 28
hour = 23
minute = 55
timestamp = 1511913359.34238
datetime.timedelta
A timedelta object represents the difference between two dates or times.
Example 11: Difference between two dates and times
t3 = 14 days, 13:55:39
Here, we have created two timedelta objects t1 and t2 , and their difference
is printed on the screen.
t1 = timedelta(seconds = 33)
t2 = timedelta(seconds = 54)
t3 = t1 - t2
t3 = -1 day, 23:59:39
t3 = 0:00:21
You can also find sum of two dates and times using + operator. Also, you
can multiply and divide a timedelta object by integers and floats.
Python format datetime
The way date and time is represented may be different in different places,
organizations etc. It's more common to use mm/dd/yyyy in the US,
whereas dd/mm/yyyy is more common in the UK.
t = a.strftime("%H:%M:%S")
print("time:", t)
s1 = a.strftime("%m/%d/%Y, %H:%M:%S")
# mm/dd/YY H:M:S format
print("s1:", s1)
s2 = a.strftime("%d/%m/%Y, %H:%M:%S")
# dd/mm/YY H:M:S format
print("s2:", s2)
When you run the program, the output will be something like:
time: 04:34:52
s1: 12/26/2018, 04:34:52
s2: 26/12/2018, 04:34:52
Here, %Y , %m , %d , %H etc. are format codes. The strftime() method takes one
or more format codes and returns a formatted string based on it.
In the above program, t , s1 and s2 are strings.
%Y - year [0001,..., 2018, 2019,..., 9999]
%m - month [01, 02, ..., 11, 12]
%d - day [01, 02, ..., 30, 31]
%H - hour [00, 01, ..., 22, 23
%M - minute [00, 01, ..., 58, 59]
Sunday,
%A Full weekday name.
Monday, ...
January,
%B Full month name.
February, ...
etc.
Mon Sep 30
%c Locale’s appropriate date and time representation.
07:06:05 2013
Files
Files are named locations on disk to store related information. They are
used to permanently store data in a non-volatile memory (e.g. hard disk).
Since Random Access Memory (RAM) is volatile (which loses its data
when the computer is turned off), we use files for future use of the data by
permanently storing them.
When we want to read from or write to a file, we need to open it first. When
we are done, it needs to be closed so that the resources that are tied with
the file are freed.
1. Open a file
We can specify the mode while opening a file. In mode, we specify whether
we want to read r , write w or append a to the file. We can also specify if we
want to open the file in text mode or binary mode.
The default is reading in text mode. In this mode, we get strings when
reading from the file.
On the other hand, binary mode returns bytes and this is the mode to be
used when dealing with non-text files like images or executable files.
Mode Description
w Opens a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
x Opens a file for exclusive creation. If the file already exists, the operation fails.
Opens a file for appending at the end of the file without truncating it. Creates a new file if it does
a
not exist.
Unlike other languages, the character a does not imply the number 97 until
it is encoded using ASCII (or other equivalent encodings).
Moreover, the default encoding is platform dependent. In windows, it
is cp1252 but utf-8 in Linux.
So, we must not also rely on the default encoding or else our code will
behave differently in different platforms.
Closing a file will free up the resources that were tied with the file. It is done
using the close() method available in Python.
Python has a garbage collector to clean up unreferenced objects but we
must not rely on it to close the file.
try:
f = open("test.txt", encoding = 'utf-8')
# perform file operations
finally:
f.close()
This way, we are guaranteeing that the file is properly closed even if an
exception is raised that causes program flow to stop.
The best way to close a file is by using the with statement. This ensures
that the file is closed when the block inside the with statement is exited.
We don't need to explicitly call the close() method. It is done internally.
This program will create a new file named test.txt in the current directory if
it does not exist. If it does exist, it is overwritten.
We must include the newline characters ourselves to distinguish the
different lines.
''
We can see that the read() method returns a newline as '\n' . Once the end
of the file is reached, we get an empty string on further reading.
We can change our current file cursor (position) using the seek() method.
Similarly, the tell() method returns our current position (in number of
bytes).
We can read a file line-by-line using a for loop. This is both efficient and
fast.
In this program, the lines in the file itself include a newline character \n . So,
we use the end parameter of the print() function to avoid two newlines
when printing.
Alternatively, we can use the readline() method to read individual lines of a
file. This method reads a file till the newline, including the newline
character.
>>> f.readline()
'This is my first file\n'
>>> f.readline()
'This file\n'
>>> f.readline()
'contains three lines\n'
>>> f.readline()
''
Lastly, the readlines() method returns a list of remaining lines of the entire
file. All these reading methods return empty values when the end of file
(EOF) is reached.
>>> f.readlines()
['This is my first file\n', 'This file\n', 'contains three lines\n']
Here is the complete list of methods in text mode with a brief description:
Method Description
close() Closes an opened file. It has no effect if the file is already closed.
detach() Separates the underlying binary buffer from the TextIOBase and returns it.
Reads at most n characters from the file. Reads till end of file if it is
read( n )
negative or None .
Reads and returns one line from the file. Reads in at most n bytes if
readline( n =-1)
specified.
Reads and returns a list of lines from the file. Reads in at most n
readlines( n =-1)
bytes/characters if specified.
tell() Returns an integer that represents the current position of the file's object.
Resizes the file stream to size bytes. If size is not specified, resizes to
truncate( size = None )
current location.
write( s ) Writes the string s to the file and returns the number of characters written.