VGC3CS1– Python
Programming
MODULE 1
Contents
Introduction To Python
Features
Idle
Python Interpreter
Writing And Executing Python Scripts
Comments, Identifiers, Keywords, Variables, Data Type
Operators, Operator Precedence And Associativity
Statements, Expressions
User Inputs,
Type Function, Eval Function, Print Function.
Introduction
Python is a simple, general purpose, high level,
and object-oriented programming language
Python is an interpreted scripting language
also.
[Link]
History of Python
Guido Van Rossum is known as the founder of Python programming.
History of Python
Python laid its foundation in the late 1980s.
The implementation of Python was started in the December 1989 by Guido Van Rossum at
CWI in Netherland.
In February 1991, van Rossum published the code (labeled version 0.9.0) to [Link].
In 1994, Python 1.0 was released with new features like: lambda, map, filter, and reduce.
Python 2.0 added new features like: list comprehensions, garbage collection system.
On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to rectify
fundamental flaw of the language.
ABC programming language is said to be the predecessor of Python language which was
capable of Exception Handling and interfacing with Amoeba Operating System.
Python Versions
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.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
Python 3.8 14 Oct 2019
How to install Python
[Link]
Features of Python
1. Easy to Learn and Use
2. Expressive Language
3. Interpreted Language
4. Cross-platform Language
5. Free and Open Source
6. Object-Oriented Language
7. Extensible
8. Extensible
9. GUI Programming Support
10. Integrated
Features of Python
Easy to Learn and Use
Python is easy to learn and use. It is developer-friendly and high level
programming language.
Expressive Language
Python language is more expressive means that it is more understandable
and readable.
Interpreted Language
Python is an interpreted language i.e. interpreter executes the code line by
line at a time. This makes debugging easy and thus suitable for beginners.
Features of Python
Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, Unix
and Macintosh etc. So, we can say that Python is a portable language.
Free and Open Source
Python language is freely available at official web address. The source-code
is also available. Therefore it is open source.
Object-Oriented Language
Python supports object oriented language and concepts of classes and
objects come into existence.
Features of Python
Extensible
It implies that other languages such as C/C++ can be used to compile the code
and thus it can be used further in our python code.
Large Standard Library
Python has a large and broad library and provides rich set of module and
functions for rapid application development.
GUI Programming Support
Graphical user interfaces can be developed using Python.
Integrated
It can be easily integrated with languages like C, C++, JAVA etc.
IDLE
IDLE is an integrated development environment for Python, which has
been bundled with the default implementation of the language
4). How Python runs?
When the Python software is installed on your machine,
minimally, it has:
an interpreter
a support library.
The interpreter
Interpreter is nothing but a software which can run your
Python scripts.
Interestingly, it can be implemented in any programming
language!
CPython is the default interpreter for Python which is
written in C programming language.
Jython is another popular implementation of python
interpreter written using Java programming language.
Programmer’s view of interpreter
If you have been coding in Python for sometime, you must
have heard about the interpreter at least a few times.
From a programmer’s perspective, an interpreter is simply a
software which executes the source code line by line.
Python’s view of interpreter
Now, let us scan through the python interpreter and try to
understand how it works.
Have a look at the diagram shown below:
Compiler compiles your source code (the statements in
your file) into a format known as byte code.
As soon as source code gets converted to byte code, it is fed
into PVM (Python Virtual Machine).
The PVM is the runtime engine of Python;
PyPy is an implementation of Python which does not use an
interpreter! It is implemented using something called
just-in-time compiler!
Interestingly, it often runs faster than the standard
implementation of Python, CPython.
Whenever a Python script is executed, the byte code is
generated in memory and simply discarded when program exits.
But, if a Python module is imported, a .pyc file for the module
is generated which contains its Byte code.
Thus, when the module is imported next time, the byte code
from .pyc file is used, hence skipping the compilation step!
Applications
5). Python Application
Python is known for its general purpose nature that makes it
applicable in almost each domain of software development.
Python as a whole can be used in any sphere of development.
Here, we are specifying applications areas where python can
be applied.
1) Web Applications
We can use Python to develop web applications.
It provides libraries to handle internet protocols such as
HTML and XML, JSON, Email processing etc.
It also provides Frameworks such as Django, Pyramid, Flask
etc to design and develop web based applications. Some
important developments are: PythonWikiEngines, Pocoo,
PythonBlogSoftware etc.
2) Desktop GUI Applications
Python provides Tk GUI library to develop user interface in
python based application.
Some other useful toolkits wxWidgets, Kivy, pyqt that are
useable on several platforms.
The Kivy is popular for writing multitouch applications.
3) Software Development
Python is helpful for software development process.
It works as a support language and can be used for build
control and management, testing etc.
4) Scientific and Numeric
Python is popular and widely used in scientific and numeric
computing.
Some useful library and package are SciPy, Pandas, IPython
etc.
SciPy is group of packages of engineering, science and
mathematics.
5) Business Applications
Python is used to build Business applications like ERP and e-
commerce systems.
Tryton is a high level application platform.
6) Console Based Application
We can use Python to develop console based applications.
For example: IPython.
7) Audio or Video based Applications
Python is awesome to perform multiple tasks and can be used
to develop multimedia applications.
Some of real applications are: TimPlayer, cplay etc.
8) 3D CAD Applications
To create CAD application Fandango is a real application
which provides full features of CAD.
9) Enterprise Applications
Python can be used to create applications which can be used
within an Enterprise or an Organization.
Some real time applications are: OpenErp, Tryton, Picalo
etc.
10) Applications for Images
Using Python several application can be developed for image.
Applications developed are: VPython, Gogh, imgSeek etc.
Writing and executing
Python Scripts
Python provides us the two ways to
run a program:
Using Interactive interpreter prompt
Using a script file
Interactive interpreter prompt
Python provides us the feature to execute the python statement one by
one at the interactive prompt.
It is preferable in the case where we are concerned about the output of
each line of our python program.
Using a script file
Interpreter prompt is good to run the individual statements of the code.
However, we can not write the code every-time on the terminal.
We need to write our code into a file which can be executed later.
For this purpose, open an editor like notepad, create a file named [Link]
(python used .py extension) and write the following code in it.
To run this file named as [Link], we need to run the following command on
the terminal.
Python Comments
Comments in Python can be used to explain any program code.
In python, any statement written along with # symbol is known as a
comment.
The interpreter does not interpret the comment.
Comment is not a part of the program, but it enhances the interactivity
of the program and makes the program readable.
Python supports two types of
comments:
1) Single Line Comment:
In case user wants to specify a single line comment, then comment
must start with #
Eg:
# This is single line comment.
print "Hello Python"
Python supports two types of
comments:
2) Multi Line Comment:
Multi lined comment can be given inside triple quotes.
eg:
''''' This
Is
Multiple line comment'''
Identifiers, Keywords,
Variables, Data Type,
Operators
Python Variables
Variable is a name which is used to refer memory location. Variable also known as
identifier and used to hold value.
In Python, we don't need to specify the type of variable because Python is a type
infer language and smart enough to get variable type.
Variable names can be a group of both letters and digits, but they have to begin
with a letter or an underscore.
It is recommended to use lowercase letters for variable name. Rahul and rahul
both are two different variables.
Identifier Naming
An Identifier is used to identify the literals used in the program. The rules to name an
identifier are given below.
The first character of the variable must be an alphabet or underscore ( _ ).
All the characters except the first character may be an alphabet of lower-case(a-z),
upper-case (A-Z), underscore or digit (0-9).
Identifier name must not contain any white-space, or special character (!, @, #, %, ^,
&, *).
Identifier name must not be similar to any keyword defined in the language.
Identifier names are case sensitive for example myname, and MyName is not the same.
Examples of valid identifiers : a123, _n, n_9, etc.
Examples of invalid identifiers: 1a, n%4, n 9, etc.
Declaring Variable and Assigning
Values
a=10
name= ‘anu’
Variables salary=25769.7 Values
print a
print name
print salary
Output:
>>>
10
anu
25769.7
>>>
Multiple Assignment
Python allows us to assign a value to multiple variables in a single
statement which is also known as multiple assignment.
We can apply multiple assignments in two ways either by assigning a
single value to multiple variables or assigning multiple values to
multiple variables.
Lets see given examples.
1. Assigning single value to
multiple variables
Egs Output
>>>
x=y=z=5
50
0
50
print x
50
print y
>>>
print z
[Link] multiple values to
multiple variables:
Egs Output
a,b,c=5,10,1 >>>
5 5
print a 10
print b 15
print c >>>
Tokens
Tokens can be defined as a punctuator mark,
reserved words and each individual word in
a statement.
Token is the smallest unit inside the given program. Tokens
Python Keywords
Python Keywords are special reserved words which convey a special
meaning to the compiler/interpreter.
Each keyword have a special meaning and a specific operation. These
keywords can't be used as variable.
Following is the List of Python Keywords.
Python Keywords
True False None and as
asset def class continue break
else finally elif del except
global for if from import
raise try or return pass
nonlocal in not is lambda
Literals
Python Literals
String literals Numeric Literals Special Literals Boolean Literals Literal Collections
Single line int None Tuple
Multiline long List
float Dictionary
complex
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:
>>> 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:
>>> text1='hello\
user'
>>> text1
'hellouser'
>>>
2).Using triple quotation marks:-
Eg:
>>> str2='''''welcome
to
SSSIT'''
>>> print str2
welcome
to
SSSIT
>>>
Numeric literals
Numeric Literals are immutable.
Numeric literals can belong to following four different numerical types.
Int(signed integers) Long(long integers) float(floating point) Complex(complex)
Numbers( can be Integers of Real numbers with In the form of
both positive and unlimited size both integer and a+bj where a
negative) with no followed by fractional part eg: forms the real part
fractional [Link]: lowercase or -26.2 and b forms the
100 uppercase L eg: imaginary part of
87032845L complex number.
eg: 3.14j
Boolean literals
A Boolean literal can have any of the two values: True or False.
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.
Egs.
>>> val1=10
>>> val2=None
>>> val1
10
>>> val2
>>> print val2
None
>>>
Literal Collections
Collections such as tuples, lists and Dictionary are used in Python.
List
List contain items of different data types. Lists are mutable i.e.,
modifiable.
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.
Value stored in a List can be retrieved using the slice operator([] and
[:]).
The plus sign (+) is the list concatenation and asterisk(*) is the
repetition operator.
Egs
>>> list=['aman',678,20.4,'saurav']
>>> list1=[456,'rahul']
>>> list
['aman', 678, 20.4, 'saurav']
>>> list[1:3]
[678, 20.4]
>>> list+list1
['aman', 678, 20.4, 'saurav', 456, 'rahul']
>>> list1*2
[456, 'rahul', 456, 'rahul']
>>>
Python Tuple
Python Tuple is used to store the sequence of immutable python
objects. Tuple is similar to lists since the value of the items stored in the
list can be changed whereas the tuple is immutable and the value of
the items stored in the tuple can not be changed.
A tuple can be written as the collection of comma-separated values
enclosed with the small brackets. A tuple can be defined as follows.
tuple1 = (10, 20, 30, 40, 50, 60)
print(tuple1)
Python Dictionary
Dictionary is used to implement the key-value pair in python.
The dictionary is the data type in python which can simulate the real-
life data arrangement where some specific value exists for some
particular key.
In other words, we can say that a dictionary is the collection of key-
value pairs where the value can be any python object whereas the keys
are the immutable python object, i.e., Numbers, string or tuple.
Creating the dictionary
The dictionary can be created by using multiple key-value pairs
enclosed with the small brackets () and separated by the colon (:). The
collections of the key-value pairs are enclosed within the curly braces
{}.
The syntax to define the dictionary is given below.
Dict = {"Name": "Ayush","Age": 22}
Print (Dict)
Data types, Operators,
Operator Precedence &
Associativity
Python Data Types
Variables can hold values of different data types.
Python is a dynamically typed language hence we need not define the
type of the variable while declaring it. The interpreter implicitly binds
the value with its type.
Python enables us to check the type of the variable used in the
program. Python provides us the type() function which returns the type
of the variable passed.
Python Data Types
Egs
A=10 Output
b="Hi Python"
c=10.5
print(type(a));
<class 'int'>
<class 'str'>
print(type(b));
<class 'float'>
print(type(c));
Standard data types
A variable can hold different types of values. For example, a person's
name must be stored as a string whereas its id must be stored as an
integer.
Python provides various standard data types that define the storage
method on each of them. The data types defined in Python are given
below.
Standard data types
1. Numbers
2. String
3. List
4. Tuple
5. Dictionary
Numbers
Python supports 4 types of numeric data.
1. int (signed integers like 10, 2, 29, etc.)
2. long (long integers used for a higher range of values like 908090800L, -
0x1929292L, etc.)
3. float (float is used to store floating point numbers like 1.9, 9.902, 15.2, etc.)
4. complex (complex numbers like 2.14j, 2.0 + 2.3j, etc.)
String
The string can be defined as the sequence of characters represented in
the quotation marks. In python, we can use single, double, or triple
quotes to define a string.
In the case of string handling, the operator + is used to concatenate
two strings as the operation "hello"+" python" returns "hello python".
The operator * is known as repetition operator as the operation "Python
" *2 returns "Python Python ".
The following example illustrates the string handling in python.
String
str1 = 'hello vimala' #string str1
Egs str2 = ' how are you' #string str2
print (str1[0:2]) #printing first two character using slice operat
or
print (str1[4]) #printing 4th character of the string
print (str1*2) #printing the string twice
print (str1 + str2) #printing the concatenation of str1 and str2
Output
he
o
hello vimalahello vimala
hello vimalahow are you
List
Lists are similar to arrays in C.
However; the list can contain data of different types.
The items stored in the list are separated with a comma (,) and enclosed
within square brackets [].
We can use slice [:] operators to access the data of the list. The
concatenation operator (+) and repetition operator (*) works with the list in
the same way as they were working with the strings.
List
Egs l=[1, "hi", "python", 2]
print(l[3:]);
print(l[0:2]);
print(l);
print(l + l);
print(l * 3);
Output [2]
[1, 'hi']
[1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2, 1, 'hi', 'python', 2]
Tuple
A tuple is similar to the list in many ways.
Like lists, tuples also contain the collection of the items of different data
types. The items of the tuple are separated with a comma (,) and
enclosed in parentheses ().
A tuple is a read-only data structure as we can't modify the size nd
value of the items of a tuple.
t=("hi", "python", 2)
Tuple print(t[1:]);
print(t[0:1]);
print(t);
Egs
print(t + t);
print(t * 3);
print(type(t))
t[2]="hi";
('python', 2)
('hi',)
('hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2)
Output ('hi', 'python', 2, 'hi', 'python', 2, 'hi', 'python', 2)
<class 'tuple'>
Traceback (most recent call last):
File
"C:/Users/Home/AppData/Local/Programs/Python/Python37/Demo/[Link]",
line 8, in <module>
t[2]="hi";
TypeError: 'tuple' object does not support item assignment
Dictionary
Dictionary is an ordered set of a key-value pair of items.
Each key stores a specific value. Key can hold any primitive data type
whereas value is an arbitrary Python object.
The items in the dictionary are separated with the comma and enclosed
in the curly braces {}.
Dictionary
Egs
d={1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'};
print("1st name is "+d[1]);
print("2nd name is "+ d[4]);
print(d);
print([Link]());
print([Link]());
Output 1st name is Jimmy
2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
dict_keys([1, 2, 3, 4])
dict_values(['Jimmy', 'Alex', 'john', 'mike'])
Python Operators
Operators are the constructs which can manipulate the value of
operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands
and + is called operator.
Types of Operator
Python language supports the following types of operators.
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
Python Arithmetic Operators
Assume variable a holds 10 and variable b holds 20, then −
Operator Description Example
+ Addition Adds values on either side of the operator. a + b = 30
- Subtraction Subtracts right hand operand from left hand operand. a – b = -10
* Multiplies values on either side of the operator a * b = 200
Multiplication
/ Division Divides left hand operand by right hand operand b/a=2
% Modulus Divides left hand operand by right hand operand and returns b%a=0
remainder
** Exponent Performs exponential (power) calculation on operators a**b =10 to the power 20
// Floor Division - The division of operands where the result is the 9//2 = 4 and 9.0//2.0 = 4.0,
quotient in which the digits after the decimal point are removed. -11//3 = -4, -11.0//3 = -4.0
But if one of the operands is negative, the result is floored, i.e.,
rounded away from zero (towards negative infinity) −
Python Comparison Operators
These operators compare the values on either sides of them and decide the
relation among them. They are also called Relational operators.
Assume variable a holds 10 and variable b holds 20, then −
Operato Description Example
r
== If the values of two operands are equal, then the condition becomes true. (a == b) is not true.
!= If values of two operands are not equal, then condition becomes true. (a != b) is true.
<> If values of two operands are not equal, then condition becomes true. (a <> b) is true. This is similar to !=
operator.
> If the value of left operand is greater than the value of right operand, then (a > b) is not true.
condition becomes true.
< If the value of left operand is less than the value of right operand, then (a < b) is true.
condition becomes true.
>= If the value of left operand is greater than or equal to the value of right (a >= b) is not true.
operand, then condition becomes true.
<= If the value of left operand is less than or equal to the value of right operand, (a <= b) is true.
then condition becomes true.
Python Assignment Operators
Assume variable a holds 10 and variable b holds 20, then −
Operator Description Example
= Assigns values from right side operands to left side operand c = a + b assigns value of a + b
into c
+= Add AND It adds right operand to the left operand and assign the
c += a is equivalent to c = c + a
result to left operand
-= Subtract AND It subtracts right operand from the left operand and assign
c -= a is equivalent to c = c - a
the result to left operand
*= Multiply AND It multiplies right operand with the left operand and assign
c *= a is equivalent to c = c * a
the result to left operand
/= Divide AND It divides left operand with the right operand and assign the
c /= a is equivalent to c = c / a
result to left operand
%= Modulus AND It takes modulus using two operands and assign the result to c %= a is equivalent to c = c %
left operand a
**= Exponent AND Performs exponential (power) calculation on operators and c **= a is equivalent to c = c **
assign value to the left operand a
//= Floor Division It performs floor division on operators and assign value to
c //= a is equivalent to c = c // a
the left operand
Python Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation.
Assume if a = 60; and b = 13; Now in the binary format their values will be 0011 1100
and 0000 1101 respectively
a = 0011 1100
b = 0000 1101
------------------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
Python Bitwise Operators
Operator Description Example
& Binary AND Operator copies a bit to the result if it exists in both
(a & b) (means 0000 1100)
operands
| Binary OR It copies a bit if it exists in either operand.
(a | b) = 61 (means 0011 1101)
^ Binary XOR It copies the bit if it is set in one operand but not both.
(a ^ b) = 49 (means 0011 0001)
~ Binary Ones Complement (~a ) = -61 (means 1100 0011 in 2's
It is unary and has the effect of 'flipping' bits. complement form due to a signed binary
number.
<< Binary Left Shift The left operands value is moved left by the number of
bits specified by the right operand. a << 2 = 240 (means 1111 0000)
>> Binary Right Shift The left operands value is moved right by the number of
bits specified by the right operand. a >> 2 = 15 (means 0000 1111)
Python Logical Operators
There are following logical operators supported by Python language.
Assume variable a holds 10 and variable b holds 20 then
Operator Description Example
and Logical AND If both the operands are true then (a and b) is
condition becomes true. true.
or Logical OR If any of the two operands are non-zero (a or b) is
then condition becomes true. true.
not Logical NOT Used to reverse the logical state of its Not(a and b)
operand. is false.
Python Membership Operators
Membership operators are used to test if a sequence is presented in an
object.
Python’s membership operators test for membership in a sequence,
such as strings, lists, or tuples.
Operator Description Example
in Returns True if a sequence with the x in y
specified value is present in the object
not in Returns True if a sequence with the x not in y
specified value is not present in the
object
Python Membership Operators
Example 1
x = ["apple", "banana"]
print("banana" in x)
# returns True because a sequence with the value "banana" is in the list
Example 2
x = ["apple", "banana"]
print("pineapple" not in x)
# returns True because a sequence with the value "pineapple" is not in the list
Python Identity Operators
Identity operators compare the memory locations of two objects.
Identity operators are used to compare the objects, not if they are equal, but if
they are actually the same object, with the same memory location
Operator Description Example
is Returns True if both variables are the same object x is y
is not Returns True if both variables are not the same x is not y
object
Python Identity Operators - Example
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is z)
# returns True because z is the same object as x
print(x is y)
# returns False because x is not the same object as y, even if they have the same content
print(x == y)
# to demonstrate the difference between "is" and "==": this comparison returns True because x is equal to y
Operator Precedence
The precedence of the operators is important to find out since
it enables us to know which operator should be evaluated first.
The following table lists all operators from highest precedence
to lowest.
Operator Description
** The exponent operator is given priority over all
the others used in the expression.
~+- The negation, unary plus and minus.
* / % // The multiplication, divide, modules, reminder,
and floor division.
+- Binary plus and minus
>> << Left shift and right shift
& Binary and.
^| Binary xor and or
<= < > >= Comparison operators (less then, less then
equal to, greater then, greater then equal
to).
<> == != Equality operators.
= %= /= //= -= += Assignment operators
*= **=
is is not Identity operators
in not in Membership operators
not or and Logical operators