Unit -2 Introduction to Python
Chap-2
Basics of Python programming
Copyright material NCERT
Copyright material NCERT
The structure of a program
Structure of a python program
Program
|->Module -> main program
| -> functions
| -> libraries
|->Statements -> simple statement
| -> compound statement
|->expressions -> Operators
| -> expressions
Copyright material NCERT
Introduction
A Python program is called a script.
Script is a sequence of definitions and commands.
These commands are executed by Python interpreter
known as PYTHON SHELL.
In python programming,
data types are inbuilt hence support “dynamic
typing”
declaration of variables is not required.
memory management is automatically done.
Copyright material NCERT
Python Character Set
A set of valid characters recognized by python.
• Python uses the traditional ASCII character set.
• The latest version recognizes the Unicode character set.
The ASCII character set is a subset of the Unicode
character set.
Letters: a-z, A-Z
Digits : 0-9
Special symbols : Special symbol available over keyboard
White spaces: blank space, tab, carriage return, new
line, form feed
Other characters: Unicode
Copyright material NCERT
Tokens
Smallest individual unit in a program is
known as token.
1. Keywords
2. Identifiers
3. Literals
4. Operators
5. Delimiters
Copyright material NCERT
1. Keywords
• Keywords are reserved words. Each keyword has
a specific meaning to the Python interpreter.
• Reserved word of the compiler/interpreter which
can’t be used as identifier.
Copyright material NCERT
2. Identifiers
A Python identifier is a name used
to identify a variable, function,
module and packages.
Copyright material NCERT
2. Identifiers
The rules for naming an identifier in Python are as
follows:
• The name should begin with an uppercase or a
lowercase alphabet or an underscore sign (_). This may
be followed by any combination of characters a-z, A-Z,
0-9 or underscore (_).
Thus, an identifier cannot start with a digit.
• It can be of any length. (However, it is preferred to keep
it short and meaningful).
• It should not be a keyword or reserved word.
• We cannot use special symbols like !, @, #, $, %, etc. in
identifiers.
Copyright material NCERT
Variables
A variable is an identifier that stores values that you can
access or change.
Variable name should be unique in a program. Value of a
variable can be string (e.g. ‘Citizen’), number (e.g.
10,71,80.52) or any combination of alphanumeric (e.g. ‘b10’)
characters.
In Python, we can use an assignment statement to create
new variables and assign specific values to them.
gender = 'M’
message = "Keep Smiling"
price = 987.9
num
Copyright =NCERT
material 10
Variables
A variable has three main components:
A) Identity of variable
B) Type of variable
C) Value of variable
Copyright material NCERT
A) Identity of the variable
It refers to object’s address in the
memory.
>>> x=10
e.g. >>> id (x)
Copyright material NCERT
B) Type of the variable
Type means Data Type of a variable.
• Data type identifies the type of data which a variable can hold
and the operations that can be performed on those data.
Copyright material NCERT
Data Type
(i) Number: It stores numerical values only.
Python supports three built in numeric types – integer,
floating point numbers and complex numbers.
a. int (integer): Integer represents whole numbers.
(positive or negative)
e.g. -6, 0, 23466
b. float (floating point numbers): It represents numbers
with decimal point.
e.g. -43.2, 6.0
c. complex (complex numbers): It is made up of pair of
real and imaginary number.
e.g. 2+5i
Copyright material NCERT
Data Type
(ii) String (str): It is a sequence of
characters. (combination of letters,
numbers and symbols).
It is enclosed within single or double
quotes.
e.g. (‘ ’ or “ ”)
>>> rem= “Hello Welcome to Python”
>>> print (rem)
Hello Welcome to Python
Copyright material NCERT
Data Type
(iii) Boolean (bool):
Boolean data type (bool) is a subtype of integer.
It is a unique data type, consisting of two constants, True
and False.
Boolean True value is non-zero. Boolean False is the value
zero.
>>> bool_1 = (6>10)
>>> print (bool_1)
False
>>> bool_2 = (6<10)
>>> print (bool_2)
True
Copyright material NCERT
Data Type
(iv) None: It is a special data type with
single value.
It is used to signify absence of value
evaluating to false in a situation.
>>> value_1 = None
>>> print (value_1)
None
Copyright material NCERT
Data Type
type() – if you wish to determine type of
the variable.
e.g.
>>> type(10)
<class ‘int’>
>>> type(8.2)
<class ‘float’>
>>> type(“hello”)
<class ‘str’>
>>> type(True)
<class ‘bool’>
Copyright material NCERT
C) Value of variable
Values are assigned to a variable using
assignment operator (=)..
e.g.
>>>marks=87 marks – Name of the variable
>>>print(marks)
87
87 Value of the variable
Copyright material NCERT
Value
The concept of assignment:
Value_1 = 100
Variable Assignment Value
operator
There should be only one variable on the left-hand side of
assignment operator.
This variable is called Left value or L-value
There can be any valid expression on the right-hand side of
assignment operator.
This variable is called Right value or R-value
L-value = R-value
Copyright material NCERT
Value
Multiple assignments:
We can declare multiple variables in a
single statement.
e.g.
>>>x, y, z, p = 2, 40, 30.5, ‘Vinay’
Copyright material NCERT
DATA TYPES IN PYTHON
Sequence
• A Python sequence is an ordered collection of
items, where each item is indexed by an
integer value. Three types of sequence data
types available in Python are Strings, Lists and
Tuples.
Copyright material NCERT
SEQUENCE DATA TYPE
String
• String is a group of characters.
These characters may be alphabets, digits or special
characters including spaces.
String values are enclosed either in single quotation marks
(for example ‘Hello’) or in double quotation marks (for
example “Hello”).
>>> str1 = 'Hello Friend'
>>> str2 = "452"
Copyright material NCERT
SEQUENCE DATA TYPE
List
List is a sequence of items separated by commas and items are
enclosed in square brackets [ ].
Note that items may be of different date types.
We can change items in a List.
Example
#To create a list
>>> list1 = [5, 3.4, "New Delhi", "20C", 45]
#print the elements of the list list1
>>> list1
[5, 3.4, 'New Delhi', '20C', 45]
Copyright material NCERT
SEQUENCE DATA TYPE
Tuple
Tuple is a sequence of items separated by commas and items
are enclosed in parenthesis ( ).
This is unlike list, where values are enclosed in brackets [ ].
Once created, we cannot change items in the tuple.
Similar to List, items may be of different data types.
Example
#create a tuple tuple1
>>> tuple1 = (10, 20, "Apple", 3.4, 'a')
#print the elements of the tuple tuple1
>>> print(tuple1)
(10, 20, "Apple", 3.4, 'a'
Copyright material NCERT
DATA TYPES IN PYTHON
Mapping
Mapping is an unordered data type in
Python. Currently, there is only one standard
mapping data type in Python called Dictionary.
Copyright material NCERT
MAPPING DATA TYPE
DICTIONARY
Dictionary in Python holds data items in key-value
pairs and Items are enclosed in curly brackets { }.
dictionaries permit faster access to data.
Every key is separated from its value using a
colon (:) sign.
The key value pairs of a dictionary can be
accessed using the key. Keys are usually of string
type and their values can be of any data type. In
order to access any value in the dictionary, we
have to specify its key in square brackets [ ].
Copyright material NCERT
MAPPING DATA TYPE
dICTIONARY
Example 3.4 #create a dictionary
>>> dict1 = {'Fruit':'Apple', 'Climate':'Cold', 'Price(kg)':120}
>>> print(dict1)
{'Fruit': 'Apple', 'Climate': 'Cold', 'Price(kg)': 120}
#getting value by specifying a key
>>> print(dict1['Price(kg)'])
120
Copyright material NCERT
Variable Naming Convention
1. A variable name can contain letter, digits and underscore (_). No
other characters are allowed.
2. A variable name must start with an alphabet or and underscore (_).
3. A variable name cannot contain spaces.
4. Keyword cannot be used as a variable name.
5. Variable names are case sensitive. Num and num are different.
6. Variable names should be short and meaningful.
Invalid variable names – 3dgraph, roll#no, first name, d.o.b, while
Copyright material NCERT
Mutable and Immutable Data types
• Mutable Data Types: Data types in python
where the value assigned to a variable can
be changed
• Immutable Data Types: Data types in python
where the value assigned to a variable
cannot be changed
Copyright material NCERT
Mutable and Immutable Data types
• Mutable Data types in Python
1. List
2. Dictionary
It is possible to add, delete, modify and rearrange items in a list
or dictionary. Hence, they are mutable objects.
• Immutable Data types in Python
1. Numeric
2. String
3. Tuple
Number values, strings, and tuple are immutable, which means
their contents can’t be altered after creation.
Copyright material NCERT
3. Literals/Constant
Literals in Python can be defined as number, text, or other data that
represent values to be stored in variables.
In contrast to variables, literals (123, 4.3, "hi") do not change in
value.
Example of String Literals in Python
Single line Strings: Enclose text in single (‘ ‘) or double quotes (“ “).
name = ‘Johni’
lname=“Dsouza”
Multiline Strings: Store text spread across multiple lines as one single
string enclosed in (‘’’ ‘’’) or (“”” “””)
Str1 = ‘’’Hello
World
Welcome to programming’’’
Copyright material NCERT
3. Literals/Constant
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
name = None
Copyright material NCERT
3. Literals
Escape sequence
e.g.
print(“I am a student of \n APS \t Yol Cantt”)
Copyright material NCERT
4. Operators
Operators can be defined as symbols that are used to
perform mathematical or logical operations on
operands.
Types of Operators
a. Arithmetic Operators.
b. Relational Operators.
c. Assignment Operators.
d. Logical Operators.
e. Membership Operators
f. Identity Operators
Copyright material NCERT
4. Operators
a. Arithmetic Operators.
Arithmetic Operators are used to perform arithmetic operations
as well as modular division, floor division and exponentiation
Copyright material NCERT
print ("hello"+"python")
print(‘India’ * 2)
print(2+3)
print(10-3)
print(22%5)
print(19//5)
print(2**3)
Output:
Hellopython
IndiaIndia
5
7
2
3
Copyright material NCERT 8
4. Operators
b. Relational Operators.
Relational operator compares the values of the operands on its
either side and determines the relationship among them
Copyright material NCERT
print(5==3) False
print(7>3) True
print(15<7) False
print(3!=2) True
print(7>=8) False
print(3<=4) True
Copyright material NCERT
4. Operators
c. Assignment Operators.
Assignment operator assigns or changes the value of the variable
on its left.
Copyright material NCERT
a=10
print(a)
a+=9
print(a)
Output:
b=11 10
b*=3 19
print(b) 33
9.5
c=19
c/=2 16
print(c)
d=2
d**=4
print(d)
Copyright material NCERT
4. Operators
d. Logical Operators.
Logical Operators are used to perform logical operations
on the given two variables or values.
a=30 a=70
b=20 b=20
if(a==30 and b==20):
print("hello")
if(a==30 or b==20):
Output :- print("hello")
hello
Copyright material NCERT
4. Operators
e. Membership Operators
It used to validate whether a value is found within a
sequence such as such as strings, lists, or tuples.
E.g. E.g.
a = 22 a = 22
list = [11, 22,33,44] list = [11, 22,33,44]
ans= a in list ans= a not in list
print(ans) print(ans)
Output: True Output: False
Copyright material NCERT
4. Operators
f. Identity Operators
Identity operators in Python compare the memory
locations of two objects.
Copyright material NCERT
Copyright material NCERT
Copyright material NCERT
5. Delimiters
These are the symbols which can be used as
separator of values or to enclose some values.
e.g ( ) {} [ ] , ; :
Copyright material NCERT
Identify variable, keyword, literal, delimiter
Token Category
X Variable
y Variable
z Variable
print Keyword
() Delimiter
/ Operator
68 Literal
“x, y, z” Literal
Copyright material NCERT
Statements
A statement in Python is a logical instruction which
Python interpreter can read and execute.
In Python, it could be an expression or an
assignment statement.
The assignment statement is fundamental to
Python. It defines the way an expression creates
objects and preserve them.
Copyright material NCERT
Statements
Simple Assignment Statement
In a simple assignment, we create new variables,
assign and change values. This statement provides
an expression and a variable name as a label to
preserve the value of the expression.
# Syntax
variable = expression
# LHS <=> RHS
Copyright material NCERT
Statements
Augmented Assignment Statement
You can combine arithmetic operators
in assignments to form an augmented assignment
statement.
e.g.
x += y
x = x + y
Copyright material NCERT
Statements
Multi-line Statement in Python
Usually, every Python statement ends with a
newline character. However, we can extend it over
to multiple lines using the line continuation character
(\).
e.g.
print(“I am a student of \n APS \t Yol Cantt”)
Copyright material NCERT
Expressions
Expressions are combination of value(s). i.e.
constant, variable and operators.
Expression Value
5+2*4 13
8+12*2-4 28
“Global”+”Citizen” GlobalCitizen
Converting mathematical expression to
equivalent Python expression
Algebraic Expression Python Expression
𝑥
y=3( ) y = 3 * (x / 2)
2
z= 3bc + 4 z = 3*b*c + 4
Copyright material NCERT
Comments
Comments are statements in the script that are
ignored by the Python interpreter.
Comments (hash symbol = #) makes code more
readable and understandable.
# Program to assign value
x=10
x=x+100 # increase value of x by 100
print(x)
Copyright material NCERT
Indentation
• Python uses indentation for block as well as
for nested block structures.
• Leading whitespace (spaces and tabs) at the
beginning of a statement is called indentation.
• In Python, the same level of indentation
associates statements into a single block of
code.
Copyright material NCERT
Indentation
• The interpreter checks indentation levels very
strictly and throws up syntax errors if
indentation is not correct.
• It is a common practice to use a single tab for
each level of indentation.
e.g.
if (5>2):
print(‘Five is greater than two’)
else:
print(“*******”)
Copyright material NCERT
Debugging
Due to errors, a program may not execute or may
generate wrong output.
• Syntax errors
• Logical errors
• Runtime errors
The process of identifying and removing logical errors
and runtime errors is called debugging.
We need to debug a program so that is can run
successfully and generate the desired output.
Copyright material NCERT
Syntax error
• Like any programming language, Python has
rules that determine how a program is to be
written. This is called syntax.
• The interpreter can interpret a statement of a
program only if it is syntactically correct.
• If any syntax error is present, the interpreter
shows error message(s) and stops the
execution there.
• Such errors need to be removed before
execution of the program.
Copyright material NCERT
Logical error
• Logical error/bug (called semantic error)
does not stop execution but the program
behaves incorrectly and produces
undesired /wrong output.
• Since the program interprets
successfully even when logical errors are
present in it, it is sometimes difficult to
identify these errors.
Copyright material NCERT
Runtime error
• A runtime error causes abnormal termination
of program while it is executing.
• Runtime error is when the statement is correct
syntactically, but the interpreter can not
execute it.
For example, we have a statement having
division operation in the program. By mistake, if
the denominator value is zero then it will give a
runtime error like “division by zero”.
Copyright material NCERT
Input/Output
Python provides three functions for getting
user’s input.
• input() function – The input() function prompts user to
enter data. It accepts all user input (whether alphabets, numbers or
special character) as string.
It is used to get data in script mode.
The input() function takes string as an argument. It always
returns a value of string type.
The syntax for input() is:
variable = input([Prompt])
Prompt is the string we may like to display on the screen
prior to taking the input, but it is optional.
Copyright material NCERT
Conversion
2. int() function– It is used to convert input string
value to numeric value.
3. float() function – It converts fetched value in float
type.
4. eval() – This function is used to evaluate the
value of a string.
It takes input as string and evaluates this string as
number and return numeric result.
NOTE : input() function always enter string value in
python 3. So on need int(), float() function can be
used for data conversion.
Copyright material NCERT
print() function
Python uses the print() function to output data to
standard output device — the screen.
The function print() evaluates the expression
before displaying it on the screen.
The syntax for print() is:
print(value)
Copyright material NCERT
Sample Program-1
n1 = input("Enter first number")
n2 = input("Enter second number")
n3=n1+n2 #adding two strings
print(n3)
Copyright material NCERT
Sample Program-2
name = input("Enter Name: ")
clas = input("Enter Class & Section: ")
print("Hello ", name)
print("Class & Section is ", clas)
print("Welcome to Python Programming")
Copyright material NCERT
Sample Program-3
n1 = int(input("Enter first number"))
n2 = int(input("Enter second number"))
Sum=n1+n2
print("Sum is:", Sum)
OR
n1 = eval(input("Enter first number"))
n2 = eval(input("Enter second number"))
Sum=n1+n2
print("Sum is:", Sum)
Copyright material NCERT
Sample Program - 4
p = int(input("Enter Principal:"))
r = float(input("Enter Rate:"))
t = int(input("Enter Time:"))
si=0.0
si=(p*r*t)/100
print("Simple Interest is:", si)
Copyright material NCERT
Sample Program - 5
m1 = int(input("Enter marks in English:"))
m2 = int(input("Enter marks in Hindi:"))
m3 = int(input("Enter marks in Maths:"))
m4 = int(input("Enter marks in Science:"))
m5 = int(input("Enter marks in Social Science:"))
total=m1+m2+m3+m4+m5
per = total/5
print("Total is:", total)
print("Percenatge is:", per)
Copyright material NCERT
Functions
A function refers to a set of statements
or instructions grouped under a name
that perform specified tasks.
• For repeated or routine tasks, we define
a function.
• A function is defined once and can be
reused at multiple places in a program by
simply writing the function name, i.e., by
calling that function.
Copyright material NCERT
Built-in Functions
Python has many predefined functions called built-in functions.
We have already used two built-in functions print() and
input().
A module is a python file in which multiple functions are
grouped together.
These functions can be easily used in a Python program by
importing the module using import command.
Use of built-in functions makes programming faster and efficient.
Copyright material NCERT
Built-in Functions
To use a built-in function we must know the following about that
function:
Function Name — name of the function.
Arguments — While calling a function, we may pass value(s), called
argument, enclosed in parenthesis, to the function.
The function works based on these values. A function may or may
not have argument(s).
Return Value − A function may or may not return one or more
values.
Copyright material NCERT
Built-in Functions
Copyright material NCERT
User Defined Functions
Function created on our own is known as user
defined function.
Syntax:
def function_name(comma_sep_list_parameters):
statements
Copyright material NCERT
User Defined Functions
Example 1:
def display():
print(“Welcome to python”)
>>>display()
Example 2:
def arearec(len, wd):
area=len*wd
return area
>>>arearec(30, 10)
Copyright material NCERT