0% found this document useful (0 votes)
15 views30 pages

Python UNIT1 Notes

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
15 views30 pages

Python UNIT1 Notes

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 30

Python First Chapter Notes-

UNIT I

Introduction to Python
Introduction

1. Python is a general purpose high level programming language.


2. Python was developed by Guido Van Rossam in 1989 while working at National
3. Research Institute at Netherlands.
4. But officially Python was made available to public in 1991. The official Date of Birth for
5. Python is : Feb 20th 1991.
6. Python is recommended as first programming language for beginners.

Eg1: To print Hello world:

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))

The name Python was selected from the TV Show


"The Complete Monty Python's Circus"
which was broadcasted in BBC from 1969 to 1974.
Guido developed Python language by taking almost all programming features from different
languages
1. Functional Programming Features from C
2. Object Oriented Programming Features from C++
3. Scripting Language Features from Perl and Shell Script
4. Modular Programming Features from Modula-3

Where we can use Python: Applications of python

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

Jain College of BBA BCA & Commerce, Belagavi Page 1


Python First Chapter Notes-

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.

High Level Programming language:


Python is high level programming language and hence it is programmer friendly language.
Being a programmer we are not required to concentrate low level activities like memory
management and security etc..

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.

Both Procedure Oriented and Object Oriented:


Python language supports both Procedure oriented (like C, Pascal etc) and object oriented
(like C++,Java) features. Hence we can get benefits of both like security and reusability etc

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.

Basic Elements of Python


Python Variables
1. 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.
2. 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.
3. Variable names can be a group of both the letters and digits, but they have to begin with a
letter or an underscore.
4. It is recommended to use lowercase letters for the variable name. Rahul and rahul both are
two different variables.

Jain College of BBA BCA & Commerce, Belagavi Page 2


Python First Chapter Notes-

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.

o The first character of the variable must be an alphabet or underscore ( _ ).


o All the characters except the first character may be an alphabet of lower-case(a-z), upper-case (A-Z), underscore,
or digit (0-9).
o Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &,
*).
o Identifier name must not be similar to any keyword defined in the language.
o Identifier names are case sensitive; for example, my name, and MyName is not the same.
o Examples of valid identifiers: a123, _n, n_9, etc.
o Examples of invalid identifiers: 1a, n%4, n 9, etc.

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

Declaring Variable and Assigning Values


Python does not bind us to declare a variable before using it in the application. It allows us tocreate 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.

The equal (=) operator is used to assign value to a variable.


Python is the highly object-oriented programming language; that's why every data item belongs toa specific type of class.
Consider the following example.
1. print("John")
Output:

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

The values will be assigned in the order in which variables appear.

Python Data Types

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-

Let's understand the working of type() function in Python with an example.


Example: Consider the following code written in Python:
#define variables with different data-type values

x=5

y = 2.3

z = 'Hello Python Developers'

#check the data-type of these variables

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.

Standard Data-types in Python


A variable inside Python can hold values of different data-types. For example, the name of a person is stored as
string type, whereas the age of the person is stored as an integer data-type in Python.
Python provides us various standard data-types that we can see in many different programming languages. Data-
type of the variables in Python defines the storage method of them in the memory. It is also to note that Python
does not provide us any special type of data-type for variables such as long int etc.
Following are the names of the data-types that are defined inside Python:
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary

Jain College of BBA BCA & Commerce, Belagavi Page 5


Python First Chapter Notes-

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.

Python supports the following three types of numeric data-type:

 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 variables i, j and k

print(i)

print(j)

print(k)

#Let’s check the data-type of variable i, j and k

print("The type of i",type(i))

print("The type of j",type(j))

print("The type of k",type(k))


Output:
27

-72

1010101010101010

The type of i <class 'int'>

The type of j <class 'int'>

The type of k <class 'int'>

 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 variables i, j and k


Jain College of BBA BCA & Commerce, Belagavi Page 7
Python First Chapter Notes-

print(i)

print(j)

print(k)

#Let’s check the data-type of variable i, j and k

print("The type of i",type(i))

print("The type of j",type(j))

print("The type of k",type(k))


Output:
3.14

-2.34

0.3010

The type of i <class 'float'>

The type of j <class 'float'>

The type of k <class 'float'>

 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.

Following are the three types of sequence data-type present in Python:

 String
 List
 Tuple

Let's discuss each of these three data-types in detail.


String
A string in Python can be defined as a sequence of characters (including white spaces) represented inside the

Jain College of BBA BCA & Commerce, Belagavi Page 8


Python First Chapter Notes-

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)

