Detailed and advanced training course for mastering python
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during 1985- 1990. Like Perl, Python source code is also available under the GNU General Public License (GPL).
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages.
• Python is Interpreted: Python is processed at runtime by the interpreter. You do not need to compile your program before executing it. This is similar to PERL and PHP.
• Python is Interactive: You can actually sit at a Python prompt and interact with the interpreter directly to write your programs.
• Python is Object-Oriented: Python supports Object-Oriented style or technique of programming that encapsulates code within objects.
• Python is a Beginner's Language: Python is a great language for the beginner-level programmers and supports the development of a wide range of applications from simple text processing to WWW browsers to games.
Reserved Words
• The following list shows the Python keywords. These are reserved words and you cannot use them as constant or variable or any other identifier names. All the Python keywords contain lowercase letters only.
Standard Data Types
The data stored in memory can be of many types. For example, a person's age is stored as a numeric value and his or her address is stored as alphanumeric characters. Python has various standard data types that are used to define the operations possible on them and the storage method for each of them.
Python has five standard data types −
• Numbers
• String
• List
• Tuple
• Dictionary
Python Numbers
Number data types store numeric values. Number objects are created when you assign a value to them. For example −
You can also delete the reference to a number object by using the del statement. The syntax of the del statement is −
You can delete a single object or multiple objects by using the del statement. For example −
Python supports four different numerical types −
• int (signed integers)
• long (long integers, they can also be represented in octal and hexadecimal)
• float (floating point real values)
• complex (complex numbers)
Examples
Here are some examples of numbers −
• 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.
Python 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.
Python Lists
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 −
Tuples: o Tuple is another form of collection where different type of data can be stored.
o It is similar to list where data is separated by commas. Only the difference is that list uses square bracket and tuple uses parenthesis.
o Tuples are enclosed in parenthesis and cannot be changed.
Eg:
1. >>> tuple=('rahul',100,60.4,'deepak')
2. >>> tuple1=('sanjay',10)
3. >>> tuple
4. ('rahul', 100, 60.4, 'deepak')
5. >>> tuple[2:]
6. (60.4, 'deepak')
7. >>> tuple1[0]
8. 'sanjay'
9. >>> tuple+tuple1
10. ('rahul', 100, 60.4, 'deepak', 'sanjay', 10)
11. >>>
Dictionary:oDictionary is a collection which works on a key-value pair.
o It works like an associated array where no two keys can be same.
o Dictionaries are enclosed by curly braces ({}) and values can be retrieved by square bracket([]).
Eg:
1. >>> dictionary={'name':'charlie','id':100,'dept':'it'}
2. >>> dictionary
3. {'dept': 'it', 'name': 'charlie', 'id': 100}
4. >>> ()
5. ['dept', 'name', 'id']
6. >>> dictionary.values()
7. ['it', 'charlie', 100]
Python Variables
Variable is a name of the memory location where data is stored. Once a variable is stored that means a space is allocated in memory.
Assigning values to Variable:
We need not to declare explicitly variable in Python. When we assign any value to the variable that variable is declared automatically.
The assignment is done using the equal (=) operator.
Eg:
Output:
1. >>>
4. 20000.67
5. >>>
Multiple Assignment:
Multiple assignment can be done in Python at a time.
There are two ways to assign values in Python:
1. Assigning single value to multiple variables:
Eg:
1. x=y=z=50
1. >>>
2. 50
3. 50
4. 50
5. >>>
2.Assigning multiple values to multiple variables:
Eg:
1. a,b,c=5,10,15
2. print a
3. print b
4. print c
Output:
1. >>>
2. 5
3. 10
4. 15
5. >>>
The values will be assigned in the order in which variables appears.
Eg
Now check the individual value in Python Shell.
view plaincopy to clipboardprint?
1. >>> x = y = z = 1
2. | >>> print(x) |
3. | 1 |
4. >>> print(y)
5. 1
6. >>> print(z) |
7. 1 |
8. >>> |
Here is an assignment statement where the variables assign many values at the same time.
Example :
x, y, z = 1, 2, "abcd"
In the above example x, y and z simultaneously get the new values 1, 2 and "abcd".
1. >>> x,y,z = 1,2,"abcd"
2. >>> print(x)
3. 1
4. >>> print(y)
5. 2
You can reuse variable names by simply assigning a new value to them :
view plaincopy to clipboardprint?
1. >>> x = 100
2. >>> print(x)
3. 100
4. >>> x = "Python" |
5. >>> print(x) |
6. Python |
7. >>>
Swap variables
Python swap values in a single line and this applies to all objects in python. Syntax
var1, var2 = var2, var1
Example :
1. >>> x = 10
2. >>> y = 20
3. >>> print(x)
4. 10
5. >>> print(y)
6. 20
7. >>> x, y = y, x
8. >>> print(x)
9. 20
10.>>> print(y) |
11.10 |
12.>>> |
Local and global variables in Python
In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
1. var1 = "Python"
2. | def func1(): |
3. var1 = "PHP"
4. | print("In side func1() var1 = ",var1) |
5.
6. | def func2(): |
7. print("In side func2() var1 = ",var1)
8. | func1() |
9. | func2() |
Output :
In side func1() var1 = PHP
In side func2() var1 = Python
You can use a global variable in other functions by declaring it as global keyword :
Example :
1. def func1():
2. | global var1 |
3. var1 = "PHP"
4. | print("In side func1() var1 = ",var1) |
5.
6. | def func2(): |
7. print("In side func2() var1 = ",var1)
8. | func1() |
9. | func2() |
Output :
In side func1() var1 = PHP
In side func2() var1 = PHP
Basic Fundamentals:
This section contains the basic fundamentals of Python like :
i)Tokens and their types.
ii) Comments
a)Tokens:
o Tokens can be defined as a punctuator mark, reserved words and each individual word in a statement.
o Token is the smallest unit inside the given program.
There are following tokens in Python:
o Keywords.
o Identifiers. o Literals. o Operators.
Python Keywords
Keywords are special reserved words which convey a special meaning to the compiler/interpreter. Each keyword have a special meaning and a specific operation. List of Keywords used in Python are:
Identifiers
Identifiers are the names given to the fundamental building blocks in a program.
These can be variables ,class ,object ,functions , lists , dictionaries etc.
There are certain rules defined for naming i.e., Identifiers.
I. An identifier is a long sequence of characters and numbers.
special character except underscore ( _ ) can be used as an identifier.
III.Keyword should not be used as an identifier name.
IV.Python is case sensitive. So using case is significant.
V.First character of an identifier can be character, underscore ( _ ) but not digit.
Python Literals
Literals can be defined as a data that is given in a variable or constant.
Python support the following literals: I. String literals:
String literals can be formed by enclosing a text in the quotes. We can use both single as well as double quotes for a String.
Eg:
"Aman" , '12345'
Types of Strings:
There are two types of Strings supported in Python:
a).Single line String- Strings that are terminated within a single line are known as Single line Strings.
Eg:
1. >>> text1='hello'
b).Multi line String- A piece of text that is spread along multiple lines is known as Multiple line String.
There are two ways to create Multiline Strings:
1). Adding black slash at the end of each line.
Eg:
1. >>> text1='hello\
2. user'
3. >>> text1
4. 'hellouser'
5. >>>
2).Using triple quotation marks:Eg:
1. >>> str2='''''welcome
2. to
3. SSSIT'''
4. >>> print str2
5. welcome
6. to
7. SSSIT
8. >>>
II.Numeric literals:
Numeric Literals are immutable. Numeric literals can belong to following four different numerical types.
Int(signed Long(long integers) float(floating Complex(complex) integers) point)
Numbers( can be both Integers of unlimited size Real numbers with In the form of a+bj where positive and negative) followed by lowercase or both integer and the real part and b for with no fractional uppercase L eg: fractional part eg: imaginary part of complex
: 100 87032845L -26.2 eg: 3.14j
III. Boolean literals:
A Boolean literal can have any of the two values: True or False.
IV. Special literals.
Python contains one special literal i.e., None.
None is used to specify to that field that is not created. It is also used for end of lists in Python.
Eg:
1. >>> val1=10
2. >>> val2=None
3. >>> val1
4. 10
5. >>> val2
6. >>> print val2
7. None
8. >>>
V.Literal Collections.
Collections such as tuples, lists and Dictionary are used in Python.
List:
o List contain items of different data types. Lists are mutable i.e., modifiable.
o The values stored in List are separated by commas(,) and enclosed within a square brackets([]). We can store different type of data in a List.
o Value stored in a List can be retrieved using the slice operator([] and [:]).
o The plus sign (+) is the list concatenation and asterisk(*) is the repetition operator.
Eg:
1. >>> list=['aman',678,20.4,'saurav']
2. >>> list1=[456,'rahul']
3. >>> list
4. ['aman', 678, 20.4, 'saurav']
5. >>> list[1:3]
6. [678, 20.4]
7. >>> list+list1
8. ['aman', 678, 20.4, 'saurav', 456, 'rahul']
9. >>> list1*2
10. [456, 'rahul', 456, 'rahul']
11. >>>
Python Operators
Operators are particular symbols which operate on some values and produce an output.
The values are known as Operands.
Eg:
1. 4 + 5 = 9
Here 4 and 5 are Operands and (+) , (=) signs are the operators. They produce the output 9.
Python supports the following operators:
1. Arithmetic Operators.
2. Relational Operators.
3. Assignment Operators.
4. Logical Operators.
5. Membership Operators.
6. Identity Operators.
7. Bitwise Operators.
1. >>> 10+20
2. 30
3. >>> 20-10
4. 10
5. >>> 10*2 6. 20
7. >>> 10/2
8. 5
9. >>> 10%3
10. 1
11. >>> 2**3
12. 8
13. >>> 10//3
14. 3
15. >>>
1. >>> 10
3. >>> 10>20
4. False
5. >>> 10
7. >>> 20>=15
8. True
9. >>> 5==6
10. False
11. >>> 5!=6
12. True
13. >>> 102
14. True
1. >>> c=10
2. >>> c
3. 10
4. >>> c+=5
5. >>> c
6. 15
7. >>> c-=5
8. >>> c
9. 10
10. >>> c*=2
11. >>> c
12. 20
13. >>> c/=2
14. >>> c
15. 10
16. >>> c%=3
17. >>> c
18. 1
19. >>> c=5
20. >>> c**=2
21. >>> c
22. 25
23. >>> c//=2
24. >>> c
25. 12
26. >>>
1. a=5>4 and 3>2
2. print a
3. b=5>4 or 3
4. print b
5. c=not(5>4)
6. print c
Output:
1. >>>
2. True
3. True
4. False
5. >>>
1. a=10
2. b=20
3. list=[10,20,30,40,50];
4. if (a in list):
5. print "a is in given list"
6. else:
7. print "a is not in given list"
8. if(b notin list):
9. print "b is not given in list"
10. else:
11. print "b is given in list" Output:
1. >>>
2. a isin given list
3. b is given in list
4. >>>
1. a=20 2. b=20
3. if( a is b):
4. print ?a,b have same identity?
5. else:
6. print ?a, b are different?
7. b=10
8. if( a isnot b):
9. print ?a,b have different identity?
10. else:
11. print ?a,b have same identity? Output:
1. >>>
2. a,b have same identity
3. a,b have different identity
4. >>>
Python Comments
Python supports two types of comments:
1) Single lined comment:
In case user wants to specify a single line comment, then comment must start with ?#?
Eg:
1. # This is single line comment. 2) Multi lined Comment:
Multi lined comment can be given inside triple quotes.
eg:
1. ''''' This
2. Is
3. Multipline comment''' eg:
1. #single line comment
2. print "Hello Python"
3. '''''This is
4. multiline comment'''
Python If Statements
The if statement in python is same as c language which is used test a condition. If condition is true, statement of if block is executed otherwise it is skipped.
Syntax of python if statement:
1. if(condition):
2. statements
Example of if statement in python
1. a=10
2. if a==10:
3. print "Hello User" Output:
Python If Else Statements
Syntax:
1. if(condition): False
2. statements
3. else: True
4. statements
Example-
1. year=2000
2. if year%4==0:
Nested If Else Statement:
When we need to check for multiple conditions to be true then we use elif Statement.
This statement is like executing a if statement inside a else statement.
Syntax:
1. If statement:
2. Body
3. elif statement:
4. Body
5. else:
6. Body
Example:
1. a=10
2. if a>=20:
3. print "Condition is True"
4. else:
5. if a>=15:
6. print "Checking second value"
7. else:
8. print "All Conditions are false"
Output:
All Conditions are false.
For Loop
for Loop is used to iterate a variable over a sequence(i.e., list or string) in the order that they appear.
Syntax:
1. for in : Output:
1. 1
2.
3. 7
4.
5. 9
Explanation:
o Firstly, the first value will be assigned in the variable.
o Secondly all the statements in the body of the loop are executed with the same value.
o Thirdly, once step second is completed then variable is assigned the next value in the sequence and step second is repeated.
o Finally, it continues till all the values in the sequence are assigned in the variable and processed.
Program to display table of Number:
1. num=2
2. for a in range (1,6):
3. print num * a Output:
1. 2
2.
3. 4
4.
5. 6
6.
7. 8
8.
9. 10
Program to find sum of Natural numbers from 1 to 10.
1. sum=0
2. for n in range(1,11):
3. sum+=n
4. print sum
Output:
1. 55
Nested Loops
Loops defined within another Loop is called Nested Loop.
When an outer loop contains an inner loop in its body it is called Nested Looping.
Syntax:
1. for :
2. for :
3. Body eg:
1. for i in range(1,6):
2. for j in range (1,i+1):
3. print i,
4. print
Output:
1. >>>
2. 1
3. 2 2
4. 3 3 3
5. 4 4 4 4
6. 5 5 5 5 5
7. >>>
Explanation:
For each value of Outer loop the whole inner loop is executed.
For each value of inner loop the Body is executed each time.
Program to print Pyramid:
1. for i in range (1,6):
2. for j in range (5,i-1,-1):
3. print "*",
4. print
Output:
1. >>>
2. * * * * *
3. * * * *
4. * * *
5. * *
6. *
While Loop
while Loop is used to execute number of statements or body till the condition passed in while is true. Once the condition is false, the control will come out of the loop.
Syntax:
1. while :
2. Body
Here, body will execute multiple times till the expression passed is true. The Body may be a single statement or multiple statement.
Eg:
1. a=10
2. while a>0:
3. print "Value of a is",a
4. a=a-2
print "Loop is Completed" Output:
1. >>>
2. Value of a is 10
3. Value of a is 8 4. Value of a is 6 5. Value of a is 4
6. Value of a is 2
7. Loop is Completed
8. >>>
Explanation:
o Firstly, the value in the variable is initialized.
o Secondly, the condition/expression in the while is evaluated. Consequently if condition is true, the control enters in the body and executes all the statements . If the condition/expression passed results in false then the control exists the body and straight away control goes to next instruction after body of while.
o Thirdly, in case condition was true having completed all the statements, the variable is incremented or decremented. Having changed the value of variable step second is followed. This process continues till the expression/condition becomes false.
o Finally Rest of code after body is executed.
Program to add digits of a number:
1. n=153
2. sum=0
3. while n>0:
4. r=n%10
5. sum+=r
6. n=n/10
7. print sum
Output:
1. >>>
2. 9
3. >>>
Python Break
break statement is a jump statement that is used to pass the control to the end of the loop.
When break statement is applied the control points to the line following the body of the loop , hence applying break statement makes the loop to terminate and controls goes to next line pointing after loop body.
eg:
1. for i in [1,2,3,4,5]:
2. if i==4:
3. print "Element found"
4. break
5. print i, Output:
1. >>>
2. 1 2 3 Element found
3. >>>
Continue Statement
continue Statement is a jump statement that is used to skip the present iteration and forces next iteration of loop to take place. It can be used in while as well as for loop statements.
eg:
1. a=0
2. while a
3. a=a+1 4. if a%2==0:
5. continue
6. print a
7. print "End of Loop" Output:
1. >>>
2. 1 3. 3
4. 5
5. End of Loop
6. >>>
Flow chart of continue:-
When you do not want any code to execute, pass Statement is used. It is same as the name refers to. It just makes the control to pass by without executing any code. If we want to bypass any code pass statement can be used.
Syntax:
1. pass eg:
1. for i in [1,2,3,4,5]:
2. if i==3:
3. pass
4. print "Pass when value is",i
5. print i, Output:
1. >>>
2. 1 2 Pass when value is 3
3. 3 4 5
4. >>>
PYTHON STRINGS
Strings are the simplest and easy to use in Python.
String pythons are immutable.
We can simply create Python String by enclosing a text in single as well as double quotes. Python treat both single and double quotes statements same.
Accessing Strings:
o In Python, Strings are stored as individual characters in a contiguous memory location.
o The benefit of using String is that it can be accessed from both the directions in forward and backward.
o Both forward as well as backward indexing are provided using Strings in Python.
o Forward indexing starts with 0,1,2,3, .
o Backward indexing starts with -1,-2,-3,-4, .
eg:
1. str[0]='P'=str[-6] , str[1]='Y' = str[-5] , str[2] = 'T' = str[-4] , str[3] = 'H' = str[-3]
2. str[4] = 'O' = str[-2] , str[5] = 'N' = str[-1].
Simple program to retrieve String in reverse as well as normal form.
1. name="Rajat"
2. length=len(name)
3. i=0
4. for n in range(-1,(-length-1),-1):
5. print name[i],"\t",name[n]
6. i+=1
Output:
There are basically 3 types of Operators supported by String:
1. Basic Operators.
2. Membership Operators.
3. Relational Operators.
Basic Operators:
There are two types of basic operators in String. They are "+" and "*".
String Concatenation Operator :(+)
The concatenation operator (+) concatenate two Strings and forms a new String. eg:
'ratanjaiswal'
>>>
Eg:
Traceback (most recent call last):
File "", line 1, in
'abc' + 3
TypeError: cannot concatenate 'str' and 'int' objects
>>>
Replication Operator: (*)
Replication operator uses two parameter for operation. One is the integer value and the other one is the String.
The Replication operator is used to repeat a string number of times. The string will be repeated the number of times which is given by the integer value.
Eg:
1. >>> 5*"Vimal"
Output:
'VimalVimalVimalVimalVimal'
Membership Operators
Membership Operators are already discussed in the Operators section. Let see with context of String.
There are two types of Membership operators:
1)in:"in" operator return true if a character or the entire substring is present in the specified string, otherwise false.
2)not in:"not in" operator return true if a character or entire substring does not exist in the specified string, otherwise false.
Eg:
1. >>> str1="javatpoint"
2. >>> str2='sssit'
3. >>> str3="seomount"
4. >>> str4='java' 5. >>> st5="it"
6. >>> str6="seo"
7. >>> str4 in str1
8. True
9. >>> str5 in str2
10. >>> st5 in str2
11. True
12. >>> str6 in str3
13. True
14. >>> str4 notin str1 15. False
16. >>> str1 notin str4
17. True
Relational Operators:
All the comparison operators i.e., (=,==,!=,) are also applicable to strings. The Strings are compared based on the ASCII value or Unicode(i.e., dictionary Order).
Eg:
1. >>> "RAJAT"=="RAJAT"
2. True
3. >>> "afsha">='Afsha'
4. True
5. >>> "Z""z"
6. True
Explanation:
The ASCII value of a is 97, b is 98, c is 99 and so on. The ASCII value of A is 65,B is 66,C is 67 and so on. The comparison between strings are done on the basis on ASCII value.
Slice Notation:
String slice can be defined as substring which is the part of string. Therefore further substring can be obtained from a string.
There can be many forms to slice a string. As string can be accessed or indexed from both the direction and hence string can also be sliced from both the direction that is left and right.
Syntax:
1. [startIndex:endIndex],
2. [:endIndex],
3. [startIndex:] Example:
1. >>> str="Nikhil"
2. >>> str[0:6] 3. 'Nikhil'
4. >>> str[0:3] 5. 'Nik'
6. >>> str[2:5]
7. 'khi'
8. >>> str[:6] 9. 'Nikhil'
10. >>> str[3:]
11. 'hil'
String slice can also be used with Concatenation operator to get whole string.
Eg:
1. >>> str="Mahesh"
2. >>> str[:6]+str[6:]
3. 'Mahesh'
//here 6 is the length of the string.
String Functions and Methods:
There are many predefined or built in functions in String. They are as follows:
1) capitalize()
1. >>> 'abc'.capitalize() Output:
1. msg = "welcome to sssit";
2. substr1 = "o";
3. print msg.count(substr1, 4, 16)
4. substr2 = "t";
5. print msg.count(substr2) Output:
1. string1="Welcome to SSSIT";
2. substring1="SSSIT";
3. substring2="to";
4. substring3="of";
5. print string1.endswith(substring1);
6. print string1.endswith(substring2,2,16);
7. print string1.endswith(substring3,2,19);
8. print string1.endswith(substring3);
2. substr1="come";
3. substr2="to";
4. print (substr1);
5. print (substr2);
6. print (substr1,3,10);
7. print (substr2,19); Output:
>>>
3
8
3
-1
>>>
5) index(string)
1. str="Welcome to world of SSSIT";
2. substr1="come";
3. substr2="of";
4. print str.index(substr1);
5. print str.index(substr2);
6. print str.index(substr1,3,10); 7. print str.index(substr2,19);
2. print str.isalnum();
3. str1="Python47";
4. print str1.isalnum(); Output:
1. string1="HelloPython"; # Even space is not allowed
2. print string1.isalpha();
3. string2="This is Python2.7.4"
4. print string2.isalpha(); Output:
8) isdigit()
1. string1="HelloPython";
2. print string1.isdigit();
3. string2="98564738"
4. print string2.isdigit(); Output:
9) islower()
1. string1="Hello Python";
2. print string1.islower();
3. string2="welcome to "
4. print string2.islower(); Output:
1. string1="Hello Python";
2. print string1.isupper();
3. string2="WELCOME TO"
4. print string2.isupper(); Output:
>>>
False
1. string1=" ";
2. print string1.isspace();
3. string2="WELCOME TO WORLD OF PYT"
4. print string2.isspace(); Output:
1. string1=" ";
2. print len(string1);
3. string2="WELCOME TO SSSIT"
4. print len(string2); Output:
1. string1="Hello Python";
2. print string1.lower();
3. string2="WELCOME TO SSSIT"
4. print string2.lower(); Output:
1. string1="Hello Python";
2. print string1.upper();
3. string2="welcome to SSSIT"
4. print string2.upper();
Output:
1. string1="Hello Python";
2. print string1.startswith('Hello');
3. string2="welcome to SSSIT"
4. print string2.startswith('come',3,7); Output:
1. string1="Hello Python";
2. print string1.swapcase();
3. string2="welcome to SSSIT"
4. print string2.swapcase(); Output:
1. string1=" Hello Python";
2. print string1.lstrip();
3. string2="@@@@@@@@welcome to SSSIT"
4. print string2.lstrip('@'); Output:
1. string1=" Hello Python ";
2. print string1.rstrip();
3. string2="@welcome to SSSIT!!!"
4. print string2.rstrip('!'); Output: