Unit-1 Python Programming
Unit-1 Python Programming
What is Python
Python is a general purpose, dynamic, high-level, and interpreted programming language.
It supports Object Oriented programming approach to develop applications. It is simple and
easy to learn and provides lots of high-level data structures.
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 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 Features
Python provides many useful features which make it popular and valuable from the other
programming languages. It supports object-oriented programming, procedural
programming approaches and provides dynamic memory allocation. We have listed below a
few essential features.
3) Interpreted Language
Python is an interpreted language; it means the Python program is executed one line at a
time. The advantage of being interpreted language, it makes debugging easy and portable.
4) 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. It enables programmers
to develop the software for several competing platforms by writing a program only once.
6) Object-Oriented Language
Python supports object-oriented language and concepts of classes and objects come into
existence. It supports inheritance, polymorphism, and encapsulation, etc. The object-
oriented procedure helps to programmer to write reusable code and develop applications in
less code.
7) 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. It converts the program into byte code, and any
platform can use that byte code.
11. Embeddable
The code of the other programming language can use in the Python source code. We can
use Python source code in another programming language as well. It can embed other
language into our code.
Python History
o Python laid its foundation in the late 1980s.
o The implementation of Python was started in December 1989 by Guido Van
Rossum at CWI in Netherland.
o In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to
alt.sources.
o In 1994, Python 1.0 was released with new features like lambda, map, filter, and
reduce.
o Python 2.0 added new features such as list comprehensions, garbage collection
systems.
o On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed
to rectify the fundamental flaw of the language.
o ABC programming language is said to be the predecessor of Python language, which
was capable of Exception Handling and interfacing with the Amoeba Operating
System.
o The following programming languages influence Python:
o ABC language.
o Modula-3
Python Identifiers
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.
Identifier Naming
Variables are the example of identifiers. An Identifier is used to identify the literals used in
the program. The rules to name an identifier are given below.
Python keywords
The following list shows the Python keywords. These are reserved words and you cannot
use them as constant or variable or any other identifier names. All the Python keywords
contain lowercase letters only.
and exec not
assert finally or
def if return
elif in while
else is with
Python Variables
Variable is a name that is used to refer to memory location. Python variable is also known
as an identifier and used to hold value.
In Python, we don't need to specify the type of variable because Python is a infer language
and smart enough to get variable type.
Variable names can be a group of both the letters and digits, but they have to begin with a
letter or an underscore.
It is recommended to use lowercase letters for the variable name. Rahul and rahul both are
two different variables.
Declaring Variable and Assigning Values
Python does not bind us to declare a variable before using it in the application. It allows us
to create a variable at the required time.
We don't need to declare explicitly variable in Python. When we assign any value to the
variable, that variable is declared automatically.
Object References
It is necessary to understand how the Python interpreter works when we declare a variable.
The process of treating variables is somewhat different from many other programming
languages.
Python is the highly object-oriented programming language; that's why every data item
belongs to a specific type of class. Consider the following example.
print("John")
Output:
John
The Python object creates an integer object and displays it to the console. In the above
print statement, we have created a string object. Let's check the type of it using the Python
built-in type() function.
type("John")
Output:
<class 'str'>
In Python, variables are a symbolic name that is a reference or pointer to an object. The
variables are used to denote objects by that name.
a = 50
a = 50
b=a
The variable b refers to the same object that a points to because Python does not create
another object.
Let's assign the new value to b. Now both variables will refer to the different objects.
a = 50
b =100
Python manages memory efficiently if we assign the same variable to two different values.
Object Identity
In Python, every created object identifies uniquely in Python. Python provides the
guaranteed that no two objects will have the same identifier. The built-in id() function, is
used to identify the object identifier. Consider the following example.
a = 50
b=a
print(id(a))
print(id(b))
# Reassigned variable a
a = 500
print(id(a))
Output:
140734982691168
140734982691168
2822056960944
We assigned the b = a, a and b both point to the same object. When we checked by
the id() function it returned the same number. We reassign a to 500; then it referred to the
new object identifier.
Variable Names
We have already discussed how to declare the valid variable. Variable names can be any
length can have uppercase, lowercase (A to Z, a to z), the digit (0-9), and underscore
character(_). Consider the following example of valid variables names.
name = "Devansh"
age = 20
marks = 80.50
print(name)
print(age)
print(marks)
Output:
Devansh
20
80.5
Multiple Assignment
Python allows us to assign a value to multiple variables in a single statement, which is also
known as multiple assignments.
We can apply multiple assignments in two ways, either by assigning a single value to
multiple variables or assigning multiple values to multiple variables. Consider the following
example.
Eg:
x=y=z=50
print(x)
print(y)
print(z)
Output:
50
50
50
Eg:
a,b,c=5,10,15
print a
print b
print c
Output:
5
10
15
a=5
The variable a holds integer value five and we did not define its type. Python interpreter will
automatically interpret variables a as an integer 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.
Consider the following example to define the values of different data types and checking its
type.
a=10
b="Hi Python"
c = 10.5
print(type(a))
print(type(b))
print(type(c))
Output:
<type 'int'>
<type 'str'>
<type 'float'>
Python provides various standard data types that define the storage method on each of
them. The data types defined in Python are given below.
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
Numbers
Number stores numeric values. The integer, float, and complex values belong to a Python
Numbers data-type. Python provides the type() function to know the data-type of the
variable. Similarly, the isinstance() function is used to check an object belongs to a
particular class.
Python creates Number objects when a number is assigned to a variable. For example;
a=5
print("The type of a", type(a))
b = 40.5
print("The type of b", type(b))
c = 1+3j
print("The type of c", type(c))
print(" c is a complex number", isinstance(1+3j,complex))
Output:
The type of a <class 'int'>
The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True
Python supports three types of numeric data.
1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc.
Python has no restriction on the length of an integer. Its value belongs to int
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is
accurate upto 15 decimal points.
3. complex - A complex number contains an ordered pair, i.e., x + iy where x and y
denote the real and imaginary parts, respectively. The complex numbers like 2.14j,
2.0 + 2.3j, etc.
Sequence Type
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.
String handling in Python is a straightforward task since Python provides built-in functions
and operators to perform operations in the string.
In the case of string handling, the operator + is used to concatenate two strings as the
operation "hello"+" python" returns "hello python".
Example - 1
Output:
Example - 2
Output:
he
o
hello javatpointhello javatpoint
hello javatpoint how are you
List
Python 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 slicing
print (list1[3:])
# List slicing
print (list1[0:2])
Output:
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 and value of the items of a
tuple.
# Tuple slicing
print (tup[1:])
print (tup[0:1])
Output:
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
The items in the dictionary are separated with the comma (,) and enclosed in the curly
braces {}.
# Printing dictionary
print (d)
print (d.keys())
print (d.values())
Output:
Boolean
Boolean type provides two built-in values, True and False. These values are used to
determine the given statement true or false. It denotes by the class bool. True can be
represented by any non-zero value or 'T' whereas false can be represented by the 0 or 'F'.
Consider the following example.
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
Set
Python Set is the unordered collection of the data type. It is iterable, mutable(can modify
after creation), and has unique elements. In set, the order of the elements is undefined; it
may return the changed sequence of the element. The set is created by using a built-in
function set(), or a sequence of elements is passed in the curly braces and separated by
the comma. It can contain various types of values. Consider the following example.
set2.add(10)
print(set2)
Output:
python data types are divided in two categories, mutable data types and
immutable data types.
Python Operators
The operator can be defined as a symbol which is responsible for a particular operation
between two operands. Operators are the pillars of a program on which the logic is built in a
specific programming language. Python provides a variety of operators, which are described
as follows.
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations between two operands. It
includes + (addition), - (subtraction), *(multiplication), /(divide), %(reminder), //(floor
division), and exponent (**) operators.
Operator Description
- (Subtraction) It is used to subtract the second operand from the first operand. If
the first operand is less than the second operand, the value results
negative. For example, if a = 20, b = 10 => a - b = 10
/ (divide) It returns the quotient after dividing the first operand by the second
operand. For example, if a = 20, b = 10 => a/b = 2.0
% (reminder) It returns the reminder after dividing the first operand by the second
operand. For example, if a = 20, b = 10 => a%b = 0
// (Floor It gives the floor value of the quotient produced by dividing the two
division) operands.
Comparison operator
Comparison operators are used to comparing the value of the two operands and returns
Boolean true or false accordingly. The comparison operators are described in the following
table.
Operator Description
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal, then the condition becomes true.
<= If the first operand is less than or equal to the second operand, then the condition
becomes true.
>= If the first operand is greater than or equal to the second operand, then the
condition becomes true.
> If the first operand is greater than the second operand, then the condition becomes
true.
< If the first operand is less than the second operand, then the condition becomes
true.
Assignment Operators
The assignment operators are used to assign the value of the right expression to the left
operand. The assignment operators are described in the following table.
Operator Description
+= It increases the value of the left operand by the value of the right operand and
assigns the modified value back to left operand. For example, if a = 10, b = 20
=> a+ = b will be equal to a = a+ b and therefore, a = 30.
-= It decreases the value of the left operand by the value of the right operand and
assigns the modified value back to left operand. For example, if a = 20, b = 10
=> a- = b will be equal to a = a- b and therefore, a = 10.
*= It multiplies the value of the left operand by the value of the right operand and
assigns the modified value back to then the left operand. For example, if a = 10,
b = 20 => a* = b will be equal to a = a* b and therefore, a = 200.
%= It divides the value of the left operand by the value of the right operand and
assigns the reminder back to the left operand. For example, if a = 20, b = 10 =>
a % = b will be equal to a = a % b and therefore, a = 0.
**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign
4**2 = 16 to a.
//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign
4//3 = 1 to a.
Bitwise Operators
The bitwise operators perform bit by bit operation on the values of the two operands.
Consider the following example.
For example,
if a = 7
b=6
then, binary (a) = 0111
binary (b) = 0011
Operator Description
& (binary If both the bits at the same place in two operands are 1, then 1 is
and) copied to the result. Otherwise, 0 is copied.
| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the
resulting bit will be 1.
^ (binary The resulting bit will be 1 if both the bits are different; otherwise, the
xor) resulting bit will be 0.
~ (negation) It calculates the negation of each bit of the operand, i.e., if the bit is
0, the resulting bit will be 1 and vice versa.
<< (left The left operand value is moved left by the number of bits present in
shift) the right operand.
>> (right The left operand is moved right by the number of bits present in the
shift) right operand.
Logical Operators
The logical operators are used primarily in the expression evaluation to make a decision.
Python supports the following logical operators.
Operator Description
and If both the expression are true, then the condition will be true. If a and b are
the two expressions, a → true, b → true => a and b → true.
or If one of the expressions is true, then the condition will be true. If a and b are
the two expressions, a → true, b → false => a or b → true.
not If an expression a is true, then not (a) will be false and vice versa.
Membership Operators
Python membership operators are used to check the membership of value inside a Python
data structure. If the value is present in the data structure, then the resulting value is true
otherwise it returns false.
Operator Description
not in It is evaluated to be true if the first operand is not found in the second operand
(list, tuple, or dictionary).
Identity Operators
The identity operators are used to decide whether an element certain class or type.
Operator Description
Output
a = 5
print('The value of a is', a)
Output
The value of a is 5
In the second print() statement, we can notice that space was added
between the string and the value of variable a
Python Input
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])
Here, we can see that the entered value 10 is a string, not a number. To
convert this into a number we can use int() or float() functions.
>>> int('10')
10
>>> float('10')
10.0
Statement Description
If Statement The if statement is used to test a specific condition. If the condition is
true, a block of code (if-block) will be executed.
If - else The if-else statement is similar to if statement except the fact that, it also
Statement provides the block of the code for the false case of the condition to be
checked. If the condition provided in the if statement is false, then the
else statement will be executed.
Indentation in Python
For the ease of programming and to achieve simplicity, python doesn't allow the use of
parentheses for the block level code. In Python, indentation is used to declare a block. If
two statements are at the same indentation level, then they are the part of the same block.
Generally, four spaces are given to indent the statements which are a typical amount of
indentation in python.
Indentation is the most used part of the python language since it declares the block of code.
All the statements of one block are intended at the same level indentation. We will see how
the actual indentation takes place in decision making and other stuff in python.
The if statement
The if statement is used to test a particular condition and if the condition is true, it executes
a block of code known as if-block. The condition of if statement can be any valid logical
expression which can be either evaluated to true or false.
The syntax of the if-statement is given below.
if expression:
statement
Example 1
num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even")
Output:
Output:
Enter a? 100
Enter b? 120
Enter c? 130
c is largest
If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.
if condition:
#block of statements
else:
#another block of statements (else-block)
Output:
The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an
if statement.
if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
Example 1
number = int(input("Enter the number?"))
if number==10:
print("number is equals to 10")
elif number==50:
print("number is equal to 50");
elif number==100:
print("number is equal to 100");
else:
print("number is not equal to 10, 50 or 100");
Output:
Python Loops
The flow of the programs written in any programming language is sequential by default.
Sometimes we may need to alter the flow of the program. The execution of a specific code
may need to be repeated several numbers of times.
For this purpose, The programming languages provide various types of loops which are
capable of repeating some specific code several numbers of times. Consider the following
diagram to understand the working of a loop statement.
Why we use loops in python?
The looping simplifies the complex problems into the easy ones. It enables us to alter the
flow of the program so that instead of writing the same code again and again, we can
repeat the same code for a finite number of times. For example, if we need to print the first
10 natural numbers then, instead of using the print statement 10 times, we can print inside
a loop which runs up to 10 iterations.
Advantages of loops
There are the following advantages of loops in Python.
for loop The for loop is used in the case where we need to execute some part of the
code until the given condition is satisfied. The for loop is also called as a per-
tested loop. It is better to use for loop if the number of iteration is known in
advance.
while loop The while loop is to be used in the scenario where we don't know the number
of iterations in advance. The block of statements is executed in the while loop
until the condition specified in the while loop is satisfied. It is also called a pre-
tested loop.
do-while The do-while loop continues until a given condition satisfies. It is also called
loop post tested loop. It is used when it is necessary to execute the loop at least
once (mostly menu driven programs).
str = "Python"
for i in str:
print(i)
Output:
P
y
t
h
o
n
list = [1,2,3,4,5,6,7,8,9,10]
n=5
for i in list:
c = n*i
print(c)
Output:
5
10
15
20
25
30
35
40
45
50s
The range() function is used to generate the sequence of the numbers. If we pass the
range(10), it will generate the numbers from 0 to 9. The syntax of the range() function is
given below.
Syntax:
range(start,stop,step size)
o The start represents the beginning of the iteration.
o The stop represents that the loop will iterate till stop-1. The range(1,5) will
generate numbers 1 to 4 iterations. It is optional.
o The step size is used to skip the specific numbers from the iteration. It is optional to
use. By default, the step size is 1. It is optional.
Output:
0 1 2 3 4 5 6 7 8 9
Example 1
for i in range(0,5):
print(i)
else:
print("for loop completely exhausted, since there is no break.")
Output:
0
1
2
3
4
for loop completely exhausted, since there is no break.
Example 2
for i in range(0,5):
print(i)
break;
else:print("for loop is exhausted");
print("The loop is broken due to break statement...came out of the loop")
In the above example, the loop is broken due to the break statement; therefore, the else
statement will not be executed. The statement present immediate next to else block will be
executed.
Output:
0
The loop is broken due to the break statement...came out of the loop. We will learn more
about the break statement in next tutorial.
It can be viewed as a repeating if statement. When we don't know the number of iterations
then the while loop is most effective to use.
while expression:
statements
Here, the statements can be a single statement or a group of statements. The expression
should be any valid Python expression resulting in true or false. The true is any non-zero
value and false is 0.
Output:
1
2
3
4
5
6
7
8
9
10
Example 1
while (1):
print("Hi! we are inside the infinite while loop")
Output:
Example 1
i=1
while(i<=5):
print(i)
i=i+1
else:
print("The while loop exhausted")
Example 2
i=1
while(i<=5):
print(i)
i=i+1
if(i==3):
break
else:
print("The while loop exhausted")
Output:
1
2
In the above code, when the break statement encountered, then while loop stopped its
execution and skipped the else statement.
Python break statement
The break is a keyword in python which is used to bring the program control out of the loop.
The break statement breaks the loops one by one, i.e., in the case of nested loops, it breaks
the inner loop first and then proceeds to outer loops. In other words, we can say that break
is used to abort the current execution of the program and the control goes to the next line
after the loop.
The break is commonly used in the cases where we need to break the loop for a given
condition.
#loop statements
break;
Example 1
list =[1,2,3,4]
count = 1;
for i in list:
if i == 4:
print("item matched")
count = count + 1;
break
print("found at",count,"location");
Output:
item matched
found at 2 location
Example 2
str = "python"
for i in str:
if i == 'o':
break
print(i);
Output:
p
y
t
h
Syntax
#loop statements
continue
#the code to be skipped
Consider the following examples.
Example 1
i=0
while(i < 10):
i = i+1
if(i == 5):
continue
print(i)
Output:
1
2
3
4
6
7
8
9
10
Observe the output of above code, the value 5 is skipped because we have provided the if
condition using with continue statement in while loop. When it matched with the given
condition then control transferred to the beginning of the while loop and it skipped the value
5 from the code.
Pass Statement
The pass statement is a null operation since nothing happens when it is executed. It is used
in the cases where a statement is syntactically needed but we don't want to use any
executable statement at its place.
For example, it can be used while overriding a parent class method in the subclass but don't
want to give its specific implementation in the subclass.
Pass is also used where the code will be written somewhere but not yet written in the
program file. Consider the following example.
Example
list = [1,2,3,4,5]
flag = 0
for i in list:
print("Current element:",i,end=" ");
if i==3:
pass
print("\nWe are inside pass block\n");
flag = 1
if flag==1:
print("\nCame out of pass\n");
flag=0
Output: