Python UNIT1 Notes
Python UNIT1 Notes
UNIT I
Introduction to Python
Introduction
Python:
print("Hello World")
Eg2: To print the sum of 2 numbers
Python:
1) a=10
2) b=20
3) print("The Sum:",(a+b))
We can use everywhere. The most common important application areas are
1. For developing Desktop Applications
2. For developing web Applications
3. For developing database Applications
4. For Network Programming
5. For developing games
6. For Data Analysis Applications
7. For Machine Learning
8. For developing Artificial Intelligence Applications
9. For IOT
Features of Python:
Simple and easy to learn: Python is a simple programming language. When we read Python
program,we can feel likereading english statements. The syntaxes are very simple and only 30+
kerywords are available. When compared with other languages, we can write programs with very less
number of lines. Hence more readability and simplicity. We can reduce development and cost of the
project.
Freeware and Open Source: We can use Python software without any licence and it is freeware.
Its source code is open,so that we can we can customize based on our requirement. Eg: Jython is
customized version of Python to work with Java Applications.
Platform Independent:
Once we write a Python program, it can run on any platform without rewriting once again. Internally
PVM is responsible to convert into machine understandable form.
Portability:
Python programs are portable. ie we can migrate from one platform to another platform very easily.
Python programs will provide same results on any platform.
Dynamically Typed:
In Python we are not required to declare type for variables. Whenever we are assigning the
value, based on value, type will be allocated automatically. Hence Python is considered
as dynamically typed language. But Java, C etc are Statically Typed Languages b'z we have to
provide type at the beginning only. This dynamic typing nature will provide more flexibility to the
programmer.
Interpreted:
We are not required to compile Python programs explicitly. Internally Python interpreter
will take care that compilation. If compilation fails interpreter raised syntax errors. Once compilation
success then PVM (Python Virtual Machine) is responsible to execute.
Keywords
Reserve word of the compiler/interpreter which can’t be used as identifier.
Identifier
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.
Literals
Literals in Python can be defined as number, text, or other data that represent values to be stored in variables.
Example of String Literals in Python
name = ‘Johni’, fname =“johny”
Example of Integer Literals in Python(numeric literal)
age = 22
Example of Float Literals in Python(numeric literal)
height = 6.2
Example of Special Literals in Python
ame = None
John
The Python object creates an integer object and displays it to the console. In the above printstatement, we have created
Jain College of BBA BCA & Commerce, Belagavi Page 3
Python First Chapter Notes-
a string object. Let's check the type of it using the Python built-in type() function.
1. type("John")
Output:
<class 'str'>
1. Assigning single value to multiple variables
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.
1. x=y=z=50
1. print(x)
2. print(y)
3. print(z)
Output:
50
50
50
2. Assigning multiple values to multiple variables:
1. a,b,c=5,10,15
2. print a
3. print b
4. print c
Output:
5
10
15
Python Data Types: The variable in Python is used to store values, and they can hold different values. Each
variable in Python has its own data-type. Since Python is a dynamically typed language (The language in which
we don't need to pre-define the data-type of the variables), Hence we don't need to define the data-type of the
variables which we are declaring in our Python program.
Python interpreter implicitly binds the value which variable stores with its data type automatically.
p=1
Here the variable p holds value 1, which is an integer data-type in Python. We did not define the data-type of the
p variable while declaring it. The Python interpreter will automatically interpret the data-type of variable p as of
integer type at the time we declared it and allocate memory to it inside Python.
The type() function
Python also enables us to check the data-type of the variables through which we can know which data-type value
the variable is holding in the program. We need to use the type() function inside Python to check the data-type of
the variable. When we run the type() function, it will return us the data-type of the variable we wrote inside the
function.
Jain College of BBA BCA & Commerce, Belagavi Page 4
Python First Chapter Notes-
x=5
y = 2.3
print(type(x))
print(type(y))
print(type(z))
Output:
<class 'int'>
<class 'float'>
<class 'str'>
Explanation:
In the above code, we have defined multiple variables that are storing values with different data-types. After that,
we have used the type() function to find the data-type of the variables inside the program.
Hence, we can see that the Python interpreter has automatically defined the data-type of the variables according
to the data-type of values they are storing and allocated memory to them.
In this section of this Python tutorial, we will discuss in detail each data-type present in Python. We will also
discuss how they are defined and how the Python interpreter will allocate memory to the variables with these
data-types.
Before proceeding to the standard types of data-type in Python,
We should note that we can change the variable's data-type by replacing the value it is holding with a
different data-type value.
And, the Python interpreter will dynamically allocate memory to it.
Numerical Data-type
The numerical data-type in Python represents the variables that are holding numbers. The int(integer), float and
complex number data-types belong to numerical data-type in Python. In Python, number objects are created
inside Python's memory when we assign number values to a variable.
In Python, we have a type() function through which we can check the data-type of any variable. The
type() function will give the class of the variable in output.
Int (Integer)
Float
Complex Number
It is to be noted that Python does not support any special numeric data-type such as long int or double etc.
Integer data-type: Variables with int data-type inside Python holds integer number objects. These
integer number objects can be 10, 200, -30, -700 etc. In Python, there is no restriction for the length of an
integer number. A variable with an integer data-type can hold a maximum value integer number. The
value of integer number belongs to int.
Jain College of BBA BCA & Commerce, Belagavi Page 6
Python First Chapter Notes-
Example:
#define variables and assign integer numbers to them.
i = 27
j = -72
k = 1010101010101010
print(i)
print(j)
print(k)
-72
1010101010101010
Float data-type: In Python, the variables having float data-type represent that they are holding floating-
point numbers objects such as 1.9, 2.34, 3.14 etc. The decimal limit of float data-type is up to 15 decimal
points in Python. It means float data-type variables have accurate and precise object values up to 15
decimal points. Variables with both positive and negative numbers can have float data-type in Python.
Example:
#define variables and assign floating numbers to them.
i = 3.14
j = -2.34
k = 0.3010
print(i)
print(j)
print(k)
-2.34
0.3010
Complex number data-type: A complex number has two parts, i.e., real and imaginary, and has the
structure same as a+ib. Here, 'a' represents the real part of the complex number, and 'ib' represents the real
part of the complex number. The variables which hold complex numbers have complex data-type in
Python. Example: 2+3i, 2.3+1.2i, 0.23i etc.
2. Sequence Data-type:
In Python, the sequence data-type is an ordered or paired collection of similar or different data values. The
sequence data-type allows us to store multiple object values in an efficient and organized manner.
Variables with sequence data-type in Python are used to store values with characters, alphabets, words,
lists etc.
Like numeric data-type, sequence data-type also has three further data-types.
String
List
Tuple
quotation marks. A variable storing a string object value is considered a string data-type. In Python, we can
define string object value using single, double or triple quotation marks.
We can also define a multiline string using triple quotes at the beginning of the string and end our string in the
next line by closing it with triple quotation marks.
Let's understand this string data-type through an example.
Example:
mkr = "A string object inside double quotation marks"
print(mkr)
string'''
print(str)
Output:
A string object inside double quotation marks
This is a multiline
string
Explanation:
In the above code, we have defined a string mkr inside the double quotation mark. Then we defined multiline
string str using five quotation marks and closed the string in the next line.
String Handling in Python:
Handling a string inside Python is a straightforward task since Python provides us with many built-in
functions.
Python also provides us many operators for performing various operations on the string.
In a string handling case, the '+' character (string addition operator) is used to concatenate(add) two string
values. As in this operation, "Hi" + "Python Developers" will return "Hi Python Developers" as a single
string to us.
The '*' character (string multiple operators) is also known as the repetition operator for strings. As in this
operator, "Hello"*2 will return 'HelloHello' in the output.
print (mkr1*2)
Output:
Hello Python DevelopersHello Python Developers
List Data-type
Lists in Python are similar to arrays present in C, C++, or other programming languages. But unlike arrays, lists
in Python can store object values of different data-types.
The items or objects stored in the list are enclosed by the square brackets [] and items are separated by comma
(,).
Let’s understand the following example.
Example:
#Define a list
print(type(list1))
print (list1)
Output:
<class 'list'>
Similar to string handling, we can also handle and operate our list straightforwardly.
Python provides us many built-in functions, the same as for strings to perform operations in the list we
have defined in our code.
The operators for list data-type are the same as for string data-type, i.e., slice operator [:], concatenate
operator (+) and multiple operators (*).
print (list1[3:])
print (list1[0:2])
print (list1 * 3)
Output:
[2]
[1, 'Hello']
Tuple
Tuple data-type in Python is used to hold multiple object values in a single variable. Tuple data-type is one of the
built-in data-type in Python that is used for storing multiple object values inside a single variable. The other is
dictionary, list and set.
print (type(sup))
print (sup)
Output:
<class 'tuple'>
print (sup[1:])
print (sup[0:1])
print (sup * 3)
Output:
('Python', 1)
('Hello')
We even can't modify the values that are present inside a defined tuple.
This property makes a tuple a very rigid variable in Python.
Let's see an example to understand the read-only property of the tuple data structure.
Example:
#define a tuple with mup name mup = (1, "Hello", "Python", "Developers", 2) # Checking class type of mup
tuple we have defined print (type(tup)) #Let’s try to modify one of the object values presents in mup tuple and
Python will throw an error while performing this modification operation t[2] = "hi"
Output:
<class 'tuple'>
t[2] = "hi";
Dictionary Data-type:
The dictionary data-type in Python is a set of key-value pairs of items in an unordered manner. Dictionary in
Python is very similar to the associative array where each key stores a unique value. Keys in a dictionary can
only hold primitive data-types, whereas the object values are arbitrary objects in Python.
print (dict)
print (dict.keys())
print (dict.values())
Output:
{1: 'Jim', 2: 'Carry', 3: 'Jonas', 4: 'Mike'}
dict_keys([1, 2, 3, 4])
Defining a set in Python: In Python, we can define the set using the following two methods:
a). We can create a set variable in our Python program using Python's built-in set () function.
b). We can pass sequence of elements inside the curly braces {} and separate the values by comma {,}.
Example:
# Creating a set(set01) using built-in set() function in Python
Set01 = set()
print(type(set01))
print(type(set02))
print(set02)
Output:
<class 'set'>
<class 'set'>
{'Python', 'James', 3, 2, 1}
{'Python', 'James', 2, 1}
Boolean data-type:
Like any other programming language in Python, boolean data-type has two built-in values, i.e., true and false.
Boolean data-type is used for the condition statement codes to check if the statement is true or false.
print(type(False))
print(type(True))
print(true)
Output:
<class 'bool'>
<class 'bool'>
input() Function In Python allows a user to give input to a program from a keyboard but returns the value accordingly.
e.g.
age = int(input(‘enter your age’))
C = age+2 #will not produce any error
NOTE : input() function always enter string value in python 3.so on need int(),float()
function can be used for data conversion.
Python Operators
The operator can be defined as a symbol which is responsible for a particular operation betweentwo 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
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations between two operands. Itincludes + (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 thefirst operand is less
than the second operand, the value results negative. For example, if a = 20, b = 10 => a -
b = 10
% (reminder) It returns the reminder after dividing the first operand by the secondoperand. For
example, if a = 20, b = 10 => a%b = 0
// (Floor It gives the floor value of the quotient produced by dividing the twooperands.
division)
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 thecondition becomes true.
> If the first operand is greater than the second operand, then the conditionbecomes true.
< If the first operand is less than the second operand, then the conditionbecomes 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 andassigns 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, ifa = 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 assign4**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 thefollowing example.
For example,
1. if a = 72.
b=6
3. then, binary (a) = 0111
4. binary (b) = 00115.
6. hence, a & b = 00117. a|
b = 0111
8. a ^ b = 0100
9. ~ a = 1000
Operator Description
& (binary If both the bits at the same place in two operands are 1, then 1 is copied tothe result. Otherwise, 0
and) is copied.
| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the resultingbit 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, theresulting bit will be 1
and vice versa.
<< (left The left operand value is moved left by the number of bits present in theright operand.
shift)
>> (right The left operand is moved right by the number of bits present in the right operand.
shift)
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 twoexpressions, 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 twoexpressions, 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
Operator Description
in It is evaluated to be true if the first operand is found in the second operand (list,tuple, or dictionary).
not in It is evaluated to be true if the first operand is not found in the second operand (list,tuple, or dictionary).
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 Precedence
The precedence of the operators is essential to find out since it enables us to know which operatorshould be evaluated first.
The precedence table of the operators in Python is given below.
Operator Description
** The exponent operator is given priority over all the othersused in the
expression.
<= < > >= Comparison operators (less than, less than equal to, greaterthan, greater then
equal to).
Python Comments
Python Comment is an essential tool for the programmers. Comments are generally used to explain the code. We can
easily understand the code if it has a proper explanation. A good programmer must use the comments because in the
future anyone wants to modify the code aswell as implement the new module; then, it can be done easily.
Here we have written comment over the print statement using the hash(#). It will not affect our print statement.
Example:
Output:
The above code is very readable even the absolute beginners can under that what is happening ineach line of the code. This is
the advantage of using comments in code.
Statement Description
If Statement The if statement is used to test a specific condition. If the condition is true, ablock of code (if-block)
will be executed.
If - else The if-else statement is similar to if statement except the fact that, it also provides the block of the
Statement 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.
Nested if Nested if statements enable us to use if ? else statement inside an outer ifstatement.
Statement
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.
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.
1. if expression:
2. statement
Example 1
1. num = int(input("enter the number?"))2. if num%2
== 0:
3. print("Number is even")
Output:
If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.
1. if condition:
2. #block of statements
3. else:
4. #another block of statements (else-block)
Output:
1. if expression 1:
2. # block of statements3.
4. elif expression 2:
5. # block of statements6.
7. elif expression 3:
8. # block of statements9.
10. else:
11. # block of statements
Example 1
1. number = int(input("Enter the number?"))
2. if number==10:
3. print("number is equals to 10")
4. elif number==50:
5. print("number is equal to 50");
6. elif number==100:
7. print("number is equal to 100");
8. else:
Output:
Advantages of loops
There are the following advantages of loops in Python.
Loop Description
Statement
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 numberof iterations in
advance. The block of statements is executed in the while loopuntil the condition specified in the
while loop is satisfied. It is also called a pre-tested loop.
1. str = "Python"
2. for i in str:
3. print(i)
Output:
P
y
t
h
o
n
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:
1. 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 generatenumbers 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.
1. for i in range(10):
2. print(i,end = ' ')
Output:
0 1 2 3 4 5 6 7 8 9
Output:
Syntax
1. for iterating_var1 in sequence: #outer loop
2. for iterating_var2 in sequence: #inner loop
3. #block of statements
4. #Other statements
Output:
1. for i in range(0,5):
2. print(i)
3. break;
4. else:print("for loop is exhausted");
5. 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 beexecuted.
Output:
The loop is broken due to the break statement...came out of the loop. We will learn more aboutthe 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.
1. while expression:
2. 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 falseis 0.
Output:
1
2
3
4
5
6
7
8
9
10
Any non-zero value in the while loop indicates an always-true condition, whereas zero indicatesthe always-false
condition. This type of approach is useful if we want our program to run continuously in the loop without any disturbance.
Example 1
1. while (1):
2. print("Hi! we are inside the infinite while loop")
Output:
The break is commonly used in the cases where we need to break the loop for a given condition.The syntax of the break is given below.
1. str = "python"
2. for i in str:
3. if i == 'o':
4. break
5. print(i);
Output:
p
y
t
h
Syntax
1. #loop statements
2. continue
3. #the code to be skipped
Example 1
1. i = 0
2. while(i < 10):3.
i = i+1
4. if(i == 5):
5. continue
6. print(i)
Output:
1
2
3
4
6
7
8
9
10
Example: In the provided code, when i is equal to 5, it prints “exit” and attempts to exit the Python interpreter
using the exit() function. If i is not equal to 5, it prints the value of i.
for i in range(10):
if i == 5:
print(exit)
exit()
print(i)
Python Library
Q: What is a library
Ans: A library is a collection of modules that is used to create specific type of need or application Some
commonly used libraries are as below
Python standard library : This library comes in-built with python distribution. Some commonly used modules of
python standard library are
math module: Provides mathematical functions to support different type of
cmath module: Provides mathematical functions related to complex numbers
Random module: Provides functions for generating random numbers •
Statistics module: Provides mathematical statistical functions