Python Overview
Python is an easy to learn, powerful programming language. It has
efficient high-level data structures and a simple but effective approach to
object-oriented programming. Python’s elegant syntax and dynamic
typing, together with its interpreted nature, make it an ideal language
for scripting and rapid application development in many areas on
most platforms.
The Python interpreter and the extensive standard library are
freely available in source or binary form for all major platforms from the
Python Web site, https://www.python.org/, and may be freely distributed
What can Python do?
Web applications.
Desktop GUI applications
Software Development
Game Development
Scientific and Numeric Applications.
Artificial Intelligence
Data Science Applications
Machine Learning Applications
Advantages
Python is simple to use, offering much more structure and support
for large programs than shell scripts or batch files can offer.
Python also offers much more error checking than C
Python allows you to split your program into modules that can
be reused in other Python programs.
It comes with a large collection of standard modules that you can
use as the basis of your programs
Python is an interpreted language, which can save you
considerable time during program development because no
compilation and linking is necessary.
Programs written in Python are typically much shorter than
equivalent C, C++, or Java programs, for several reasons:
The high-level data types allow you to express complex
operations in a single statement;
Statement grouping is done by indentation instead of
beginning and ending brackets;
No variable or argument declarations are necessary.
Python works on different platforms (Windows, Mac, Linux,
Raspberry Pi, etc).
Programming Modes in Python
Python has two basic modes: normal and interactive.
The normal mode is the mode where the scripted and finished .py files are
run in the Python interpreter.
Interactive mode is a command line shell which gives immediate feedback
for each statement, while running previously fed statements in active
memory.
Python Keywords
Keywords are the reserved words in Python.
We cannot use a keyword as a variable name, function name or any other
identifier. They are used to define the syntax and structure of the Python
language.
In Python, keywords are case sensitive.
There are 35 keywords in Python 3.8. This number can vary slightly over
the course of time.
All the keywords except True, False and None are in lowercase and they
must be written as they are. The list of all the keywords is given below .
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield
Python Identifiers
An identifier is a name given to entities like class, functions,
variables, etc. It helps to differentiate one entity from another.
Rules for writing identifiers
1. Identifiers can be a combination of letters in lowercase (a to z) or
uppercase (A to Z) or digits (0 to 9) or an underscore _ Names like
myClass, var_1 and print_this_to_screen, all are valid example.
2. An identifier cannot start with a digit. 1variable is invalid,
but variable1 is a valid name.
3. Keywords cannot be used as identifiers
4. We cannot use special symbols like !, @, #, $, % etc. in our
identifier.
5. An identifier can be of any length
Python Statement
Instructions that a Python interpreter can execute are called statements.
For example, a = 1 is an assignment statement. if statement, for
statement, while statement, etc. are other kinds of statements.
PYTHON DATA TYPES
Every value in Python has a datatype. Since everything is an object in
Python programming, data types are actually classes and variables are
instance (object) of these classes.
Numbers
Integers, floating point numbers and complex numbers fall under Python
numbers category. They are defined as int, float and complex classes in
Python.
We can use the type() function to know which class a variable or a value
belongs to.
PROGRAM
a=5
print(a, "is of type", type(a))
a = 2.0
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
OUTPUT
5 is of type <class 'int'>
2.0 is of type <class 'float'>
(1+2j) is complex number? True
Integers can be of any length, it is only limited by the memory
available.
A floating-point number is accurate up to 15 decimal places. Integer
and floating points are separated by decimal points. 1 is an integer, 1.0 is
a floating-point number.
Complex numbers are written in the form, x + yj, where x is the real
part and y is the imaginary part. Here are some examples.
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.
PROGRAM
single_line = "Welcome to Inspire Solutions"
char = "P"
multi_line = """Welcome to Inspire Solutions
This is 30 Hours Online Hands-on Programme
for Python Programming"""
print("Single Line: ", single_line)
print("Single Character :", char)
print("Multi Line: ",multi_line)
OUTPUT
Single Line: Welcome to Inspire Solutions
Single Character : Python Programming
Multi Line: Welcome to Inspire Solutions
This is 30 Hours Online Hands-on Programme
for Python Programming
s1='Welcome'
Indexing 0 1 2 3 4 5 6
String – s1 W E L C O M E
-ve Index -7 -6 -5 -4 -3 -2 -1
List
List is an ordered sequence of items. It is one of the most used
datatype in Python and is very flexible. All the items in a list do not
need to be of the same type.
Declaring a list is pretty straight forward. Items separated by commas are
enclosed within brackets [ ].
0 1 2 3 4 Positive Indexing
99 98 96 95 100 marks
-5 -4 -3 -2 -1 Negative Indexing
PROGRAM
student= [101, 'RAM', 100.5, 'CSE']
print(student[0])
print(student[1])
print(student[2])
print(student[3])
print(student[-1])
print(student[-2])
print(student[-3])
print(student[-4])
print(student)
OUTPUT
101
RAM
100.5
CSE
CSE
100.5
RAM
101
[101, 'RAM', 100.5, 'CSE']
Lists are mutable, meaning, the value of elements of a list can be
altered.
PROGRAM
student= [101, 'RAM', 100.5, 'CSE']
student[1] = ‘RAJ’
print(student)
OUTPUT
[101, 'RAJ', 100.5, 'CSE']
Tuple
Tuple is an ordered sequence of items same as a list. The only
difference is that tuples are immutable. Tuples once created cannot be
modified.
Tuples are used to write-protect data and are usually faster than lists as
they cannot change dynamically.
It is defined within parentheses ( ) where items are separated by commas.
PROGRAM
student= (101, 'RAM', 100.5, 'CSE')
print(student[0])
print(student[1])
print(student[2])
print(student[3])
print(student[-1])
print(student[-2])
print(student[-3])
print(student[-4])
OUTPUT
101
RAM
100.5
CSE
CSE
100.5
RAM
101
If we try to change a value of a tuple. We will get error as mention below
student[1]='RAJ'
print(student)
TypeError: 'tuple' object does not support item assignment
Set
Set is an unordered collection of unique items. Set is defined by
values separated by comma inside braces { }. Items in a set are not
ordered.
set1 = {1, 3, 6, 7, 9}
print(set1)
Since, set are unordered collection, indexing has no meaning. Hence, the
slicing operator [ ] does not work.
Dictionary
Dictionary is an unordered collection of key-value pairs.
It is generally used when we have a huge amount of data. Dictionaries are
optimized for retrieving data. We must know the key to retrieve the value.
In Python, dictionaries are defined within braces { } with each item being
a pair in the form key:value. Key and value can be of any type.
PROGRAM
student= {'rollno':101, 'name':'RAM', 'grade':9.5,'branch':'CSE'}
print(student['name'])
OUTPUT
RAM
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.
Consider the below example
x = 5; y = 10
print('The sum of', x, 'and', y, 'is',x+y)
OUTPUT
The sum of 5 and 10 is 15
For Better Understanding we can use format( ) function to get same
output
PROGRAM
x = 5; y = 10
print('The sum of {} and {} is {}'.format(x,y,x+y)
OUTPUT
The sum of 5 and 10 is 15
Input Statement
Till now, our programs were static. The value of variables was defined or
hard coded into the source code.
To allow flexibility, we might want to take the input from the user. In
Python, we have the input() function to allow this. The syntax
for input() is:
input([prompt])
where prompt is the string we wish to display on the screen. It is
optional.
The return type of input statement is always a String
Example
num=input(‘Enter a Number’)
print(“The values Entered is”,num)
OUTPUT
Enter a Number 10.5
The values Entered is 10.5
Check the type of the variable, Do you think the type will be float since
the value given is 10.5?
But the type is str only
PROGRAM
num=input('Enter a Number')
print('The values Entered is',num)
print(type(num))
OUTPUT
Enter a Number10.5
The values Entered is 10.5
<class 'str'>
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.
Consider the below example
x = 5; y = 10
print('The sum of', x, 'and', y, 'is',x+y)
OUTPUT
The sum of 5 and 10 is 15
For Better Understanding we can use format( ) function to get same
output
PROGRAM
x = 5; y = 10
print('The sum of {} and {} is {}'.format(x,y,x+y)
OUTPUT
The sum of 5 and 10 is 15
Input Statement
Till now, our programs were static. The value of variables was defined or
hard coded into the source code.
To allow flexibility, we might want to take the input from the user. In
Python, we have the input() function to allow this. The syntax
for input() is:
input([prompt])
where prompt is the string we wish to display on the screen. It is
optional.
The return type of input statement is always a String
Example
num=input(‘Enter a Number’)
print(“The values Entered is”,num)
OUTPUT
Enter a Number 10.5
The values Entered is 10.5
Check the type of the variable, Do you think the type will be float since
the value given is 10.5?
But the type is str only
PROGRAM
num=input('Enter a Number')
print('The values Entered is',num)
print(type(num))
OUTPUT
Enter a Number10.5
The values Entered is 10.5
<class 'str'>
Operators
Operators are special symbols in Python that carry out arithmetic or
logical computation. The value that the operator operates on is called
the operand.
Consider the following statement
z=x+y
where x and y are operands and + is the operator addition
Arithmetic operators
Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication, etc.
Operat
Meaning Example
or
+ Add two operands or unary plus x + y+ 2
Subtract right operand from the left or
- x - y- 2
unary minus
* Multiply two operands x*y
Divide left operand by the right one
/ x/y
(always results into float)
x % y
Modulus - remainder of the division of
% (remainder of
left operand by the right
x/y)
Floor division - division that results into
// whole number adjusted to the left in x // y
the number line
Exponent - left operand raised to the x**y (x to the
**
power of right power y)
Comparison operators
Comparison operators are used to compare values. It returns either True
or False according to the condition.
Operat Exampl
Meaning
or e
Greater than - True if left operand is greater
> x>y
than the right
Less than - True if left operand is less than
< x<y
the right
== Equal to - True if both operands are equal x == y
!= Not equal to - True if operands are not equal x != y
Greater than or equal to - True if left operand
>= x >= y
is greater than or equal to the right
Less than or equal to - True if left operand is
<= x <= y
less than or equal to the right
Logical operators
Logical operators are the and, or, not operators.
Operat Examp
Meaning
or le
and True if both the operands are true x and y
or True if either of the operands is true x or y
True if operand is false (complements the
not not x
operand)
Bitwise operators
Bitwise operators act on operands as if they were strings of binary
digits. They operate bit by bit, hence the name.
For example, 2 is 10 in binary and 7 is 111.
In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000
0100 in binary)
Operator Meaning Example
& Bitwise AND x & y = 0 (0000 0000)
| Bitwise OR x | y = 14 (0000 1110)
~ Bitwise NOT ~x = -11 (1111 0101)
^ Bitwise XOR x ^ y = 14 (0000 1110)
>> Bitwise right shift x >> 2 = 2 (0000 0010)
<< Bitwise left shift x << 2 = 40 (0010 1000)
Assignment operators
Assignment operators are used in Python to assign values to variables.
a = 5 is a simple assignment operator that assigns the value 5 on the right
to the variable a on the left.
There are various compound operators in Python like a += 5 that adds to
the variable and later assigns the same. It is equivalent to a = a + 5.
Operator Example Equivalent to
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
&= x &= 5 x=x&5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
>>= x >>= 5 x = x >> 5
<<= x <<= 5 x = x << 5
Special operators
Python language offers some special types of operators like the identity
operator and the membership operator . They are described below
with examples.
Membership operators
in and not in are the membership operators. These are used to test
whether the given element is present in the given sequence or not
PROGRAM
marks=[99,98,97,93,88,91]
print(91 in marks) #Returs True since 91 is in the list marks
print(92 in marks) #Returs False since 92 is not in the list marks
OUTPUT
True
False
PROGRAM
s='Welcome to Python Programming Course'
print('to' in s)
print('is' in s)
print('to' not in s)
print('is' not in s)
OUTPUT
True
False
False
True
Identity operators
is and is not are the identity operators in Python. They are used to check
if two values (or variables) are located on the same part of the memory.
Two variables that are equal does not imply that they are identical.
Operat
Meaning Example
or
True if the operands are identical
is x is True
(refer to the same object)
True if the operands are not identical x is not
is not
(do not refer to the same object) True
Example
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]
# Output: False
print(x1 is not y1)
# Output: True
print(x2 is y2)
# Output: False
print(x3 is y3)
PROGRAM
x = [1,2,3]
y = [1,2,3]
z=x
if (x == y):
print("True")
else:
print("False")
if (x is y):
print("True")
else:
print("False")
if (x is z):
print("True")
else:
print("False")
OUTPUT
True
False
True
Operator Precedence
The combination of values, variables, operators, and function calls is
termed as an expression. The Python interpreter can evaluate a valid
expression.
For example z = x +y is an expression
There can be more than one operator in an expression.
To evaluate these types of expressions there is a rule of precedence in
Python. It guides the order in which these operations are carried out.
For example, multiplication has higher precedence than subtraction.
x = 10 + 2 * 3
What will be the value of x after the above statement?
x = 36 or 16 ?
The answer is 16 why because in the above operation we have more than
one operations ( i.e + and *) out of which * has the highest priority.
Operator Description
** Exponentiation (raise to the power)
~+- Complement, unary plus and minus (method names for the last
two are +@ and -@)
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^| Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= += *= Assignment operators
**=
is is not Identity operators
in not in Membership operators
not or and Logical operators
Python control structures
Flow of control through any given program is implemented with three
basic types of control structures: Sequential, Selection and
Repetition.
Selection / Decision Making / Branching Statement
Decision making is required when we want to execute a code only if a
certain condition is satisfied.
The if…elif…else statement is used in Python for decision making.
Simple if Statement Syntax
if test_expression:
statement(s)
Here, the program evaluates the test_expression and will execute
statement(s) only if the test expression is True.
If the test expression is False, the statement(s) is not executed.
In Python, the body of the if statement is indicated by the indentation.
The body starts with an indentation and the first unindented line marks
the end.
Python interprets non-zero values as True. None and 0 are
interpreted as False.
if Statement
# If the number is positive, we print an appropriate message
num = 13
if num > 0:
print(num, "is a positive number.")
print("I am out of If Statement")
num = -13
if num < 0:
print(num, "is a Negative number.")
print("I am out of If Statement")
OUTPUT
13 is a positive number.
I am out of If Statement
-13 is a Negative number.
I am out of If Statement
if...else Statement
Syntax of if...else
if test expression:
Body of if
else:
Body of else
The if..else statement evaluates test expression and will execute the
body of if only when the test condition is True.
If the condition is False, the body of else is executed. Indentation is used
to separate the blocks.
Example1
num = 13
if num > 0:
print(num, "is a positive number.")
else:
print(num, "is a Negative number.")
print("I am out of If Statement")
OUTPUT
13 is a positive number.
I am out of If Statement
Example 2
num = int(input("Enter a Number"))
if num > 0:
print(num, "is a positive number.")
else:
print(num, "is a Negative number.")
print("I am out of If Statement")
OUTPUT
Enter a Number-12
-12 is a Negative number.
I am out of If Statement
if...elif...else Statement
Syntax of if...elif...else
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
The elif is short for else if. It allows us to check for multiple
expressions.
If the condition for if is False, it checks the condition of the next elif block
and so on.
If all the conditions are False, the body of else is executed.
Only one block among the several if...elif...else blocks is executed
according to the condition.
The if block can have only one else block. But it can have
multiple elif blocks.
Flowchart of if...elif...else
EXAMPLE
num = int(input("Enter a Number"))
if num > 0:
print(num, "is a positive number.")
elif(num<0):
print(num, "is a Negative number.")
else:
print(num, "is zero")
print("I am out of If Statement")
OUTPUT
Enter a Number0
0 is zero
I am out of If Statement
Nested if statements
We can have a if...elif...else statement inside another if...elif...else
statement. This is called nesting in computer programming.
Any number of these statements can be nested inside one another.
Indentation is the only way to figure out the level of nesting. They can get
confusing, so they must be avoided unless necessary.
Example
num = int(input("Enter a Number"))
if num > 0:
print(num, "is a positive number.")
else:
if(num<0):
print(num, "is a Negative number.")
else:
print(num, "is zero")
print("I am out of If Statement")
OUTPUT
Enter a Number0
0 is zero
I am out of If Statement
Enter a Number 12
12 is a positive number.
I am out of If Statement
Enter a Number -12
-12 is a Negative number.
I am out of If Statement
LOOPING Statement / Iterative Statement
The for loop in Python is used to iterate over a sequence / iterator
(list, tuple, string) or other iterable objects. Iterating over a sequence is
called traversal.
Syntax of for Loop
for <val> in <sequence/iterator>:
Body of for loop
Here, val is the variable that takes the value of the item inside the
sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of
for loop is separated from the rest of the code using indentation
Example
str="Welcome"
for i in str:
print(i)
OUTPUT
e
l
EXAMPLES for FOR LOOP
lst=[4,"raja",9.5] #List
for i in lst:
print(i)
OUTPUT
raja
9.5
s={3,7,19,12} #Set
for i in s:
print(i)
OUTPUT
19
12
t=(3,7,19,12) #Tuple
for i in t:
print(i)
OUTPUT
7
19
12
di={"rollno":101,"name":"DEV","mark":100} #Dictionary
for i in di:
print(i)
OUTPUT
rollno
name
mark
di={"rollno":101,"name":"DEV","mark":100} #Dictionary
for i in di:
print(di[i])
OUTPUT
101
DEV
100
FOR LOOP WITH RANGE( ) FUNCTION
Function range()
We can also use a range() function in for loop to iterate over numbers
defined by range().
range(n): generates a set of whole numbers starting from 0 to (n-1).
For example:
range(8) is equivalent to [0, 1, 2, 3, 4, 5, 6, 7]
range(start, stop): generates a set of whole numbers starting
from start to stop-1.
For example:
range(5, 9) is equivalent to [5, 6, 7, 8]
range(start, stop, step_size): The default step_size is 1 which is why
when we didn’t specify the step_size, the numbers generated are having
difference of 1. However by specifying step_size we can generate
numbers having the difference of step_size.
For example:
range(1, 10, 2) is equivalent to [1, 3, 5, 7, 9]
Lets use the range() function in for loop:
Example 1 : Print the Number from 1 to 10
for i in range(1,11):
print(i)
Example 2 : Print the Number from 10, 15, 20 … 100
for i in range(10,101,5):
print(i)
Example 3 : Print the Number from 100, 95, 90 … 5
for i in range(100,4,-5):
print(i)
Example 4 : Sum of First 20 Natural Numbers
sum=0
for i in range(1,21):
sum+=i
print("Sum is:",sum)
OUTPUT : Sum is: 210
Example 5 : Write a program to implement Multiplication Table
num = int(input("Enter a number : "))
for i in range(1,13):
print("{} x {} = {}".format(num,i,num*i))
break Statement
The break statement is used for premature termination of the current
loop. After abandoning the loop, execution at the next statement is
resumed, just like the traditional break statement in C.
for i in range(10):
if i==5:
break
print(i)
print("For Loop ends")
OUTPUT
0
For Loop ends
continue Statement
The continue statement continues with the next iteration of the
loop:
for i in range(10):
if i==5:
continue
print(i)
print("For Loop ends")
4
6
For Loop ends
FOR Loop with else
for loops also have an else clause which most of us are unfamiliar with.
The else clause executes after the loop completes normally. This means
that the loop did not encounter a break statement.
for i in range(10):
print(i)
else:
print("For loop ends normally")
OUTPUT
3
4
For loop ends normally
for i in range(10):
if i==5:
break
print(i)
else:
print("For loop ends normally")
OUTPUT
of a list one by one
num=[23,55,66,22,43]
i=0
while(i<len(num)):
print(num[i])
i+=1
OUTPUT
23
55
66
22
43