Introduction To Programming With Python
Introduction To Programming With Python
Introduction To Programming With Python
with Python
Deependra Rastogi
Assistant Professor, CCSIT
TMU
1
Languages
Some influential ones:
FORTRAN
science / engineering
COBOL
business data
LISP
logic and AI
BASIC
a simple language
2
Programming basics
code or source code: The sequence of instructions in a program.
3
Compiling and interpreting
Many languages require you to compile (translate) your program
into a form that the machine understands.
compile execute
source code byte code output
Hello.java Hello.class
interpret
source code output
Hello.py
4
Python Program Structure
5
Python Identifier
A Python identifier is a name used to identify a variable, function,
class, module or other object. An identifier starts with a letter A to
Z or a to z or an underscore (_) followed by zero or more letters,
underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and %
within identifiers. Python is a case sensitive programming
language. Thus, Manpower and manpower are two different
identifiers in Python.
Here are naming conventions for Python identifiers −
Class names start with an uppercase letter. All other identifiers start
with a lowercase letter.
Starting an identifier with a single leading underscore indicates that the
identifier is private.
Starting an identifier with two leading underscores indicates a strongly
private identifier.
If the identifier also ends with two trailing underscores, the identifier is
a language-defined special name.
6
Reserved Word
7
Lines and Indentation
Python provides no braces to indicate blocks of code for class and
function definitions or flow control. Blocks of code are denoted by
line indentation, which is rigidly enforced.
The number of spaces in the indentation is variable, but all
statements within the block must be indented the same amount.
For example −
if True:
print "True"
else:
print "False"
8
Lines and Indentation
However, the following block generates an error −
if True:
print "Answer"
print "True"
else:
print "Answer"
print "False“
Thus, in Python all the continuous lines indented with same number
of spaces would form a block.
9
Lines and Indentation
However, the following block generates an error −
if True:
print "Answer"
print "True"
else:
print "Answer"
print "False“
Thus, in Python all the continuous lines indented with same number
of spaces would form a block.
10
Multi Line Statement
Statements in Python typically end with a new line. Python does,
however, allow the use of the line continuation character (\) to
denote that the line should continue. For example −
total = item_one + \
item_two + \
item_three
Statements contained within the [], {}, or () brackets do not need to
use the line continuation character. For example −
11
Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes to
denote string literals, as long as the same type of quote starts and
ends the string.
The triple quotes are used to span the string across multiple lines.
For example, all the following are legal −
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
12
Comment in Python
A hash sign (#) that is not inside a string literal begins a comment.
All characters after the # and up to the end of the physical line are
part of the comment and the Python interpreter ignores them.
#!/usr/bin/python
# First comment
13
print() in Python
In Python a function is a group of statements that are put together to
perform a specific task. The task of print function is to display the
contents on the screen. The syntax of print function is
print() Parameters
objects - object to the printed. * indicates that there may be more
than one object
sep - objects are separated by sep. Default value: ' '
end - end is printed at last
file - must be an object with write(string) method. If omitted
it, sys.stdout will be used which prints objects on the screen.
flush - If True, the stream is forcibly flushed. Default value: False
14
print() in Python
The argument of the print function can be a value of any type int,
str, float etc. it also be a value stored in a variable.
Example
print("Python is fun.")
a=5
15
Variable
In most of the programming languages a variable is a named location
used to store data in the memory. Each variable must have a unique
name called identifier. It is helpful to think of variables as container
that hold data which can be changed later throughout programming.
16
Variable
Declaring Variables in Python
In Python, variables do not need declaration to reserve memory
space. The "variable declaration" or "variable initialization" happens
automatically when we assign a value to a variable.
website = "Apple.com“
print(website)
17
Variable
website = "Apple.com“
# assigning a new variable to website
website = "Programiz.com“
print(website)
18
Variable
If we want to assign the same value to multiple variables at once, we
can do this as
x = y = z = "same“
print (x)
print (y)
print (z)
19
Variable
Rules and Naming convention for variables and constants
Create a name that makes sense. Suppose, vowel makes more
sense than v.
Use camelCase notation to declare a variable. It starts with
20
Variable
Never use special symbols like !, @, #, $, %, etc.
Don't start name with a digit.
Constants are put into Python modules and meant not be changed.
Constant and variable names should have combination of letters in
lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an
underscore (_). For example:
snake_case
MACRO_CASE
camelCase C
apWords
21
Literals
Literal is a raw data given in a variable or constant. In Python, there
are various types of literals they are as follows:
Numeric Literals
String Literals
Boolean Literals
Special Literals
Literal Collection
22
Literals
Numeric Literals
Numeric Literals are immutable (unchangeable). Numeric literals can
#Float Literal
float_1 = 10.5
float_2 = 1.5e2
#Complex Literal
x = 3.14j
print(a, b, c, d)
print(float_1, float_2)
print(x, x.imag, x.real)
23
Literals
String literals
A string literal is a sequence of characters surrounded by quotes. We
can use both single, double or triple quotes for a string. And, a
character literal is a single character surrounded by single or double
quotes.
24
Literals
Boolean literals
A Boolean literal can have any of the two values: True or False.
25
Literals
Literal Collections
There are four different literal collections List literals, Tuple literals,
Dict literals, and Set literals.
26
Literals
Special literals
Python contains one special literal i.e. None. We use it to specify to
that field that is not created.
27
input() in python
The input() method reads a line from input, converts into a string
and returns it.
28
input() in python
Return value from input()
The input() method reads a line from input (usually user), converts
the line into a string by removing the trailing newline, and returns it.
29
input() in python
30
Python Type Conversion
The process of converting the value of one data type (integer, string,
float, etc.) to another data type is called type conversion. Python has
two types of type conversion.
31
Python Type Conversion
32
Python Type Conversion
33
Python Type Conversion
34
Python Type Conversion
Explicit Type Conversion:
In Explicit Type Conversion, users convert the data type of an object
to required data type. We use the predefined functions
like int(), float(), str(), etc to perform explicit type conversion.
This type conversion is also called typecasting because the user casts
(change) the data type of the objects.
Syntax :
(required_datatype)(expression)
35
Python Type Conversion
36
Python Type Conversion
37
Python Type Conversion
Type Conversion is the conversion of object from one data type to
another data type.
Implicit Type Conversion is automatically performed by the Python
interpreter.
Python avoids the loss of data in Implicit Type Conversion.
Explicit Type Conversion is also called Type Casting, the data types
of object are converted using predefined function by user.
In Type Casting loss of data may occur as we enforce the object to
specific data type.
38
Example Programs
#Simple Interest
SI=(P * R * T)/100
39
Example Programs
#Compound Interest
40
Example Programs
#Compound Interest
41
Example Programs
#Program to find area of a circle
42
Output formatting
Sometimes we would like to format our output to make it look
attractive. This can be done by using the str.format() method. This
method is visible to any string object.
43
Output formatting
44
Output formatting
45
Operator
46
Operator
47
Operator
48
Operator
49
Operator
50
Operator
51
Operator
52
Operator
53
Operator
54
Operator
# Python Program to calculate the square root
55
Operator
# Python Program to find the area of triangle
56
Operator
# Solve the quadratic equation ax**2 + bx + c = 0
57
Operator
# Solve the quadratic equation ax**2 + bx + c = 0
58
Repetition (loops)
and Selection (if/else)
59
The for loop
for loop: Repeats a set of statements over a group of values.
Syntax:
for variableName in groupOfValues:
statements
We indent the statements to be repeated with tabs or spaces.
variableName gives a name to each value, so you can refer to it in the statements.
groupOfValues can be a range of integers, specified with the range function.
Example:
for x in range(1, 6):
print x, "squared is", x * x
Output:
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
60
The for loop
for loop: Repeats a set of statements over a group of values.
Syntax:
for variableName in groupOfValues:
statements
We indent the statements to be repeated with tabs or spaces.
variableName gives a name to each value, so you can refer to it in the statements.
groupOfValues can be a range of integers, specified with the range function.
Example:
for x in range(1, 6):
print x, "squared is", x * x
Output:
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
61
The for loop
# Program to find the sum of all numbers stored in a list
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
62
The for loop
for loop with else
A for loop can have an optional else block as well. The else part is executed if the items
in the sequence used in for loop exhausts.
break statement can be used to stop a for loop. In such case, the else part is ignored.
Hence, a for loop's else part runs if no break occurs.
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
63
range
The range function specifies a range of integers:
range(start, stop) - the integers between start (inclusive)
and stop (exclusive)
It can also accept a third value specifying the change between values.
range(start, stop, step) - the integers between start (inclusive)
and stop (exclusive) by step
Example:
for x in range(5, 0, -1):
print x
print "Blastoff!"
Output:
5
4
3
2
1
Blastoff!
64
range
# Program to iterate through a list using indexing
65
Cumulative loops
Some loops incrementally compute a value that is initialized outside
the loop. This is sometimes called a cumulative sum.
sum = 0
for i in range(1, 11):
sum = sum + (i * i)
print "sum of first 10 squares is", sum
Output:
sum of first 10 squares is 385
66
if
if statement: Executes a group of statements only if a certain
condition is true. Otherwise, the statements are skipped.
Syntax:
if condition:
statements
Example:
gpa = 3.4
if gpa > 2.0:
print "Your application is accepted."
67
if/else
if/else statement: Executes one block of statements if a certain
condition is True, and a second block of statements if it is False.
Syntax:
if condition:
statements
else:
statements
Example:
gpa = 1.4
if gpa > 2.0:
print "Welcome to Mars University!"
else:
print "Your application is denied."
Syntax:
while condition:
statements
Example:
number = 1
while number < 200:
print number,
number = number * 2
Output:
1 2 4 8 16 32 64 128
69
while
# numbers upto
# sum = 1+2+3+...+n
while i <= n:
sum = sum + i
i = i+1 # update counter
70
while
while loop with else
Same as that of for loop, we can have an optional else block with while loop as well.
The else part is executed if the condition in the while loop evaluates to False.
The while loop can be terminated with a break statement. In such case, the else part
is ignored. Hence, a while loop's else part runs if no break occurs and the condition
is false.
71
Examples
# Python program to check if the input number is prime or not
72
Examples
# Python program to display all the prime numbers within an interval
73
Examples
# Python program to find the factorial of a number provided by the user.
factorial = 1
74
Examples
# Program to display the Fibonacci sequence up to n-th term where n is provided by the
user
# initialize sum
sum = 0
76
Examples
# Python program to find the largest number among the three input numbers
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
77
Examples
# Program to check Armstrong numbers in certain interval
# order of number
order = len(str(num))
# initialize sum
sum = 0
if num == sum:
print(num)
78
Examples
# Program to check Armstrong numbers in certain interval
# order of number
order = len(str(num))
# initialize sum
sum = 0
if num == sum:
print(num)
79
Examples
#Number is Even or Odd
80
Examples
# Python program to check if the input year is a leap year or not
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
81
List, Tuple, String and Dictionary
82
How to create list?
In Python programming, a list is created by placing all the items (elements) inside a
square bracket [ ], separated by commas.
It can have any number of items and they may be of different types (integer, float,
string etc.).
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
83
How to create list?
Also, a list can even have another list as an item. This is called
nested list.
# nested list
84
How to access elements from a list?
List Index
We can use the index operator [] to access an item in a list. Index
starts from 0. So, a list having 5 elements will have index from 0 to
4.
Trying to access an element other that this will raise an IndexError.
The index must be an integer. We can't use float or other types,
this will result into TypeError.
Nested list are accessed using nested indexing.
85
How to access elements from a list?
86
How to access elements from a list?
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.
87
How to slice lists in Python?
We can access a range of items in a list by using the slicing operator
(colon).
88
How to change or add elements to a list?
List are mutable, meaning,
their elements can be
changed
unlike string or tuple.
We can use assignment
operator (=) to change an
item or a range of items.
89
How to change or add elements to a list?
We can add one item to a list
using append() method or
add several items
using extend()method.
90
list.append(item)
92
list.append(item)
93
list.append(item)
94
How to change or add elements to a list?
We can also use + operator
to combine two lists. This is
also called concatenation.
The * operator repeats a list
for the given number of
times.
95
How to change or add elements to a list?
Furthermore, we can insert
one item at a desired location
by using the
method insert() or insert
multiple items by squeezing it
into an empty slice of a list.
96
How to change or add elements to a list?
Furthermore, we can insert one item at a desired location by using
the method insert() or insert multiple items by squeezing it into
an empty slice of a list.
insert() Parameters
The insert() function takes two parameters:
index - position where an element needs to be inserted
element - this is the element to be inserted in the list
97
How to change or add elements to a list?
Return Value from insert()
The insert() method only inserts the element to the list. It doesn't
return anything; returns None.
98
How to change or add elements to a list?
Inserting a Tuple (as an Element) to the List
99
How to delete or remove elements from a
list?
We can delete one or
more items from a list
using the keyword del. It
can even delete the list
entirely.
100
How to delete or remove elements from a
list?
We can use remove() method to remove the given item
or pop() method to remove an item at the given index.
101
How to delete or remove elements from a
list?
102
How to delete or remove elements from a
list?
remove() Method on a List having Duplicate Elements
103
How to delete or remove elements from a
list?
pop() parameter
The pop() method takes a single argument (index) and removes
the item present at that index.
If the index passed to the pop() method is not in range, it
throws IndexError: pop index out of range exception.
The parameter passed to the pop() method is optional. If no
parameter is passed, the default index -1 is passed as an
argument which returns the last item.
104
How to delete or remove elements from a
list?
Print Element Present at the Given Index from the List
105
How to delete or remove elements from a
list?
pop() without an index, and for negative indices
106
How to delete or remove elements from a
list?
pop() without an index, and for negative indices
107
Python List Method
108
Python List Method
Python List count()
The count() method returns the number of occurrences of an
element in a list.
count() Parameters
The count() method takes a single argument:
element - element whose count is to be found.
109
Python List Method
Count the occurrence of an element in the list
110
Python List Method
List reverse()
The reverse() method reverses the elements of a given list.
111
Python List Method
Reverse a List Using Slicing Operator
112
Python List Method
Accessing Individual Elements in Reversed Order
113
Python List Method
List sort()
The sort() method sorts the elements of a given list in a specific order -
Ascending or Descending.
The syntax of sort() method is:
list.sort(key=..., reverse=...)
Alternatively, you can also use Python's in-built function sorted() for the same
purpose.
sorted(list, key=..., reverse=...)
Note: Simplest difference between sort() and sorted() is: sort() doesn't return
any value while, sorted() returns an iterable list.
sort() Parameters
By default, sort() doesn't require any extra parameters. However, it has two
optional parameters:
reverse - If true, the sorted list is reversed (or sorted in Descending order)
key - function that serves as a key for the sort comparison
114
Python List Method
Sort a given list
115
Python List Method
How to sort in Descending order?
116
Python List Method
How to sort using your own function with key parameter?
If you want your own implementation for sorting, sort() also accepts
a key function as an optional parameter.
Based on the results of the key function, you can sort the given list.
list.sort(key=len)
Alternatively for sorted
sorted(list, key=len)
117
Python List Method
Sort the list using key
118
Python List Method
119
Python List Method
Matrix Addition using Nested List Comprehension
120
Python List Method
121
Python List Example
122
Python List Example
123
Python List Example
124
Python Tuple
What is tuple?
In Python programming, a tuple is similar to a list. The difference between the two is
that we cannot change the elements of a tuple once it is assigned whereas in a list,
elements can be changed.
125
Creating a Tuple
A tuple is created by placing
all the items (elements) inside
a parentheses (), separated by
comma. The parentheses are
optional but is a good practice
to write it.
A tuple can have any number
of items and they may be of
different types (integer, float,
list, string etc.).
126
Creating a Tuple
Creating a tuple with one
element is a bit tricky.
Having one element within
parentheses is not enough.
We will need a trailing
comma to indicate that it is
in fact a tuple.
127
Accessing Elements in a Tuple
Indexing
We can use the index operator []
128
Changing a Tuple
Unlike lists, tuples are
immutable.
This means that elements
of a tuple cannot be
changed once it has been
assigned. But, if the
element is itself a mutable
datatype like list, its
nested items can be
changed.
We can also assign a tuple
to different values
(reassignment).
129
Deleting a Tuple
we cannot change the elements in a tuple. That also means we
cannot delete or remove items from a tuple.
But deleting a tuple entirely is possible using the keyword del.
130
Built-in Functions with Tuple
131
Built-in Functions with Tuple
132
Built-in Functions with Tuple
Python any()
133
Built-in Functions with Tuple
Python len()
134
Python Dictionary
What is dictionary in Python?
Python dictionary is an unordered collection of items. While other
known.
135
Python Dictionary
136
How to access elements from a dictionary?
While indexing is used with other container types to access
values, dictionary uses keys. Key can be used either inside square
brackets or with the get() method.
The difference while using get() is that it returns None instead
of KeyError, if the key is not found.
137
How to change or add elements in a
dictionary?
Dictionary are mutable. We can add new items or change the
value of existing items using assignment operator.
If the key is already present, value gets updated, else a new key:
value pair is added to the dictionary.
138
How to delete or remove
elements from a dictionary?
We can remove a particular
item in a dictionary by
using the method pop().
This method removes as
item with the provided key
and returns the value.
The method, popitem() can
be used to remove and
return an arbitrary item
(key, value) form 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.
139
How to delete or remove elements from a
dictionary?
140
Python Dictionary Comprehension
Dictionary comprehension is an elegant and concise way to create
new dictionary from an iterable in Python.
Dictionary comprehension consists of an expression pair (key:
value) followed by forstatement inside curly braces {}.
Here is an example to make a dictionary with each item being a
pair of a number and its square.
141
Python Dictionary Comprehension
142
Python Dictionary Comprehension
Here are some examples to make dictionary with only odd items.
143
Python Nested Dictionary
144
Python Nested Dictionary
Create a Nested Dictionary
145
Python Nested Dictionary
Access elements of a Nested Dictionary
146
Python Nested Dictionary
Add element to a Nested Dictionary
147
Python Nested Dictionary
Add another dictionary to the nested dictionary
148
Python Nested Dictionary
Delete elements from a Nested Dictionary
149
Python Nested Dictionary
How to delete dictionary from a nested dictionary?
150
Python Nested Dictionary
How to iterate through a Nested dictionary?
151
Python String
A string is a sequence of characters.
A character is simply a symbol. For example, the English
language has 26 characters.
Computers do not deal with characters, they deal with numbers
(binary). Even though you may see characters on your screen,
internally it is stored and manipulated as a combination of 0's and
1's.
This conversion of character to a number is called encoding, and
the reverse process is decoding. ASCII and Unicode are some of
the popular encoding used.
In Python, string is a sequence of Unicode character. Unicode was
introduced to include every character in all languages and bring
uniformity in encoding. You can learn more about Unicode from
here.
152
How to create a string in Python?
Strings can be created by enclosing characters inside a single quote
or double quotes. Even triple quotes can be used in Python but
generally used to represent multiline strings and docstrings.
153
How to access characters in a string?
We can access individual characters using indexing and a range
of characters using slicing. Index starts from 0. Trying to access a
character out of index range will raise an IndexError. The index
must be an integer. We can't use float or other types, this will
result into TypeError.
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. We can access a range of items in a string by using
the slicing operator (colon).
154
How to access characters in a string?
155
Python String Operations
Concatenation of Two or More Strings
Joining of two or more strings into a single one is called
concatenation.
The + operator does this in Python. Simply writing two string
literals together also concatenates them.
The * operator can be used to repeat the string for a given
number of times.
156
Python String Operations
Built-in functions to Work with Python
Various built-in functions that work with sequence, works with
string as well.
Some of the commonly used ones are enumerate() and len().
The enumerate() function returns an enumerate object. It
contains the index and value of all the items in the string as
pairs. This can be useful for iteration.
Similarly, len() returns the length (number of characters) of the
string.
157
Python String Formatting
Escape Sequence
If we want to print a text like -He said, "What's there?"- we can
neither use single quote or double quotes. This will result
into SyntaxError as the text itself contains both single and double
quotes.
One way to get around this problem is to use triple quotes.
Alternatively, we can use escape sequences.
An escape sequence starts with a backslash and is interpreted
differently. If we use single quote to represent a string, all the
single quotes inside the string must be escaped. Similar is the
case with double quotes. Here is how it can be done to represent
the above text.
158
Python String Formatting
159
Python String Formatting
Raw String to ignore escape sequence
Sometimes we may wish to ignore the escape sequences inside a
string. To do this we can place r or R in front of the string. This
will imply that it is a raw string and any escape sequence inside it
will be ignored.
160
Python String Formatting
161
Common Python String Methods
162
String Example
163
String Example
164
String Example
165
String Methods
166
String Methods
167
String Methods
168
String Methods
169
String Methods
170