PDF Advanced Programming Module
PDF Advanced Programming Module
MODULE-1
TEACHING SCHEME: 3-1-0 (L-T-P) CREDIT:3
1. Introduction:
What is Python
Python is easy to learn yet powerful and versatile scripting language, which
makes it attractive for Application Development.
Python's syntax and dynamic typing with its interpreted nature make it an
ideal language for scripting and rapid application development.
Python supports multiple programming pattern, including object-oriented,
imperative, and functional or procedural programming styles.
Python is not intended to work in a particular area, such as web
programming. That is why it is known as multipurpose programming
language because it can be used with web, enterprise, 3D CAD, etc.
We don't need to use data types to declare variable because it is dynamically
typed so we can write a=10 to assign an integer value in an integer variable.
Python makes the development and debugging fast because there is no
compilation step included in Python development, and edit-test-debug cycle
is very fast.
Python History
Python was invented by Guido Van Rossum in 1991 at CWI in Netherland. The idea
of Python programming language has taken from the ABC programming language
or we can say that ABC is a predecessor of Python language.
There is also a fact behind the choosing name Python. Guido van Rossum was a fan
of the popular BBC comedy show of that time, "Monty Python's Flying Circus". So
he decided to pick the name Python for his newly created programming language.
Data Science
Date Mining
Desktop Applications
Console-based Applications
Mobile Applications
Software Development
Artificial Intelligence
Web Applications
Enterprise Applications
3D CAD Applications
Machine Learning
Computer Vision or Image Processing Applications.
Speech Recognitions
What can be done with Python?
In order to become Python developer, the first step is to learn how to install or
update Python on a local machine or computer. In this tutorial, we will discuss the
installation of Python on various operating systems.
Installation on Windows
Double-click the executable file, which is downloaded; the following window will
open. Select Customize installation and proceed. Click on the Add Path check box,
it will set the Python path automatically.
We can also click on the customize installation to choose desired location and
features. Other important thing is install launcher for the all user must be checked.
In this Section, we will discuss the basic syntax of Python, we will run a simple
program to print Hello World on the console.
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.
To open the interactive mode, open the terminal (or command prompt) and type
python (python3 in case if you have Python2 and Python3 both installed on your
system).
It will open the following prompt where we can execute the Python statement and
check their impact on the console.
The interpreter prompt is best to run the single-line statements of the code.
However, we cannot write the code every-time on the terminal. It is not suitable to
write multiple lines of code.
Using the script mode, we can write multiple lines code into a file which can be
executed later. For this purpose, we need to open an editor like notepad, create a
file named and save it with .py extension, which stands for "Python". Now, we will
implement the above example using the script mode.
print ("hello world"); #here, we have used print() function to print the message
on the console.
To run this file named as first.py, we need to run the following command on the
terminal.
Step - 1: Open the Python interactive shell, and click "File" then choose "New", it
will open a new blank script in which we can write our code.
Step -2: Now, write the code and press "Ctrl+S" to save the file.
Step - 3: After saving the code, we can run it by clicking "Run" or "Run Module". It
will display the output to the shell.
We need to type the python keyword, followed by the file name and hit
enter to run the Python file.
Summary:
Python Syntax:
Python syntax can be executed by writing directly in the Command Line:
Keywords
Variables
What are Reserved Keywords in Python?
Reserved words (also called keywords) are defined with predefined meaning and
syntax in the language. These keywords have to be used to develop programming
instructions. Reserved words can’t be used as identifiers for other programming
elements like name of variable, function etc.
Following is the list of reserved keywords in Python 3
and except lambda with
as finally nonlocal while
assert false None yield
break for not
class from or
continue global pass
def if raise
del import return
elif in True
else is try
Python 3 has 33 keywords while Python 2 has 30. The print has been removed from
Python 2 as keyword and included as built-in function.
Hello, World!
Variables
Variables are containers for storing data values.
Creating Variables
x=5
y = "John"
print(x)
print(y)
o/p:
5
John
Casting
If you want to specify the data type of a variable, this can be done with casting.
Example
print(x)
print(y)
print(z)
o/p
3
3
3.0
x=5
y = "John"
print(type(x))
print(type(y))
o/p:
<class 'int'>
<class 'str'>
Example
x = "John"
print(x)
x = 'John'
print(x)
o/p:
John
John
Case-Sensitive
Variable names are case-sensitive.
Example
This will create two variables:
a=4
A = "Sally"
print(a)
print(A)
o/p:
4
Sally
o/p:
John
John
John
John
John
John
Example
o/p:
Orange
Banana
Cherry
Output Variables
The Python print statement is often used to output variables.
Example
x = "awesome"
print("Python is " + x)
o/p:
Python is awesome
Global Variables
Variables that are created outside of a function (as in all of the examples above) are known as
global variables.
Global variables can be used by everyone, both inside of functions and outside.
Example
Create a variable outside of a function, and use it inside the function
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
o/p:
Python is awesome
If you create a variable with the same name inside a function, this variable will be local, and can
only be used inside the function. The global variable with the same name will remain as it was,
global and with the original value.
Example
Create a variable inside a function, with the same name as the global variable
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
o/p:
Python is fantastic
Python is awesome
myfunc()
print("Python is " + x)
o/p:
Python is fantastic
Python Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Example
print(5 + 3)
o/p:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Operators Meaning
() Parentheses
** Exponent
+, - Addition, Subtraction
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <, <=, is, is not, in, not in Comparisons, Identity, Membership operators
or Logical OR
Example 1:
1. # Precedence of and and or operators
2. colour = "red"
3.
4. quantity = 0
5.
6. if colour == "red" or colour == "green" and quantity >= 5:
7. print("Your parcel is dispatched")
8. else:
9. print("your parcel cannot be dispatched")
O/p:
Your parcel is dispatched
Python Indentation
Indentation refers to the spaces at the beginning of a code line.
Example:
if 5 > 2:
print("Five is greater than two!")
o/p:
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
o/p
Syntax Error:
Python Comments
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.
Creating a Comment
Example:
#This is a comment
print("Hello, World!")
o/p:
Hello, World!
Comments can be placed at the end of a line, and Python will ignore the rest of
the line:
Hello, World!
Python does not really have a syntax for multi line comments.
Since Python will ignore string literals that are not assigned to a variable, you can
add a multiline string (triple quotes) in your code, and place your comment inside
it:
Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
o/p:
Hello, World!
Example
x=5
print(type(x))
o/p:
int
x = "Hello World"
#display x:
print(x)
Hello World
<class 'str'>
Python Numbers
There are three numeric types in Python:
int
float
complex
Variables of numeric types are created when you assign a value to them:
Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
print(type(x))
print(type(y))
print(type(z))
o/p:
<class 'int'>
<class 'float'>
<class 'complex'>
Python List:
Python lists are one of the most versatile data types that allow us to work with multiple elements at
once. For example,
# list of integers
my_list = [1, 2, 3]
A list can have any number of items and they may be of different types (integer, float, string,
etc.).
# empty list
my_list = []
A list can also have another list as an item. This is called a nested list.
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
We can use the index operator [] to access an item in a list. In Python, indices start at 0. So, a
list having 5 elements will have an index from 0 to 4.Nested lists are accessed using nested
indexing.
Output
p
o
e
a
5
Traceback (most recent call last):
File "<string>", line 21, in <module>
TypeError: list indices must be integers or slices, not float
Negative indexing
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to
the second last item and so on.
# last item
print(my_list[-1])
Output
e
p
my_list = ['p','r','o','g','r','a','m','i','z']
Output
print(my_list)
print(my_list)
Output
We can use remove () to remove the given item or pop () to remove an item at the given index.
The pop () method removes and returns the last item if the index is not provided. This helps us
implement lists as stacks (first in, last out data structure).
And, if we have to empty the whole list, we can use the clear () method.
Finally, we can also delete items in a list by assigning an empty list to a slice of elements.
Python Tuple
Creating a Tuple
A tuple is created by placing all the items (elements) inside parentheses (), separated by commas.
The parentheses are optional, however, it is a good practice to use them.
A tuple can have any number of items and they may be of different types (integer, float,
list, string, etc.).
# Empty tuple
my_tuple = ()
print(my_tuple)
# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
Output
()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))
A tuple can also be created without using parentheses. This is known as tuple packing.
print(a) #3
print(b) # 4.6
print(c) # dog
Output
There are various ways in which we can access the elements of a tuple.
1. Indexing
We can use the index operator [] to access an item in a tuple, where the index starts from 0.
So, a tuple having 6 elements will have indices from 0 to 5. Trying to access an index outside of
the tuple index range(6,7,... in this example) will raise an IndexError.
The index must be an integer, so we cannot use float or other types. This will result in TypeError.
Likewise, nested tuples are accessed using nested indexing, as shown in the example below.
print(my_tuple[0]) # 'p'
print(my_tuple[5]) # 't'
# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
# nested index
print(n_tuple[0][3]) # 's'
print(n_tuple[1][1]) #4
Output
p
t
s
4
2. Negative Indexing
The index of -1 refers to the last item, -2 to the second last item and so on.
# Output: 't'
print(my_tuple[-1])
# Output: 'p'
print(my_tuple[-6])
Output:
3. Slicing
We can access a range of items in a tuple by using the slicing operator colon :.
Output
Slicing can be best visualized by considering the index to be between the elements as shown below.
So if we want to access a range, we need the index that will slice the portion from the tuple.
This means that elements of a tuple cannot be changed once they have been assigned. But, if
the element is itself a mutable data type like a list, its nested items can be changed.
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple)
Output
We can also repeat the elements in a tuple for a given number of times using the * operator.
# Concatenation
# Output: (1, 2, 3, 4, 5, 6)
print((1, 2, 3) + (4, 5, 6))
# Repeat
# Output: ('Repeat', 'Repeat', 'Repeat')
print(("Repeat",) * 3)
Output
(1, 2, 3, 4, 5, 6)
('Repeat', 'Repeat', 'Repeat')
Tuple Operations
1. Tuple Membership Test
We can test if an item exists in a tuple or not, using the keyword in.
# In operation
print('a' in my_tuple)
print('b' in my_tuple)
# Not in operation
print('g' not in my_tuple)
Output
True
False
True
Output
Hello John
Hello Kate
Python Sets:
A set is an unordered collection of items. Every set element is unique (no duplicates) and must
be immutable (cannot be changed).
However, a set itself is mutable. We can add or remove items from it.
Sets can also be used to perform mathematical set operations like union, intersection, symmetric
difference, etc.
It can have any number of items and they may be of different types (integer, float, tuple, string
etc.). But a set cannot have mutable elements like lists, sets or dictionaries as its elements.
# Different types of sets in Python
# set of integers
my_set = {1, 2, 3}
print(my_set)
Output
{1, 2, 3}
{1.0, (1, 2, 3), 'Hello'}
# set cannot have duplicates
# Output: {1, 2, 3, 4}
my_set = {1, 2, 3, 4, 3, 2}
print(my_set)
# we can make set from a list
# Output: {1, 2, 3}
my_set = set([1, 2, 3, 2])
print(my_set)
Output
{1, 2, 3, 4}
{1, 2, 3}
Traceback (most recent call last):
File "<string>", line 15, in <module>
my_set = {1, 2, [3, 4]}
TypeError: unhashable type: 'list'
Python Dictionary
Python dictionary is an unordered collection of items. Each item of a dictionary has
a key/value pair.
Dictionaries are optimized to retrieve values when the key is known.
An item has a key and a corresponding value that is expressed as a pair (key: value).
While the values can be of any data type and can repeat, keys must be of immutable type
(string, number or tuple with immutable elements) and must be unique.
# empty dictionary
my_dict = {}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
If we use the square brackets [], KeyError is raised in case a key is not found in the dictionary. On
the other hand, the get() method returns None if the key is not found.
# Output: Jack
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
# KeyError
print(my_dict['address'])
Output
Jack
26
None
Traceback (most recent call last):
File "<string>", line 15, in <module>
print(my_dict['address'])
KeyError: 'address'
If the key is already present, then the existing value gets updated. In case the key is not present,
a new (key: value) pair is added to the dictionary.
# update value
my_dict['age'] = 27
# add item
my_dict['address'] = 'Downtown'
# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}
print(my_dict)
Output
{'name': 'Jack', 'age': 27}
{'name': 'Jack', 'age': 27, 'address': 'Downtown'}
The popitem () method can be used to remove and return an arbitrary (key, value) item pair from
the dictionary. All the items can be removed at once, using the clear () method.
We can also use the del keyword to remove individual items or the entire dictionary itself.
# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# Output: {1: 1, 2: 4, 3: 9}
print(squares)
# Output: {}
print(squares)
# Throws Error
print(squares)
Output
16
{1: 1, 2: 4, 3: 9, 5: 25}
(5, 25)
{1: 1, 2: 4, 3: 9}
{}
Traceback (most recent call last):
File "<string>", line 30, in <module>
print(squares)
NameError: name 'squares' is not defined
SAMPLE PYTHON PROGRAMS
1. Write a program in python to take the input from the user and find the sum,
difference, product, division, Modulus and power.
4. Swap two integer numbers using a temporary variable. Repeat the exercise
using the code format: a, b = b, a. Verify your results in both the cases.
x, y = y, x
print("x =", x)
print("y =", y)
Output:
x=6
y=4