str = '''This is a multiline

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.

Example: look at the following code for string handling example:


mkr1 = 'Hello Python Developers'

#defining string first with mkr1 name

mkr2 = ' How are you all'

#printing the string twice using multiple operator.

print (mkr1*2)

#printing the addition of str1 and str2 using concatenation operator

print (mkr1 + mkr2)

Jain College of BBA BCA & Commerce, Belagavi Page 9


Python First Chapter Notes-

Output:
Hello Python DevelopersHello Python Developers

Hello Python Developers How are you all

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

list1 = [1, "Hello", "Python", 24]

#Checking the type of list we have defined

print(type(list1))

#Printing the list01

print (list1)
Output:
<class 'list'>

[1, 'Hello', 'Python', 24]


List handling in Python

 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 (*).

Let's look at an example of list handling in Python.


Example:
# Define a list with objects in it

list01 = [1, "Hello", "Python", 2]

#slice the defined list slicing operator

print (list1[3:])

#Again List slicing

print (list1[0:2])

# Add the list to itself using List Concatenation '+' operator


Jain College of BBA BCA & Commerce, Belagavi Page 10
Python First Chapter Notes-

print (list1 + list1)

# Multiple the list using the List repetition '*' operator

print (list1 * 3)
Output:
[2]

[1, 'Hello']

[1, 'Hello', 'Python', 2, 1, 'Hello', 'Python', 2]

[1, 'Hello', 'Python', 2, 1, 'Hello', 'Python', 2, 1, 'Hello', 'Python', 2]

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.

 Items present inside tuple are ordered and unchangeable.


 Tuple data-type allows duplication, i.e., we can store the same value multiple times inside tuple variables.
 To Create a tuple data-type variable with a single value present in it, we need to use comma (,) after the
value; otherwise, Python will consider this variable type as string data-type.

Let's see an example of a tuple to understand it detail.


#define a tuple with parentheses

sup = ("Hello", "Python", 1)

# Check the class type of sup

print (type(sup))

#Print the sup tuple we have defined

print (sup)
Output:
<class 'tuple'>

('Hello', 'Python', '1')


Operations in Tuple

 As in lists or strings, performing operations on tuple is very straightforward in Python.


 Python provides us built-in functions and operators to perform various operations on the tuple.
 We can perform slicing, concatenation and repetition operation on a tuple in Python.

Look at the following code for understanding operations on tuple:


Example

Jain College of BBA BCA & Commerce, Belagavi Page 11


Python First Chapter Notes-

sup = ("Hello", "Python", 1)

#Perform the slice operation on sup tuple

print (sup[1:])

print (sup[0:1])

#Perform the tuple concatenation operation using + operator on sup

print (sup + sup)

# Perform tuple repetition using * operator

print (sup * 3)
Output:
('Python', 1)

('Hello')

('Hello', 'Python', '1' 'Hello', 'Python', '1')

('Hello', 'Python', '1' 'Hello', 'Python', '1' 'Hello', 'Python', '1')


Note: Tuple is read-only data structure: - In Python, tuples are immutable data-type which means we can't
modify the size of the tuple after it has been defined.

 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'>

Traceback (most recent call last):

File "code.py", line 6, in <module>

t[2] = "hi";

TypeError: 'tuple' object does not support item assignment


We can clearly see that tuple is a read-only data structure, and we can perform insertion or modification
operations on tuple after defining it.

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.

Jain College of BBA BCA & Commerce, Belagavi Page 12


Python First Chapter Notes-

 In the dictionary, items are closed inside in the curly braces {}


 In the dictionary, items are separated from each other through a comma ().

Look at the following code for dictionary data-type.


Example:
dict = {1:'Jim', 2:'Carry', 3:'Jonas', 4:'Mike'}

# Printing dictionary dict that we have defined above

print (dict)

# Accesing value of dictionary using keys

print("1st name is "+dict[1])

print("2nd name is "+ dict[2])

print (dict.keys())

print (dict.values())
Output:
{1: 'Jim', 2: 'Carry', 3: 'Jonas', 4: 'Mike'}

1st name is Jim

2nd name is Carry

dict_keys([1, 2, 3, 4])

dict_values(['Jim', 'Carry', 'Jonas', 'Mike'])


.
Set data-type
Set data-type in Python is an unordered collection of data. The variables with set data-type stores values
unorderly and doesn't have key values in them. Since the order of the values is undefined in the set, Python may
return the changed sequence of the elements in the set while printing the set in output.

 Sets are iterable in nature.


 Sets are also mutable, i.e., we can modify elements of the set after creation.
 Set always has unique elements stored in them. It doesn't allow duplicity of elements.
 In Python, a set can contain various types of values with different data-types.

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()

# the set01 is an empty set

Jain College of BBA BCA & Commerce, Belagavi Page 13


Python First Chapter Notes-

# creating a set(set02) by passing sequence elements in curly braces

set02 = {‘Jimmy’, 2, 3,’Python’}

# Check the class type of set01 and set02

print(type(set01))

print(type(set02))

# Printing the values present in set02

print(set02)
Output:
<class 'set'>

<class 'set'>

{3, 'Python', 'Jimmy', 2}

{'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.

 The class bool denotes the boolean data-type.


 True in boolean data-type can be represented by any non-zero value or 'T'.
 False in boolean data-type can be represented by zero value (0) or 'F'.

Example: Look at the following code for boolean type:


# A Python program to check the boolean data-type

print(type(False))

print(type(True))

print(true)
Output:
<class 'bool'>

<class 'bool'>

NameError: name 'true' is not defined


Input and Output function
var1=‘Computer Science'
var2=‘Informatics Practices'
print (var1,' and ',var2 )
Output:-
Jain College of BBA BCA & Commerce, Belagavi Page 14
Python First Chapter Notes-

Computer Science and Informatics Practices

age = int(raw_input(‘enter your age’))


percentage = float(raw_input(‘enter percentage’))

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.

Consider the following table for a detailed explanation of arithmetic operators.

Operator Description

+ (Addition) It is used to add two operands. For example, if a = 20, b = 10 =>a+b = 30

- (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

** (Exponent) It is an exponent operator represented as it calculates the firstoperand power to


the second operand.

Jain College of BBA BCA & Commerce, Belagavi Page 15


Python First Chapter Notes-

// (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 assigns the value of the right expression to the left operand.

+= 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.

Jain College of BBA BCA & Commerce, Belagavi Page 16


Python First Chapter Notes-

-= 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.

Jain College of BBA BCA & Commerce, Belagavi Page 17


Python First Chapter Notes-

^ (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).

Jain College of BBA BCA & Commerce, Belagavi Page 18


Python First Chapter Notes-

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.

~+- The negation, unary plus, and minus.

* / % // The multiplication, divide, modules, reminder, and floordivision.

+- Binary plus, and minus

>> << Left shift. and right shift

& Binary and.

^| Binary xor, and or

<= < > >= Comparison operators (less than, less than equal to, greaterthan, greater then
equal to).

<> == != Equality operators.

= %= /= //= -= += Assignment operators


*= **=

is is not Identity operators

Jain College of BBA BCA & Commerce, Belagavi Page 19


Python First Chapter Notes-

in not in Membership operators

not or and Logical operators

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.

1. # This is the print statement


2. print("Hello Python")

Here we have written comment over the print statement using the hash(#). It will not affect our print statement.

Multiline Python Comment


We must use the hash(#) at the beginning of every line of code to apply the multiline Python comment. Consider the
following example.

1. # First line of the comment


2. # Second line of the comment
3. # Third line of the comment

Example:

1. # Variable a holds value 5

2. # Variable b holds value 10


3. # Variable c holds sum of a and b
4. # Print the result5. a
=5
6. b = 10
7. c = a+b
8. print("The sum is:", c)

Output:

The sum is: 15

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.

Python If-else statements


Decision making is the most important aspect of almost all the programming languages. As the name implies, decision
making allows us to run a particular block of code for a particular decision.Here, the decisions are made on the validity of
the particular conditions. Condition checking is thebackbone of decision making.

In python, decision making is performed by the following statements.

Jain College of BBA BCA & Commerce, Belagavi Page 20


Python First Chapter Notes-

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.

The syntax of the if-statement is given below.

1. if expression:
2. statement

Jain College of BBA BCA & Commerce, Belagavi Page 21


Python First Chapter Notes-

Example 1
1. num = int(input("enter the number?"))2. if num%2
== 0:
3. print("Number is even")

Output:

enter the number?10


Number is even

The if-else statement


The if-else statement provides an else block combined with the if statement which is executed in the false case of the
condition.

If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.

The syntax of the if-else statement is given below.

1. if condition:
2. #block of statements
3. else:
4. #another block of statements (else-block)

Example 1 : Program to check whether a person is eligible to vote ornot.


1. age = int (input("Enter your age? "))
2. if age>=18:
3. print("You are eligible to vote !!");
4. else:
5. print("Sorry! you have to wait !!");

Output:

Jain College of BBA BCA & Commerce, Belagavi Page 22


Python First Chapter Notes-

Enter your age? 90


You are eligible to vote !!

The elif statement


The elif statement enables us to check multiple conditions and execute the specific block of
statements depending upon the true condition among them. We can have any number of elif
statements in our program depending upon our need. However, using elif is optional.
The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if
statement.

The syntax of the elif statement is given below.

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:

Jain College of BBA BCA & Commerce, Belagavi Page 23


Python First Chapter Notes-

9. print("number is not equal to 10, 50 or 100");

Output:

Enter the number?15


number is not equal to 10, 50 or 100

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 10iterations.

Advantages of loops
There are the following advantages of loops in Python.

1. It provides code re-usability.


2. Using loops, we do not need to write the same code again and again.
3. Using loops, we can traverse over the elements of data structures (array or linked lists).

There are the following loop statements 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.

Python for loop


The for loop in Python is used to iterate the statements or a part of the program several times. It is
frequently used to traverse the data structures like list, tuple, or dictionary.

The syntax of for loop in python is given below.

1. for iterating_var in sequence:


2. statement(s)

Jain College of BBA BCA & Commerce, Belagavi Page 24


Python First Chapter Notes-

The for loop flowchart

For loop Using Sequence


Example-1: Iterating string using for loop

1. str = "Python"
2. for i in str:
3. print(i)

Output:

P
y
t
h
o
n

For loop Using range() function


The range() function

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.

Consider the following examples:


Example-1: Program to print numbers in sequence.

Jain College of BBA BCA & Commerce, Belagavi Page 25


Python First Chapter Notes-

1. for i in range(10):
2. print(i,end = ' ')

Output:

0 1 2 3 4 5 6 7 8 9

Example - 2: Program to print table of given number.

1. n = int(input("Enter the number "))


2. for i in range(1,11):
3. c = n*i
4. print(n,"*",i,"=",c)

Output:

Enter the number 10


10 * 1 = 10
10 * 2 = 20
10 * 3 = 30
10 * 4 = 40
10 * 5 = 50
10 * 6 = 60
10 * 7 = 70
10 * 8 = 80
10 * 9 = 90
10 * 10 = 100

Nested for loop in python


Python allows us to nest any number of for loops inside a for loop. The inner loop is executed nnumber of times for
every iteration of the outer loop. The syntax is given below.

Syntax
1. for iterating_var1 in sequence: #outer loop
2. for iterating_var2 in sequence: #inner loop
3. #block of statements
4. #Other statements

Example- 1: Nested for loop


1. # User input for number of rows
2. rows = int(input("Enter the rows:"))
3. # Outer loop will print number of rows
4. for i in range(0,rows+1):
5. # Inner loop will print number of Astrisk
6. for j in range(i):
7. print("*",end = '')
8. print()

Output:

Jain College of BBA BCA & Commerce, Belagavi Page 26


Python First Chapter Notes-

Enter the rows:5


*
**
***
****
*****

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.

Python While loop


The Python while loop allows a part of the code to be executed until the given condition returns false. It is also known as
a pre-tested loop.

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.

The syntax is given below.

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.

While loop Flowchart

Jain College of BBA BCA & Commerce, Belagavi Page 27


Python First Chapter Notes-

Example-1: Program to print 1 to 10 using while loop


1. i=1
2. #The while loop will iterate until condition becomes false.3. While(i<=10):
4. print(i)
5. i=i+1

Output:
1
2
3
4
5
6
7
8
9
10

Infinite while loop


If the condition is given in the while loop never becomes false, then the while loop will never terminate, and it turns
into the infinite while loop.

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:

Hi! we are inside the infinite while loop


Hi! we are inside the infinite while loop

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 abortthe 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.The syntax of the break is given below.

1. str = "python"
2. for i in str:
3. if i == 'o':
4. break

Jain College of BBA BCA & Commerce, Belagavi Page 28


Python First Chapter Notes-

5. print(i);

Output:

p
y
t
h

Python continue Statement


The continue statement in Python is used to bring the program control to the beginning of the loop.
The continue statement skips the remaining lines of code inside the loop and start with the next
iteration. It is mainly used for a particular condition inside the loop so that we can skip somespecific
code for a particular condition.The continue statement in Python is used to bring the program control
to the beginning of the loop. The continue statement skips the remaining lines ofcode inside the loop
and start with the next iteration. It is mainly used for a particular condition inside the loop so that we
can skip some specific code for a particular condition.

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

Python Exit Command using exit() Function


The exit() in Python is defined as exit commands in python if in site.py and it works only if the site module is
imported so it should be used in the interpreter only. It is like a synonym for quit() to make Python more user-
friendly. It too gives a message when printed and terminate a program in Python.

Jain College of BBA BCA & Commerce, Belagavi Page 29


Python First Chapter Notes-

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

1.Urllib module: Provides URL handling function


2. NumPy Library: This Library provides some advance math functionality along with tools to create and
manipulate arrays
3. SciPy Library: This is basically used for scientific calculations
4. Tkinter Library: This is basically used for GUI interface for different types of calculations
5. Matplotlib Library: This is basically used for producing quality output in variety of formats such as plots
charts, graphs, etc

Jain College of BBA BCA & Commerce, Belagavi Page 30

You might also like