Introduction to Python- notes
Introduction to Python- notes
In order to tell the computer “What you want to do”, we write a program in a language which
computer can understand. Though there are many different programming languages such as BASIC,
Pascal, C, C++, Java, Haskell, Ruby, Python, etc. but we will study Python in this course.
Before learning the technicalities of Python, let’s get familiar with it. Python was created by Guido
Van Rossum when he was working at CWI (Centrum Wiskunde & Informatica) which is a National
Research Institute for Mathematics and Computer Science in Netherlands. The language was
released in I991. Python got its name from a BBC comedy series from seventies- “Monty Python’s
Flying Circus”.
Python can be used to follow both Procedural approach and Object-Oriented approach of
programming. It is free to use.
• It is a general-purpose programming language which can be used for both scientific and non-
scientific programming.
• It is a platform independent programming language.
• It is a very simple high-level language with vast library of add-on modules.
• It is excellent for beginners as the language is interpreted, hence gives immediate results.
• The programs written in Python are easily readable and understandable.
• It is suitable as an extension language for customizable applications.
• It is easy to learn and use.
INSTALLATION
To write and run a Python program, we need to have a Python interpreter installed in our computer.
IDLE (GUI integrated) is the standard, most popular Python development environment. IDLE is an
acronym for Integrated Development Environment. It lets edit, run, browse and debug Python
Programs from a single interface. This environment makes it easy to write programs. Python can be
downloaded and installed for free from http://www.python.org/download/ and download the latest
version. We will be using IDLE to run all our programs and exercise.
EXECUTION MODE
INTERACTIVE MODE
To work in the interactive mode, we can simply type a Python statement on the >>> prompt directly.
As soon as we press enter, the interpreter executes the statement and displays the result(s)
1|Page
SCRIPT MODE
In the script mode, we can write a Python program in a file, save it and then use the interpreter to
execute it. Python scripts are saved as files where file name has extension ".py".
To create and run a Python script, we will use the following steps in IDLE, if the script mode is not
made available by default with the IDLE environment.
Keywords are special identifiers with predefined meanings that cannot change. As these words have
specific meaning for interpreter, they cannot be used for any other
purpose.
2|Page
IDENTIFIERS
Identifiers are the names used to identify a variable, function or other entities in a program. The
rules for naming an identifier in Python are as follows:
4. Python is a case sensitive programming language. Thus, Sname and sname are two different
identifiers in Python.
• If • yes&no • Interest1
ASSIGNMENT OPERATOR
In Python we can use an assignment statement to create new variables and assign specific values to
them. You can declare and assign value to a variable with the assignment operator ‘=’
Multiple Assignments:
x = y = z = 100
p, q, r = 10, 20, 30
It will assign the value order wise that is value 10 assign to variable p, value 20 assign to variable q
and value 30 assign to variable r.
DATA TYPES
Python has built-in data types such as numbers, strings, lists etc. Every value in Python has a
datatype. Data types are used to define the type of value a data can contain. Data types define the
way to store the values in memory. Since everything is an object in Python programming, data types
are actually classes and variables are instances (objects) of these classes.
3|Page
There are various data types in Python. Some of the important types are mentioned below in the
image-
Numeric Data
are the data-type which represent the numeric values. It can be any number from the -infinity to
+infinity. There are several numeric data types in Python:
Integer
Integer data types are the one which can hold the integral value of the number.
a=5
Float
b=5.5
Sequences
In Python, sequence is the ordered collection of similar or different data types. Sequences allow you
to store multiple values in an organized and efficient fashion. There are several sequence types in
Python:
String
Lists
List is also a sequence of values of any type. It is used to store values of same and different data
types like integer, string, float etc. Values in the list are called elements / items. These are
indexed/ordered. List is enclosed in square brackets.
OPERATORS
4|Page
Operators are special symbols which represent computation. They are applied on operand(s), which
can be values or variables. Same operators can behave differently on different data types. Operators
when applied on operands form an expression. Operators are categorized as Arithmetic, Relational,
Logical and Assignment. Value and variables when used with operators are known as operands.
ARITHMETIC OPERATORS
+ Addition 10 + 20 30
- Subtraction 30 - 10 20
/ Division 30 / 10 3.0
1/2 0.5
// Integer Division 25 // 10 2
1 // 2 0
% Remainder 25 % 10 5
** Raised to power 3 ** 2 9
In Python, we have the input() function for taking the user input. The input() function prompts the
user to enter data. It accepts all user input as string. The syntax for input() is:
input ([Prompt])
Python uses the print() function to output data to standard output device - the screen.
a = "Hello World!"
print(a)
a = 20 30
b = 10
print(a + b)
5|Page
print(15 + 35) 50
x = 1.3 x=
USER INPUT
In all the examples till now, we have been using the calculations on known values (constants). Now
let us learn to take user’s input in the program. In python, input() function is used for the same
purpose.
Syntax Meaning
TYPE CONVERSION
The process of converting the value of one data type (integer, string, float, etc.) to another data
type is called type conversion. Python has two types of type conversion.
In Implicit type conversion, Python automatically converts one data type to another data type. This
process doesn't need any user involvement.
EXAMPLE:
6|Page
principle_amount = 2000
roi = 4.5
ime = 10
• We calculate the simple interest by using the variable priniciple_amount and roi with time
divide by 100.
• In the output we can see the datatype of principle_amount is an integer, datatype of roi is a
float.
• Also, we can see the simple_interest has float data type because Python always converts
smaller data type to larger data type to avoid the loss of data.
a = 10 File "cbse2.py", line 3, in The output shows an error which says that we cannot
<module> print(a+b) add integer and string variable types using implicit
b = "Hello"
conversion.
TypeError : unsupported
print(a+b)
operand type(s) for +: 'int'
and 'str'
c = 'Ram' RamRamRam The output shows that the string is printed 3 times
when we use a multiply operator with a string.
N=3
print(c*N)
7|Page
x = True 11 The output shows that the boolean value x will be
converted to integer and as it is true will be
y = 10
considered as 1 and then give the output.
print(x +
10)
In Explicit Type Conversion, users convert the data type of an object to required data type. We use
the predefined functions like int(), float(), str(), etc to perform explicit type conversion. This type of
conversion is also called typecasting because the user casts (changes) the data type of the objects.
Syntax:
(required_datatype) (expression)
Typecasting can be done by assigning the required data type function to the expression.
Birth_day = 10
Birth_month = "July"
Birth_day = str(Birth_day)
8|Page
data type of Birth_date : <class 'str'>
In above program,
a = 20 20 Apples Writing str(a) will convert integer a into a string and then will
add to the string b.
b = "Apples"
print(str(a)+ b)
COMPARISON OPERATORS
Comparison operators are used to compare values. It either returns True or False according to the
condition.
15 > 25 False
20 < 10 False
== Equal To 5 == 5 True
9|Page
5 == 6 False
35 != 35 False
23 >=34 False
13 <= 12 False
LOGICAL OPERATORS
PYTHON COMMENTS
Comments are non-executable statements written in the program to make it more readable and
understandable to different individuals. A comment is text that doesn't affect the outcome of a code,
it is just a piece of text to let someone know what you have done in a program or what is being done
in a block of code. In Python, single line comments are indicated by # while multiline comments are
placed inside triple quotes (‘’’ ‘’’)
10 | P a g e
TYPES OF ERRORS
A. Syntax error
Errors that occur due to improper syntax of statements in the program are called syntax errors. For
example, parentheses must occur in pairs, thus the statement print (“how is incorrect.
2. Missing a keyword.
5. Incorrect variable naming eg using a reserved word in place of a variable name, using special
characters in a variable name.
B. Logical error
A logical error is a bug in the program that causes it to behave incorrectly. A logical error produces an
undesired output but without abrupt termination of the execution of the program. Unlike a program
with syntax errors, a program with logic errors can be run, but it does not operate as intended.
Consider the following example of an logical error:
z = x+y/2
print ('The average of the two numbers you have entered is:', z)
11 | P a g e
The example above should calculate the average of the two numbers the user enters. But, because of
the order of operations in arithmetic (the division is evaluated before addition) the program will not
give the right answer:
Enter a number: 3
Enter a number: 4
The average of the two numbers you have entered is: 5.0
C. Runtime error
Runtime error is when the statement is correct syntactically, but the interpreter cannot execute it.
Runtime errors do not appear until after the program starts running or executing. A runtime error is a
program error that occurs during the execution of a program. example- Division by zero, trying to
access a file which doesn't exist.
Let’s Practice
print("Perimeter:",Perimeter)
Height:10
#Input Height
#Calculate Area
#Display Area
12 | P a g e
#Input English Marks Maths:75
#Display Discount
EXERCISE 4-A
b. ________________ function is used to cast the string variable “a” that is equal to “2” into
integer 2
f. The process of identifying and removing errors from a computer program is called
________________.
c. Python doesn’t require explicit memory management as the interpreter itself allocates
memory to new variables.
d. In Python3, Whatever you enter as input, the input() function converts it into a string.
13 | P a g e
e. The expression int(x) implies that the variable x is converted to integer.
g. Comments are used to explain code, make code more readable, and prevent execution when
testing code. Comments start with a # and Python will ignore them.
Code Correction
a. print(“Hello World”)”
c. num=5 print(num):
d. age=7:
e. print(Hello World!)
Code Output
a. print(9//2)
b. print(3*1**3)
c. var = "James" * 2 * 3
print(var)
d. valueOne = 5 ** 2
valueTwo = 5 ** 3
print(valueOne)
print(valueTwo)
e. p, q, r = 10, 20 ,30
print(p, q, r)
14 | P a g e
h. print(4 * "test")
i. print(float(5))
a=a**b
b=a**b
a=a**b
print(a)
i. In Python3, which functions are used to accept input from the user
a. input() c) raw_input()
b. rawinput() d) string()
print(22 % 3)
a. 7 c) 1
b. 0 d) 5
a. / c) //
print(3**2)
a. 5 c) 9
b. 6 d) 10
a. init c) int
b. it d) on
15 | P a g e
viii. Which of the following is an invalid statement?
a. my_string_1 c) 1st_string
b. foo d) none
a. a=1 c) a = 1
a. Yes c) no
xii. Which of the following options is correct in context to the variable name?
xiii. Which punctuation symbols are used to mark the beginning and end of a print command in
Python?
a. {} c) [ ]
b. () d) < >
a. python c) .py
b. .pi d) .pt
a. Yes
b. No
16 | P a g e
xvii. Storage locations in Python are:
b. Variables d) Operators
a) Valid
b) Invalid
As studied in the previous section, List is a sequence of values of any type. Values in the list are called
elements / items. List is enclosed in square brackets.
Example:
a = [1,2.3,"Hello"]
List is one of the most frequently used and very versatile data type used in Python. A number of
operations can be performed on the lists, which we will study as we go forward.
In Python programming, a list is created by placing all the items (elements) inside a square bracket [
], separated by commas.
It can have any number of items and they may be of different types (integer, float, string etc.).
#empty list
empty_list = []
#list of integers
age = [15,12,18]
A list is made up of various elements which need to be individually accessed on the basis of the
application it is used for. There are two ways to access an individual element of a list:
1. List Index
2. Negative Indexing
List Index
A list index is the position at which any element is present in the list. Index in the list starts from 0, so
if a list has 5 elements the index will start from 0 and go on till 4. In order to access an element in a
list we need to use index operator [].
Negative Indexing
17 | P a g e
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the
In order to access elements using negative indexing, we can use the negative index as mentioned in
the above figure.
print(my_list[0])
print(my_list[4])
print(my_list[4.0])
print(a[-6]) f
18 | P a g e
Elements can be added to the List by using built-in append() function. Only one element at a time
can be added to the list by using append() method, for addition of multiple elements with the
append() method, loops are used.
append() method only works for addition of elements at the end of the List, for addition of element
at the desired position, insert() method is used. Unlike append() which takes only one argument,
insert() method requires two arguments(position, value).
Other than append() and insert() methods, there's one more method for Addition of elements,
extend(), this method is used to add multiple elements at the same time at the end of the list.
print(List)
# Addition of Elements
List.append(1)
List after Addition: [1, 2, 4]
List.append(2)
List.append(4)
print(List)
print(List)
19 | P a g e
Using extend() # Creating a List List = [1,2,3,4]
method
print("Initial List: ") Initial List:[1, 2, 3, 4]
print(List)
print(List)
Elements can be removed from the list by using built-in remove() function but an Error arises if
element doesn't exist in the set. Remove() method only removes one element at a time, to remove
range of elements, iterator is used. The remove() method removes the specified item.
NOTE – Remove method in List will only remove the first occurrence of the searched element.
Pop() function can also be used to remove and return an element from the set, but by default it
removes only the last element of the set, to remove an element from a specific position of the List,
index of the element is passed as an argument to the pop() method.
print(List)
20 | P a g e
List.remove(5)
List.remove(6)
print(List)
Using pop() # Removing element by using pop() List after popping an element:
method
List.pop() [1, 2, 3, 4, 7, 8, 9, 10, 11]
print(List)
List after popping a specific element:
[1, 2, 4, 7, 8, 9, 10, 11]
List.pop(2)
print(List)
LIST METHODS
Some of the other functions which can be used with lists are mentioned below:
21 | P a g e
clear() Removes all items from the list.
EXERCISE 4-B
1. List = [ ]
print(List)
List.append[2]
List.append[3]
print(List)
print(List)
List.insert("Kolkata")
22 | P a g e
List.remove(2)
List = [14,23,45,67,89,36]
print((count(List)))
print(r[1;4])
1. marks=[5,10,15,20]
print(sum(marks))
2. list=[12,45,0,73,5]
print(list[2]*list[4])
3. letter=["A","B","C","D","E"]
letter.reverse()
print(letter)
In the programs we have seen till now, there has always been a series of statements faithfully
executed by Python in exact top-down order. What if you wanted to change the flow of how it
works? For example, you want the program to take some decisions and do different things depending
on different situations, such as printing 'Good Morning' or 'Good Evening' depending on the time of
the day?
As you might have guessed, this is achieved using control flow statements. There are three control
flow statements in Python - if, for and while.
There come situations in real life when we need to make some decisions and based on these
decisions, we need to decide what should we do next. Similar situations arise in programming also
where we need to make some decisions and based on these decisions we will execute the next block
of code.
23 | P a g e
Decision making statements in programming languages decide the direction of flow of program
execution. Decision making statements available in Python are:
● if statement
● if..else statements
● if-elif ladder
IF STATEMENT
The if statement is used to check a condition: if the condition is true, we run a block of statements
(called the if-block).
SYNTAX:
if text expression:
statement(s)
Here, the program evaluates the test expression and will execute statement(s) only if the text
expression is True.
NOTE:
• In python, the body of the if statement is indicated by the indentation. Body starts with an
indentation and the first unindented line marks the end.
• Python interprets non-zero values ad True. None and 0 are interpreted as False.
num = 3
if num > 0:
24 | P a g e
When you run the program, the output will be:
3 is a positive number
In the above example, num > 0 is the test expression. The body of if is executed only if this evaluates
to True.
When variable num is equal to 3, test expression is true and body inside body of if is executed.
NOTE: The print() statement falls outside of the if block (unindented). Hence, it is executed
regardless of the test expression.
SYNTAX of if...else:
if test expression:
Body of if
else:
Body of else
The if..else statement evaluates test expression and will execute body of if only when test condition
is True.
If the condition is False, body of else is executed. Indentation is used to separate the blocks.
else:
In the above example, when if the age entered by the person is greater than or equal to 18, he/she
can vote. Otherwise, the person is not eligible to vote.
25 | P a g e
SYNTAX of if...elif...else:
if test expression:
Body of if
Body of elif
else:
Body of else
The elif is short for else if. It allows us to check for multiple expressions.
If the condition for if is False, it checks the condition of the next elif block and so on.
Only one block among the several if...elif...else blocks is executed according to the condition. The if
block can have only one else block. But it can have multiple elif blocks.
else:
The for...in statement is another looping statement which iterates over a sequence of objects i.e. go
through each item in a sequence. We will see more about sequences in detail in later chapters. What
you need to know right now is that a sequence is just an ordered collection of items.
26 | P a g e
Syntax of for Loop:
Body of for
Here, val is the variable that takes the value of the item inside the sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is separated from
the rest of the code using indentation.
# List of numbers
sum = 0
sum = sum+val
The sum is 48
The while statement allows you to repeatedly execute a block of statements as long as a condition is
true. A while statement is an example of what is called a looping statement. A while statement can
have an optional else clause.
while test_expression:
Body of while
In while loop, test expression is checked first. The body of the loop is entered only if the
test_expression evaluates to True. After one iteration, the test expression is checked again. This
process continues until the test_expression evaluates to False. In Python, the body of the while loop
is determined through indentation. Body starts with indentation and the first unindented
line marks the end. Python interprets any non-zero value as True. None and 0 are
interpreted as False.
27 | P a g e
Flowchart of while Loop Example: Python while Loop
# sum = 1+2+3+...+n
n = int(input("Enter n: "))
n = 10
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1
Enter n: 10
The sum is 55
In the above program, the test expression will be True as long as our counter variable i is less than or
equal to n (10 in our program).
We need to increase the value of the counter variable in the body of the loop. This is very important
(and mostly forgotten). Failing to do so will result in an infinite loop (never ending loop).
28 | P a g e