Introduction
1. Python History and Versions
o Python laid its foundation in the late 1980s.
o The implementation of Python was started in the December 1989 by Guido Van Rossum at CWI in Netherland.
o In February 1991, van Rossum published the code (labeled version 0.9.0) to alt.sources. o In 1994, Python 1.0 was released with new features like: lambda, map, filter, and reduce. o Python 2.0 added new features like: list comprehensions, garbage collection system.
o On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to rectify fundamental flaw of the language.
o ABC programming language is said to be the predecessor of Python language which was capable of Exception Handling and interfacing with Amoeba Operating System.
o Python is influenced by following programming languages: o ABC language.
o Modula-3 2. Python Version
Python programming language is being updated regularly with new features and supports. There are lots of updations in python versions, started from 1994 to current release.
A list of python versions with its released date is given below.
Python Version Released Date
Python 1.0 January 1994 Python 1.5 December 31, 1997 Python 1.6 September 5, 2000 Python 2.0 October 16, 2000 Python 2.1 April 17, 2001 Python 2.2 December 21, 2001 Python 2.3 July 29, 2003 Python 2.4 November 30, 2004
Python 2.5 September 19, 2006 Python 2.6 October 1, 2008 Python 2.7 July 3, 2010 Python 3.0 December 3, 2008 Python 3.1 June 27, 2009 Python 3.2 February 20, 2011 Python 3.3 September 29, 2012 Python 3.4 March 16, 2014 Python 3.5 September 13, 2015 Python 3.6 December 23, 2016 Python 3.7 June 27, 2018 Next Topic
3. How to Install Python (Environment Set-up)
In this section of the tutorial, we will discuss the installation of python on various operating systems.
3.1. Installation on Windows
Visit the link https://www.python.org/downloads/ to download the latest release of Python. In this process, we will install Python 3.6.7 on our Windows operating system.
Double-click the executable file which is downloaded; the following window will open. Select Customize installation and proceed.
The following window shows all the optional features. All the features need to be installed and are checked by default; we need to click next to continue.
The following window shows a list of advanced options. Check all the options which you want to install and click next. Here, we must notice that the first check-box (install for all users) must be checked.
To set the path on Python, we need to set the environment variable.
Type PATH as the variable name and set the path to the installation directory of the python shown in the below image
Now the path is set, we are ready to run python on our system. Restart CMD and type python again. It will open the python interpreter shell where we can execute the python statements. 4. Environment Variables
Environment variables are a key value pairs that can affect how a program runs. They need to be set at some point before a process is run so the process can read them in and act accordingly. A lot of times in production environments your database name and password are set as environment variables so that information does not end up in a code repository somewhere.
By relying on an environment variable your code doesn't care what a setting is because you can set that at some other point. Actually working with environment variables is really simple. All you need to start is import os and you are off to the races.
5. Executing Python from command line
Python code files can be created with any plain text editor. If you are new to Python programming, you can try Sublime Text, which is a powerful and easy-to-use editor, but you can use any editor you like.
To keep moving forward in this tutorial, you’ll need to create a test script. Open your favorite text editor and write the following code:
1 #!/usr/bin/env python3 2
3 print('Hello World!')
Save the file in your working directory with the name hello.py. With the test script ready, you can continue reading.
Using the python Command
To run Python scripts with the python command, you need to open a command-line and type in the word python, or python3 if you have both versions, followed by the path to your script, just like this:
$ python3 hello.py
Hello World!
If everything works okay, after you press Enter you’ll see the phrase Hello World! on your screen. That’s it! You’ve just run your first Python script!
If this doesn’t work right, maybe you’ll need to check your system PATH, your Python installation, the way you created the hello.py script, the place where you saved it, and so on. This is the most basic and practical way to run Python scripts.
Basic Python Syntax
1.String
Python has a built-in string class named "str" with many handy features (there is an older module named "string" which you should not use). String literals can be enclosed by either double or single quotes, although single quotes are more commonly used. Backslash escapes work the usual way within both single and double quoted literals -- e.g. \n \' \". A double quoted string literal can contain single quotes without any fuss (e.g. "I didn't do it") and likewise single quoted string can contain double quotes. A string literal can span multiple lines, but there must be a backslash \ at the end of each line to escape the newline. String literals inside triple quotes, """ or ''', can span multiple lines of text.
Python strings are "immutable" which means they cannot be changed after they are created (Java strings also use this immutable style). Since strings can't be changed, we construct *new* strings as we go to represent computed values. So for example the expression ('hello' + 'there') takes in the 2 strings 'hello' and 'there' and builds a new string 'hellothere'.
Characters in a string can be accessed using the standard [ ] syntax, and like Java and C++, Python uses zero-based indexing, so if s is 'hello' s[1] is 'e'. If the index is out of bounds for the string, Python raises an error. The Python style (unlike Perl) is to halt if it can't tell what to do,
rather than just make up a default value. The handy "slice" syntax (below) also works to extract any substring from a string. The len(string) function returns the length of a string. The [ ] syntax and the len() function actually work on any sequence type -- strings, lists, etc.. Python tries to make its operations work consistently across different types. Python newbie gotcha: don't use "len" as a variable name to avoid blocking out the len() function. The '+' operator can
concatenate two strings. Notice in the code below that variables are not pre-declared -- just assign to them and go.
s = 'hi'
print s[1] ## i
print len(s) ## 2
print s + ' there' ## hi there
Unlike Java, the '+' does not automatically convert numbers or other types to string form. The str() function converts values to a string form so they can be combined with other strings.
pi = 3.14
##text = 'The value of pi is ' + pi ## NO, does not work
text = 'The value of pi is ' + str(pi) ## yes
For numbers, the standard operators, +, /, * work in the usual way. There is no ++ operator, but +=, -=, etc. work. If you want integer division, it is most correct to use 2 slashes -- e.g. 6 // 5 is 1 (previous to python 3000, a single / does int division with ints anyway, but moving forward // is the preferred way to indicate that you want int division.)
The "print" operator prints out one or more python items followed by a newline (leave a trailing comma at the end of the items to inhibit the newline). A "raw" string literal is prefixed by an 'r' and passes all the chars through without special treatment of backslashes, so r'x\nx' evaluates to the length-4 string 'x\nx'. A 'u' prefix allows you to write a unicode string literal (Python has lots of other unicode support features -- see the docs below).
raw = r'this\t\n and that'
# this\t\n and that
print raw
multi = """It was the best of times. It was the worst of times."""
# It was the best of times.
# It was the worst of times.
print multi
2.String Methods
Here are some of the most common string methods. A method is like a function, but it runs "on" an object. If the variable s is a string, then the code s.lower() runs the lower() method on that string object and returns the result (this idea of a method running on an object is one of the basic
ideas that make up Object Oriented Programming, OOP). Here are some of the most common string methods:
s.lower(), s.upper() -- returns the lowercase or uppercase version of the string
s.strip() -- returns a string with whitespace removed from the start and end
s.isalpha()/s.isdigit()/s.isspace()... -- tests if all the string chars are in the various character classes
s.startswith('other'), s.endswith('other') -- tests if the string starts or ends with the given other string
s.find('other') -- searches for the given other string (not a regular expression) within s, and returns the first index where it begins or -1 if not found
s.replace('old', 'new') -- returns a string where all occurrences of 'old' have been replaced by 'new'
s.split('delim') -- returns a list of substrings separated by the given delimiter. The delimiter is not a regular expression, it's just text. 'aaa,bbb,ccc'.split(',') -> ['aaa', 'bbb', 'ccc']. As a convenient special case s.split() (with no arguments) splits on all whitespace chars.
s.join(list) -- opposite of split(), joins the elements in the given list together using the string as the delimiter. e.g. '---'.join(['aaa', 'bbb', 'ccc']) -> aaa---bbb---ccc
3.The % method
Python has a printf()-like facility to put together a string. The % operator takes a printf-type format string on the left (%d int, %s string, %f/%g floating point), and the matching values in a tuple on the right (a tuple is made of values separated by commas, typically grouped inside parentheses):
# % operator
text = "%d little pigs come out, or I'll %s, and I'll %s, and I'll blow your %s down." % (3, 'huff',
'puff', 'house')
The above line is kind of long -- suppose you want to break it into separate lines. You cannot just split the line after the '%' as you might in other languages, since by default Python treats each line as a separate statement (on the plus side, this is why we don't need to type semi-colons on each line). To fix this, enclose the whole expression in an outer set of parenthesis -- then the expression is allowed to span multiple lines. This code-across-lines technique works with the various grouping constructs detailed below: ( ), [ ], { }.
# Add parentheses to make the long line work:
text = (
"%d little pigs come out, or I'll %s, and I'll %s, and I'll blow your %s down."
% (3, 'huff', 'puff', 'house'))
That's better, but the line is still a little long. Python lets you cut a line up into chunks, which it will then automatically concatenate. So, to make this line even shorter, we can do this:
# Split the line into chunks, which are concatenated automatically by Python
text = (
"or I'll %s, and I'll %s, "
"and I'll blow your %s down."
% (3, 'huff', 'puff', 'house'))
4.The Print function
The simplest way to produce output is using the print() function where you can pass zero or more expressions separated by commas. This function converts the expressions you pass into a string before writing to the screen.
Syntax: print(value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush) Parameters:
value(s) : Any value, and as many as you like. Will be converted to string before printed sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than one.Default :’ ‘
end=’end’: (Optional) Specify what to print at the end.Default : ‘\n’ file : (Optional) An object with a write method. Default :sys.stdout
flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False). Default: False
Language Components 1.The if statement
Syntax for using the if keyword is as follows: if [conditional expression]:
[statement(s) to execute]
if keyword and the conditional expression is ended with a colon. In [conditional
expression] some conditional expression is introduced that is supposed to return a boolean value, i.e., True or False. If the resulting value is True then the [statement to execute] is executed, which is mentioned below the if condition with a tabspace(This indentation is very important).
2. Relational and Logical Operator 2.1.Relational operator
Relational operators are used to establish some sort of relationship between the two operands. Some of the relevant examples could be less than, greater than or equal to operators. Python language is capable of understanding these types of operators and accordingly return the output, which can be either True or False.
1. Less than → used with < 2. Greater than → used with > 3. Equal to → used with == 4. Not equal to → used with !=
5. Less than or equal to → used with <= 6. Greater than or equal to → used with >=
2.2. Logical Operators
Logical operators, as the name suggests are used in logical expressions where the operands are either True or False. The operands in a logical expression, can be expressions which
returns Trueor False upon evaluation. There are three basic types of logical operators:
1. Logical AND: For AND operation the result is True if and only if both operands are True. The keyword used for this operator is and.
2. Logical OR: For OR operation the result is True if either of the operands is True. The keyword used for this operator is or.
3. Logical NOT: The result is True if the operand is False. The keyword used for this operator is
4. The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true.
5. We generally use this loop when we don't know beforehand, the number of times to iterate.
3. The while Loop
while test_expression:
Body of while
In while loop, test expression is checked first. The body of the loop is entered only the test_expression evaluates to True. After one iteration, the test expression is checked again. This process continues until the test_expression evaluates to False.In Python, the body of the while loop is determined through indentation.Body starts with indentation and the first unindented line marks the end.Python interprets any non-zero value as True. None and 0 are interpreted as False.
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects. Iterating over a sequence is called traversal.
Syntax of for Loop for val in sequence:
Body of for
Here, val is the variable that takes the value of the item inside the sequence on each iteration. Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation.
Collection
1.List
A list is a collection which is ordered and changeable. In Python lists are written with square brackets.
Example Create a List:
thislist = ["apple", "banana", "cherry"] print(thislist)
C:\Users\My Name>python demo_list.py ['apple', 'banana', 'cherry']
1.1. Access Items
You access the list items by referring to the index number: Example
Print the second item of the list: thislist = ["apple", "banana", "cherry"] print(thislist[1])
C \Users\My Name>python demo_list_access.py 1.2. Change Item Value
To change the value of a specific item, refer to the index number: Example
Change the second item:
thislist = ["apple", "banana", "cherry"] thislist[1] = "blackcurrant"
print(thislist)
C:\Users\My Name>python demo_list_change.py ['apple', 'blackcurrant', 'cherry']
1.3. Loop Through a List
You can loop through the list items by using a for loop: Example
Print all items in the list, one by one: thislist = ["apple", "banana", "cherry"] for x in thislist:
print(x)
1.3. Check if Item Exists
To determine if a specified item is present in a list use the in keyword: Example
Check if "apple" is present in the list: thislist = ["apple", "banana", "cherry"] if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
C:\Users\My Name>python demo_list_loop.py Apple
Banana cherry
1.4. List Length
To determine how many items a list has, use the len() method: Example
Print the number of items in the list: thislist = ["apple", "banana", "cherry"] print(len(thislist))
Output 3
1.5. Add Items
To add an item to the end of the list, use the append() method: Example
Using the append() method to append an item: thislist = ["apple", "banana", "cherry"]
thislist.append("orange") print(thislist)
:\Users\My Name>python demo_list_append.py ['apple', 'banana', 'cherry', 'orange']
To add an item at the specified index, use the insert() method: Example
Insert an item as the second position: thislist = ["apple", "banana", "cherry"] thislist.insert(1, "orange")
print(thislist) output
C:\Users\My Name>python demo_list_insert.py ['apple', 'orange', 'banana', 'cherry']
1.6. Remove Item
There are several methods to remove items from a list: Example
The remove() method removes the specified item: thislist = ["apple", "banana", "cherry"]
thislist.remove("banana") print(thislist)
Output
C:\Users\My Name>python demo_list_remove.py ['apple', 'cherry']
Example
The pop() method removes the specified index, (or the last item if index is not specified): thislist = ["apple", "banana", "cherry"]
thislist.pop() print(thislist) Example
The del keyword removes the specified index: thislist = ["apple", "banana", "cherry"]
del thislist[0] print(thislist) Output
C:\Users\My Name>python demo_list_del.py ['banana', 'cherry']
Example
thislist = ["apple", "banana", "cherry"] del thislist
C:\Users\My Name>python demo_list_del2.py Traceback (most recent call last):
File "demo_list_del2.py", line 3, in <module>
print(thislist) #this will cause an error because you have succsesfully deleted "thislist". NameError: name 'thislist' is not defined
Example
The clear() method empties the list:thislist = ["apple", "banana", "cherry"] thislist.clear()
print(thislist) 1.7. Copy a List
You cannot copy a list simply by typing list2 = list1, because: list2 will only be
a reference to list1, and changes made in list1 will automatically also be made in list2. There are ways to make a copy, one way is to use the built-in List method copy(). Example
Make a copy of a list with the copy() method: thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy() print(mylist)
C:\Users\My Name>python demo_list_copy.py ['apple', 'banana', 'cherry']
Another way to make a copy is to use the built-in method list(). Example
Make a copy of a list with the list() method: thislist = ["apple", "banana", "cherry"] mylist = list(thislist)
C:\Users\My Name>python demo_list_copy2.py ['apple', 'banana', 'cherry']
2.Set
A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.
Example Create a Set:
thisset = {"apple", "banana", "cherry"} print(thisset)
2.1. Access Items
You cannot access items in a set by referring to an index, since sets are unordered the items has no index.
But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using thein keyword.
Example
Loop through the set, and print the values: thisset = {"apple", "banana", "cherry"} for x in thisset:
print(x) Example
Check if "banana" is present in the set: thisset = {"apple", "banana", "cherry"} print("banana" in thisset)
2.2. Change Items
Once a set is created, you cannot change its items, but you can add new items. 2.3. Add Items
To add one item to a set use the add() method.
To add more than one item to a set use the update() method. Example
Add an item to a set, using the add() method: thisset = {"apple", "banana", "cherry"} thisset.add("orange")
print(thisset) Example
Add multiple items to a set, using the update() method: thisset = {"apple", "banana", "cherry"}
thisset.update(["orange", "mango", "grapes"]) print(thisset)
2.4. Get the Length of a Set
To determine how many items a set has, use the len() method. Example
Get the number of items in a set: thisset = {"apple", "banana", "cherry"} print(len(thisset))
2.5. Remove Item
To remove an item in a set, use the remove(), or the discard() method. Example
Remove "banana" by using the remove() method: thisset = {"apple", "banana", "cherry"}
thisset.remove("banana") print(thisset)
Example
Remove "banana" by using the discard() method: thisset = {"apple", "banana", "cherry"}
thisset.discard("banana") print(thisset)
Note: If the item to remove does not exist, discard() will NOT raise an error.
You can also use the pop(), method to remove an item, but this method will remove the last item. Remember that sets are unordered, so you will not know what item that gets removed.
The return value of the pop() method is the removed item. Example
Remove the last item by using the pop() method: thisset = {"apple", "banana", "cherry"}
x = thisset.pop() print(x)
Example
The clear() method empties the set: thisset = {"apple", "banana", "cherry"} thisset.clear()
print(thisset) Example
The del keyword will delete the set completely: thisset = {"apple", "banana", "cherry"}
del thisset print(thisset)
2.6.The set() Constructor
It is also possible to use the set() constructor to make a set. Example
Using the set() constructor to make a set:
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets print(thisset)
2.7. Set Methods
Python has a set of built-in methods that you can use on sets.
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 other 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
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 the union of this set and others
3. Dictionaries
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values.
Example
Create and print a dictionary: thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(thisdict)
3.1. Accessing Items
You can access the items of a dictionary by referring to its key name, inside square brackets: Example
Get the value of the "model" key: x = thisdict["model"]
There is also a method called get() that will give you the same result: Example
Get the value of the "model" key: x = thisdict.get("model")
3.2. Change Values
You can change the value of a specific item by referring to its key name: Example
Change the "year" to 2018: thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict["year"] = 2018
3.3. Loop Through a Dictionary
You can loop through a dictionary by using a for loop.
When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.
Example
Print all key names in the dictionary, one by one: for x in thisdict:
print(x) Example
Print all values in the dictionary, one by one: for x in thisdict:
print(thisdict[x]) Example
You can also use the values() function to return values of a dictionary: for x in thisdict.values():
print(x) Example
Loop through both keys and values, by using the items() function: for x, y in thisdict.items():
print(x, y)
3.4. Check if Key Exists
To determine if a specified key is present in a dictionary use the in keyword: Example
Check if "model" is present in the dictionary: thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } if "model" in thisdict:
3.5. Dictionary Length
To determine how many items (key-value pairs) a dictionary has, use the len() method. Example
Print the number of items in the dictionary: print(len(thisdict))
3.6. Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a value to it: Example thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict["color"] = "red" print(thisdict) 3.7. Removing Items
There are several methods to remove items from a dictionary: Example
The pop() method removes the item with the specified key name: thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict.pop("model") print(thisdict)
Example
The popitem() method removes the last inserted item (in versions before 3.7, a random item is removed instead): thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict.popitem() print(thisdict) Example
The del keyword removes the item with the specified key name: thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } del thisdict["model"] print(thisdict) Example
The del keyword can also delete the dictionary completely: thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer exists. Example
The clear() keyword empties the dictionary: thisdict = {
"model": "Mustang", "year": 1964 } thisdict.clear print(thisdict) 3.8. Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to dict1, and changes made in dict1 will automatically also be made in dict2. There are ways to make a copy, one way is to use the built-in Dictionary method copy(). Example
Make a copy of a dictionary with the copy() method: thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } Modules
A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use. A module is a Python object with arbitrarily named attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions, classes and variables. A module can also include runnable code.
Example
The Python code for a module named aname normally resides in a file named aname.py. Here's an example of a simple module, support.py
def print_func( par ): print "Hello : ", par return
You can use any Python source file as a module by executing an import statement in some other Python source file. The import has the following syntax −
import module1[, module2[,... moduleN]
When the interpreter encounters an import statement, it imports the module if the module is present in the search path. A search path is a list of directories that the interpreter searches before importing a module. For example, to import the module support.py, you need to put the
following command at the top of the script − #!/usr/bin/python
# Import module support import support
# Now you can call defined function that module as follows support.print_func("Zara")
When the above code is executed, it produces the following result − Hello : Zara
2. Standard module-Sys
The sys module provides information about constants, functions and methods of the Python interpreter. dir(system) gives a summary of the available constants, functions and methods. Another possibility is the help() function. Using help(sys) provides valuable detail information. The module sys informs e.g. about the maximal recursion depth (sys.getrecursionlimit() ) and provides the possibility to change (sys.setrecursionlimit())
The current version number of Python can be accessed as well: >>> import sys >>> sys.version '2.6.5 (r265:79063, Apr 16 2010, 13:57:41) \n[GCC 4.4.3]' >>> sys.version_info (2, 6, 5, 'final', 0) >>>
3.Standard module-math
The math module is a standard module in Python and is always available. To use mathematical functions under this module, you have to import the module using import math.
3.1.Functions in Python Math Module
Here is the list of all the functions and attributes defined in math module with a brief explanation of what they do.
List of Functions in Python Math Module
Function Description
ceil(x) Returns the smallest integer greater than or equal to x.
copysign(x,
y) Returns x with the sign of y
fabs(x) Returns the absolute value of x
factorial(x) Returns the factorial of x
floor(x) Returns the largest integer less than or equal to x
fmod(x, y) Returns the remainder when x is divided by y
frexp(x) Returns the mantissa and exponent of x as the pair (m, e)
fsum(iterable) Returns an accurate floating point sum of values in the iterable
isfinite(x) Returns True if x is neither an infinity nor a NaN (Not a Number)
isinf(x) Returns True if x is a positive or negative infinity
isnan(x) Returns True if x is a NaN
ldexp(x, i) Returns x * (2**i)
modf(x) Returns the fractional and integer parts of x
trunc(x) Returns the truncated integer value of x
exp(x) Returns e**x
expm1(x) Returns e**x – 1
log(x[, base]) Returns the logarithm of x to the base (defaults to e)
log1p(x) Returns the natural logarithm of 1+x
log2(x) Returns the base-2 logarithm of x
log10(x) Returns the base-10 logarithm of x
pow(x, y) Returns x raised to the power y
sqrt(x) Returns the square root of x
acos(x) Returns the arc cosine of x
asin(x) Returns the arc sine of x
Standard 4.standard module- time
Python has defined a module, “time” which allows us to handle various operations regarding time, its conversions and representations, which find its use in various applications in life. The beginning of time is started measuring from 1 January, 12:00 am, 1970 and this very time is termed as “epoch” in Python.
4.1. Operations on Time :
4.1.1. time() :- This function is used to count the number of seconds elapsed since the epoch.
4.1.2. gmtime(sec) :- This function returns a structure with 9 values each representing a time attribute in sequence. It converts seconds into time attributes(days, years, months etc.)till specified seconds from epoch. If no seconds are mentioned, time is calculated till present. The structure attribute table is given below.
4.1.3. asctime(“time”) :- This function takes a time attributed string produced by gmtime() and returns a 24 character string denoting time.
4.1.4. ctime(sec) :- This function returns a 24 character time string but takes seconds as argument and computes time till mentioned seconds. If no argument is passed, time is calculated till
present.
atan2(y, x) Returns atan(y / x)
cos(x) Returns the cosine of x
hypot(x, y) Returns the Euclidean norm, sqrt(x*x + y*y)
sin(x) Returns the sine of x
tan(x) Returns the tangent of x
degrees(x) Converts angle x from radians to degrees
radians(x) Converts angle x from degrees to radians
acosh(x) Returns the inverse hyperbolic cosine of x
4.1.5. sleep(sec) :- This method is used to hault the program execution for the time specified in the arguments.
Exceptions
Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions and are not unconditionally fatal: you will soon learn how to handle them in Python programs. Most exceptions are not handled by programs, however, and result in error messages as shown here: 1.Handling multiple exceptions
It is possible to write programs that handle selected exceptions. Look at the following example, which asks the user for input until a valid integer has been entered, but allows the user to interrupt the program (using Control-Cor whatever the operating system supports); note that a user-generated interruption is signalled by raising the KeyboardInterrupt exception.
>>>
>>> while True: ... try:
... x = int(input("Please enter a number: ")) ... break
... except ValueError:
... print("Oops! That was no valid number. Try again...") ...
The try statement works as follows.
First, the try clause (the statement(s) between the try and except keywords) is executed. If no exception occurs, the except clause is skipped and execution of the try statement is
finished.
If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement.
If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.
2. Raise
The raise statement allows the programmer to force a specified exception to occur. For example:
>>> raise NameError('HiThere') Traceback (most recent call last):
File "<stdin>", line 1, in <module> NameError: HiThere
The sole argument to raise indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives from Exception). If an exception class is passed, it will be implicitly instantiated by calling its constructor with no arguments:
raise ValueError # shorthand for 'raise ValueError()'
If you need to determine whether an exception was raised but don’t intend to handle it, a simpler form of the raise statement allows you to re-raise the exception:
>>> >>> try:
... raise NameError('HiThere') ... except NameError:
... print('An exception flew by!') ... raise
...
An exception flew by!
Traceback (most recent call last): File "<stdin>", line 2, in <module> NameError: HiThere
Input and Output 1. Introduction
Like all high-level languages, Python is easy to read, takes less time to write, and is portable. This versatile programming language has two versions: Python 2 and Python 3. Wiki says: Python 2.x is legacy, Python 3.x is the present and future of the language. That is, Python 2 is no longer in development and all new features will be added in Python 3. Note that, keeping this in mind, the code examples in this tutorial are in Python 3. Wherever Python 2.x code is shown, it will be highlighted.
2. Access Modes
Access modes govern the type of operations possible in the opened file. It refers to how the file will be used once its opened. These modes also define the location of the File Handle in the file. File handle is like a cursor, which defines from where the data has to be read or written in the file. There are 6 access modes in python.
2.1.Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning of the file. If the file does not exists, raises I/O error. This is also the default mode in which file is opened.
2.2. Read and Write (‘r+’) : Open the file for reading and writing. The handle is positioned at the beginning of the file. Raises I/O error if the file does not exists.
2.3. Write Only (‘w’) : Open the file for writing. For existing file, the data is truncated and over-written. The handle is positioned at the beginning of the file. Creates the file if the file does not exists.
2.4. Write and Read (‘w+’) : Open the file for reading and writing. For existing file, data is truncated and over-written. The handle is positioned at the beginning of the file.
2.5.Append Only (‘a’) : Open the file for writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.
2.6.Append and Read (‘a+’) : Open the file for reading and writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.
3.Writing Data to a File
In order to write into a file in Python, we need to open it in write 'w', append 'a' or exclusive creation 'x' mode.
We need to be careful with the 'w' mode as it will overwrite into the file if it already exists. All previous data are erased.
Writing a string or sequence of bytes (for binary files) is done using write() method. This method returns the number of characters written to the file.
with open("test.txt",'w',encoding = 'utf-8') as f: f.write("my first file\n")
f.write("This file\n\n")
f.write("contains three lines\n")
This program will create a new file named 'test.txt' if it does not exist. If it does exist, it is overwritten.
4.Reading data to a File
To read a file in Python, we must open the file in reading mode.
There are various methods available for this purpose. We can use the read(size) method to read in size number of data. If size parameter is not specified, it reads and returns up to the end of the file.
>>> f = open("test.txt",'r',encoding = 'utf-8') >>> f.read(4) # read the first 4 data
'This'
>>> f.read(4) # read the next 4 data ' is '
>>> f.read() # read in the rest till end of file 'my first file\nThis file\ncontains three lines\n'
>>> f.read() # further reading returns empty sting ''
We can see that, the read() method returns newline as '\n'. Once the end of file is reached, we get 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).
>>> f.tell() # get the current file position 56
>>> f.seek(0) # bring file cursor to initial position 0
>>> print(f.read()) # read the entire file This ismy first file
This file
We can read a file line-by-line using a for loop. This is both efficient and fast. >>> for line in f:
... print(line, end = '') ...
This ismy first file This file
contains three lines
The lines in file itself has a newline character '\n'.
Moreover, the print() end parameter to avoid two newlines when printing.
Alternately, we can use 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 method return empty values when end of file (EOF) is reached.
>>> f.readlines()
['This is my first file\n', 'This file\n', 'contains three lines\n'] Classes in Python
Focusing first on the data, each thing or object is an instance of some class.
The primitive data structures available in Python, like numbers, strings, and lists are designed to represent simple things like the cost of something, the name of a poem, and your favorite colors, respectively.
What if you wanted to represent something much more complicated? For example, let’s say you wanted to track a number of different animals. If you used a list, the first element could be the animal’s name while the second element could represent its age. How would you know which element is supposed to be which? What if you had 100 different animals? Are you certain each animal has both a name and an age, and so forth? What if you wanted to add other properties to these animals? This lacks organization, and it’s the exact need for classes.
Classes are used to create new user-defined data structures that contain arbitrary information about something. In the case of an animal, we could create an Animal() class to track properties about the Animal like the name and age.
It’s important to note that a class just provides structure—it’s a blueprint for how something should be defined, but it doesn’t actually provide any real content itself. The Animal() class may specify that the name and age are necessary for defining an animal, but it will not actually state what a specific animal’s name or age is.
It may help to think of a class as an idea for how something should be defined. 2.Python Objects (Instances)
While the class is the blueprint, an instance is a copy of the class with actual values, literally an object belonging to a specific class. It’s not an idea anymore; it’s an actual animal, like a dog named Roger who’s eight years old.
Put another way, a class is like a form or questionnaire. It defines the needed information. After you fill out the form, your specific copy is an instance of the class; it contains actual information relevant to you.
You can fill out multiple copies to create many different instances, but without the form as a guide, you would be lost, not knowing what information is required. Thus, before you can create individual instances of an object, we must first specify what is needed by defining a class. 3. How To Define a Class in Python
Defining a class is simple in Python: class Dog:
You start with the class keyword to indicate that you are creating a class, then you add the name of the class (using CamelCase notation, starting with a capital letter.)
Also, we used the Python keyword pass here. This is very often used as a place holder where code will eventually go. It allows us to run this code without throwing an error.
The (object) part in parentheses specifies the parent class that you are inheriting from (more on this below.) In Python 3 this is no longer necessary because it is the implicit default.
3.1.Instance Attributes
All classes create objects, and all objects contain characteristics called attributes (referred to as properties in the opening paragraph). Use the __init__() method to initialize (e.g., specify) an object’s initial attributes by giving them their default value (or state). This method must have at least one argument as well as the self variable, which refers to the object itself (e.g., Dog). class Dog:
# Initializer / Instance Attributes def __init__(self, name, age): self.name = name
self.age = age
In the case of our Dog() class, each dog has a specific name and age, which is obviously important to know for when you start actually creating different dogs. Remember: the class is just for defining the Dog, not actually creating instances of individual dogs with specific names and ages; we’ll get to that shortly.
Similarly, the self variable is also an instance of the class. Since instances of a class have varying values we could state Dog.name = name rather than self.name = name. But since not all dogs share the same name, we need to be able to assign different values to different instances. Hence the need for the special self variable, which will help to keep track of individual instances of each class.
4.Inheritance
Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides code reusability to the program because we can use an existing class to create a new class instead of creating it from scratch.
In inheritance, the child class acquires the properties and can access all the data members and functions defined in the parent class. A child class can also provide its specific implementation to the functions of the parent class. In this section of the tutorial, we will discuss inheritance in
detail. In python, a derived class can inherit base class by just mentioning the base in the bracket after the derived class name. Consider the following syntax to inherit a base class into the
derived class Syntax
1. class derived-class(base class): 2. <class-suite>
A class can inherit multiple classes by mentioning all of them inside the bracket. Consider the following syntax.
Syntax
1. class derive-class(<base class 1>, <base class 2>, ... <base class n>): 2. <class - suite>
Example 1 1. class Animal: 2. def speak(self):
3. print("Animal Speaking")
4. #child class Dog inherits the base class Animal 5. class Dog(Animal): 6. def bark(self): 7. print("dog barking") 8. d = Dog() 9. d.bark() 10. d.speak() Output: dog barking Animal Speaking
4.1.Python Multi-Level inheritance
Multi-Level inheritance is possible in python like other object-oriented languages. Multi-level inheritance is archived when a derived class inherits another derived class. There is no limit on the number of levels up to which, the multi-level inheritance is archived in python.
The syntax of multi-level inheritance is given below. Syntax 1. class class1: 2. <class-suite> 3. class class2(class1): 4. <class suite> 5. class class3(class2): 6. <class suite> 7. . 8. . Example 1. class Animal: 2. def speak(self): 3. print("Animal Speaking")
4. #The child class Dog inherits the base class Animal 5. class Dog(Animal):
6. def bark(self):
8. #The child class Dogchild inherits another child class Dog 9. class DogChild(Dog): 10. def eat(self): 11. print("Eating bread...") 12. d = DogChild() 13. d.bark() 14. d.speak() 15. d.eat() Output: dog barking Animal Speaking Eating bread...
4.2.Python Multiple inheritance
Python provides us the flexibility to inherit multiple base classes in the child class.
The syntax to perform multiple inheritance is given below. Syntax 1. class Base1: 2. <class-suite> 3. 4. class Base2: 5. <class-suite> 6. . 7. . 8. . 9. class BaseN:
10. <class-suite> 11.
12. class Derived(Base1, Base2, ... BaseN): 13. <class-suite> Example 1. class Calculation1: 2. def Summation(self,a,b): 3. return a+b; 4. class Calculation2: 5. def Multiplication(self,a,b): 6. return a*b; 7. class Derived(Calculation1,Calculation2): 8. def Divide(self,a,b): 9. return a/b; 10. d = Derived() 11. print(d.Summation(10,20)) 12. print(d.Multiplication(10,20)) 13. print(d.Divide(10,20)) Output: 30 200 0.5
The is subclass(sub,sup) method
The issubclass(sub, sup) method is used to check the relationships between the specified classes. It returns true if the first class is the subclass of the second class, and false otherwise.
Consider the following example. Example 1. class Calculation1: 2. def Summation(self,a,b): 3. return a+b; 4. class Calculation2: 5. def Multiplication(self,a,b): 6. return a*b; 7. class Derived(Calculation1,Calculation2): 8. def Divide(self,a,b): 9. return a/b; 10. d = Derived() 11. print(issubclass(Derived,Calculation2))
12. print(issubclass(Calculation1,Calculation2)) Output:
True False
The isinstance (obj, class) method
The isinstance() method is used to check the relationship between the objects and classes. It returns true if the first parameter, i.e., obj is the instance of the second parameter, i.e., class. Consider the following example.
Example 1. class Calculation1: 2. def Summation(self,a,b): 3. return a+b; 4. class Calculation2: 5. def Multiplication(self,a,b): 6. return a*b; 7. class Derived(Calculation1,Calculation2): 8. def Divide(self,a,b): 9. return a/b; 10. d = Derived() 11. print(isinstance(d,Derived)) Output: True Regular Expression 1.Introduction
A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions are widely used in UNIX world.
The module re provides full support for Perl-like regular expressions in Python. The re module raises the exception re.error if an error occurs while compiling or using a regular expression. We would cover two important functions, which would be used to handle regular expressions. But a small thing first: There are various characters, which would have special meaning when they are used in regular expression. To avoid any confusion while dealing with regular expressions, we would use Raw Strings as r'expression'
2.Match Object
2.1class re.MatchObject
Match objects always have a boolean value of True.
Since match() and search() return None when there is no match, you can test whether there was a match with a simple if statement:
match = re.search(pattern, string) if match:
process(match)
Match objects support the following methods and attributes: 2.2.expand(template)
Return the string obtained by doing backslash substitution on the template string template, as done by the sub() method. Escapes such as \nare converted to the appropriate characters, and numeric backreferences (\1, \2) and named backreferences (\g<1>, \g<name>) are replaced by the contents of the corresponding group.
2.3.group([group1, ...])
Returns one or more subgroups of the match. If there is a single argument, the result is a single string; if there are multiple arguments, the result is a tuple with one item per argument. Without arguments, group1 defaults to zero (the whole match is returned). If a groupN argument is zero, the corresponding return value is the entire matching string; if it is in the inclusive range [1..99], it is the string matching the corresponding parenthesized group. If a group number is negative or larger than the number of groups defined in the pattern, an IndexError exception is raised. If a group is contained in a part of the pattern that did not match, the corresponding result is None. If a group is contained in a part of the pattern that matched multiple times, the last match is returned.
>>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist") >>> m.group(0) # The entire match
'Isaac Newton'
>>> m.group(1) # The first parenthesized subgroup. 'Isaac'
>>> m.group(2) # The second parenthesized subgroup. 'Newton'
>>> m.group(1, 2) # Multiple arguments give us a tuple. ('Isaac', 'Newton')
If the regular expression uses the (?P<name>...) syntax, the groupN arguments may also be strings identifying groups by their group name. If a string argument is not used as a group name in the pattern, an IndexError exception is raised.
A moderately complicated example:
>>> m.group('first_name') 'Malcolm'
>>> m.group('last_name') 'Reynolds'
Named groups can also be referred to by their index: >>> m.group(1)
'Malcolm' >>> m.group(2) 'Reynolds'
If a group matches multiple times, only the last match is accessible: >>> m = re.match(r"(..)+", "a1b2c3") # Matches 3 times.
>>> m.group(1) # Returns only the last match. 'c3'
2.4.groups([default])
Return a tuple containing all the subgroups of the match, from 1 up to however many groups are in the pattern. The default argument is used for groups that did not participate in the match; it defaults to None. (Incompatibility note: in the original Python 1.5 release, if the tuple was one element long, a string would be returned instead. In later versions (from 1.5.1 on), a singleton tuple is returned in such cases.)
For example:
>>> m = re.match(r"(\d+)\.(\d+)", "24.1632") >>> m.groups()
('24', '1632')
If we make the decimal place and everything after it optional, not all groups might participate in the match. These groups will default to Noneunless the default argument is given:
>>> m = re.match(r"(\d+)\.?(\d+)?", "24")
>>> m.groups() # Second group defaults to None. ('24', None)
>>> m.groups('0') # Now, the second group defaults to '0'. ('24', '0')
2.5.groupdict([default])
Return a dictionary containing all the named subgroups of the match, keyed by the subgroup name. The default argument is used for groups that did not participate in the match; it defaults to None. For example:
>>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds") >>> m.groupdict()
{'first_name': 'Malcolm', 'last_name': 'Reynolds'} start([group])
end([group])
Return the indices of the start and end of the substring matched by group; group defaults to zero (meaning the whole matched substring). Return -1 if group exists but did not contribute to the match. For a match object m, and a group g that did contribute to the match, the substring matched by group g (equivalent to m.group(g)) is
m.string[m.start(g):m.end(g)]
Note that m.start(group) will equal m.end(group) if group matched a null string. For example, after m = re.search('b(c?)', 'cba'), m.start(0) is 1, m.end(0) is 2, m.start(1) and m.end(1) are both 2, and m.start(2) raises an IndexError exception. An example that will remove remove_this from email addresses:
>>> email = "tony@tiremove_thisger.net" >>> m = re.search("remove_this", email) >>> email[:m.start()] + email[m.end():] '[email protected]'
2.6.span([group])
For MatchObject m, return the 2-tuple (m.start(group), m.end(group)). Note that if group did not contribute to the match, this is (-1, -1). groupdefaults to zero, the entire match.
2.7.pos
The value of pos which was passed to the search() or match() method of the RegexObject. This is the index into the string at which the RE engine started looking for a match.
2.8.endpos
The value of endpos which was passed to the search() or match() method of the RegexObject. This is the index into the string beyond which the RE engine will not go.
2.9.lastindex
The integer index of the last matched capturing group, or None if no group was matched at all. For example, the expressions (a)b, ((a)(b)), and((ab)) will have lastindex == 1 if applied to the string 'ab', while the expression (a)(b) will have lastindex == 2, if applied to the same string.
2.10.lastgroup
The name of the last matched capturing group, or None if the group didn’t have a name, or if no group was matched at all.
3. Quantifiers
A quantifier has the form {m,n} where m and n are the minimum and maximum times the expression to which the quantifier applies must match. For
example,both e{1,1}e{1,1} and e{2,2} match feel, but neither matches felt.
Writing a quantifier after every expression would soon become tedious, and is certainly difficult to read. Fortunately, the regex language supports several convenient shorthands. If only one number is given in the quantifier, it's taken to be both the minimum and the maximum, so e{2} is the same as e{2,2}. As noted in the preceding section, if no quantifier is explicitly given, it's assumed to be 1 (that is, {1,1} or {1}); therefore, ee is the same as e{1,1}e{1,1} and e{1}e{1}, so both e{2} and ee match feelbut not felt.
Having a different minimum and maximum is often convenient. For example, to match travelled and traveled (both legitimate spellings),we could use
either travel{1,2}ed or travell{0,1}ed. The {0,1} quantification is used so often that it has its own shorthand form, ?, so another way of writing the regex (and the one most likely to be used in practice) is travell?ed.
Two other quantification shorthands are provided: A plus sign (+) stands for {1,n} ("at least one") and an asterisk (*) stands for {0,n} ("any number of"). In both cases, n is the maximum possible number allowed for a quantifier, usually at least 32767. Table 2 shows all the
quantifiers.
The + quantifier is very useful. For example, to match integers, we could use \d+ to match one or more digits. This regex could match in two places in the string 4588.91, for
example: 4588.91 and 4588.91. Sometimes typos are the result of pressing a key too long. We could use the regex bevel+ed to match the legitimate beveled and bevelled, and the
incorrect bevellled. If we wanted to standardize on the single-l spelling, and match only occurrences that had two or more l's, we could use bevell+ed to find them.
The * quantifier is less useful, simply because it can lead so often to unexpected results. For example, supposing that we want to find lines that contain comments in Python files, we might try searching for #*. But this regex will match any line whatsoever, including blank lines, because the meaning is "match any number of pound signs"—and that includes none. As a rule for those new to regexes, avoid using *at all, and if you do use it (or if you use ?), make sure that at least one other expression in the regex has a nonzero quantifier. Use at least one quantifier other than * or ?, that is, since both of these can match their expression zero times.
Often it's possible to convert * uses to + uses and vice versa. For example, we could match "tasselled" with at least one l using tassell*ed or tassel+ed, and match those with two or more l's using tasselll*ed or tassell+ed.
If we use the regex \d+ it will match 136. But why does it match all the digits, rather than just the first one? By default, all quantifiers are greedy—they match as many characters as they can. We can make any quantifier nongreedy (also called minimal) by following it with a question mark (?) symbol. (The question mark has two different meanings—on its own it's a shorthand for the {0,1} quantifier, and when it follows a quantifier it tells the quantifier to be nongreedy.) For example, \d+? can match the string 136 in three different places: 136, 136, and 136. Here's another example: \d?? matches zero or one digits, but prefers to match none since it's nongreedy; on its own it suffers the same problem as * in that it will match nothing—that is, any text at all. Table 2 Regular Expression Quantifiers
Syntax Meaning
e? or e{0,1} Greedily match zero occurrences or one occurrence of expression e.
e?? or e{0,1}? Nongreedily match zero occurrences or one occurrence of expression e.
e+ or e{1,} Greedily match one or more occurrences of expression e.
e+? or e{1,}? Nongreedily match one or more occurrences of expression e.
e* or e{0,} Greedily match zero or more occurrences of expression e.
e*? or e{0,}? Nongreedily match zero or more occurrences of expression e.
e{m} Match exactly m occurrences of expression e.
e{m,}? Nongreedily match at least m occurrences of expression e.
e{,n} Greedily match at most n occurrences of expression e.
e{,n}? Nongreedily match at most n occurrences of expression e.
e{m,n} Greedily match at least m and at most n occurrences of expression e.
e{m,n}? Nongreedily match at least m and at most n occurrences of expression e.
4.Splitting Strings
re.split(regex, subject) returns an array of strings. The array contains the parts of subject between all the regex matches in the subject. Adjacent regex matches will cause empty strings to appear in the array. The regex matches themselves are not included in the array. If the regex contains capturing groups, then the text matched by the capturing groups is included in the array. The capturing groups are inserted between the substrings that appeared to the left and right of the regex match. If you don't want the capturing groups in the array, convert them into non-capturing groups. The re.split() function does not offer an option to suppress capturing groups.
You can specify an optional third parameter to limit the number of times the subject string is split. Note that this limit controls the number of splits, not the number of strings that will end up in the array. The unsplit remainder of the subject is added as the final string to the array. If there are no capturing groups, the array will contain limit+1 items.
The behavior of re.split() has changed between Python versions when the regular expression can find zero-length matches. In Python 3.4 and prior, re.split() ignores zero-length matches. In Python 3.5 and 3.6 re.split() throws a FutureWarning when it encounters a zero-length match. This warning signals the change in Python 3.7. Now re.split() also splits on zero-length matches.