Brief Overview of
PYTHON
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
An ordered set of instructions or commands to be executed
By a computer is called a program.
The language used to specify those set of instructions to the
computer is called a programming language for example
Python, C, C++, Java, etc.
Python is a very popular and easy to learn programming
language, created by Guido van Rossum in 1991.
It is used in a variety of fields including
software development
web development
scientific computing
big data and
Artificial Intelligence.
• Portability −Python can run on a wide variety of hardware
platforms and has the same interface on all platforms.
• Extendibility – It allows to add low-level modules to the Python
interpreter.
• Databases −Python provides interfaces to all major commercial
databases.
• GUI Programming −Python supports GUI applications that can be
created and ported to many system calls, libraries and windows
systems, such as Windows MFC, Macintosh, and the XWindow
system of UNIX.
• Very Easy-to-learn −Python has few keywords, simple structure,
and a clearly defined syntax. This allows the student to pick up the
language quickly.
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
• Readability −Python code is more clearly defined and visible to the
eyes.
• Interactive Mode −Python uses SHELL which allows interactive
testing and debugging of snippets of code.
• Garbage Collections: It supports automatic garbage collection.
• It can be easily integrated with C, C++, COM, ActiveX, CORBA,
and Java.
Working with Python
To write and run (execute) a Python program, we need to have a
Python interpreter installed on our computer or we can use any online
Python interpreter. The interpreter is also called Python shell.
Figure 1.1
A sample screen of Python interpreter is shown in above Figure 1.1.
Here, the symbol >>> is called Python prompt. We can type
commands or statements on this prompt for execution.
Execution Modes
There are two ways to run a program using the Python interpreter:
a) Interactive mode
b) Script mode
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
(A) Interactive Mode
In the interactive mode, we can type a Python statement
on the >>> prompt directly. As soon as we press enter, the
interpreter executes the statement and displays the result(s),
as shown in Figure 1.2 Working in the interactive mode is
convenient for testing a single line code for instant execution.
figure 1.2 Python Interpréter in Interactive Mode
(B) Script Mode
In the script mode, we can write a Python program in a file,
save it and then use the interpreter to execute the program
from the file. Such program files have sum.py extension and
they are also known as scripts.
Python has a built-in editor called IDLE (Integrated
Development and Learning Environment) which can be used
to create programs. After opening the IDLE, we can click
File>New File to create a new file, then write our program on
that file and save it with a desired name (sum.py). By
default, the Python scripts are saved in the Python
installation folder.
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Python Program in Script Mode
Output: >>> 30
• IDLE helps you
program in Python
by:
– color-coding your
program code
– debugging
– auto-indent
– interactive shell
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Features of Python
Python Character Set
Character Set is a group of letters or signs which are specific to
a language.
Character set includes letter, sign, number and symbol.
Letters: A-Z, a-z
Digits: 0-9
Special Symbols: _, +, -, *, /, (, #,@, {, } etc.
White Spaces: blank space, tab, carriage return, newline,
formfeed etc.
Other characters: Python can process all characters of ASCII
and UNICODE.
Tokens
Token is the smallest unit of any programming language. It
is also known as Lexical Unit. Types of token are-
i. Keywords
ii. Identifiers (Names)
iii. Literals
iv. Operators
v. Punctuators
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Keywords
Keywords are reserved words. Each keyword has a specific
meaning to the Python interpreter. As Python is case
sensitive, these cannot be used as identifiers, variable name
or any other purpose keywords must be written exactly as
given in Table 1.3
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
Table 1.3 Python Keywords
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Identifiers
In programming languages, identifiers are names used to
identify a variable, function, or other entities in a program.
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 given in Table
3.1.
We cannot use special symbols like !, @, #, $, %, etc. in
identifiers.
For example, to find the average of marks obtained by a student
in three subjects namely Maths, English, Informatics Practices (IP),
we can choose the identifiers as marksMaths, marksEnglish,
marksIP and avg rather than a, b, c, or A, B, C, as such alphabets
do not give any clue about the data that variable refers to.
avg = (marksMaths + marksEnglish + marksIP)/3
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Literals/ Values
Literals are often called Constant Values.
Python permits following types of literals -
a. –String literals - “Rishaan”
b. –Numeric literals – 10, 13.5, 3+5i
c. –Boolean literals – True or False
d. –Special Literal None
e. –Literal collections
String Literals
String Literal is a sequence of characters that can be a
combination of letters, numbers and special symbols,
enclosed in quotation marks, single, double or triple(“ “ or
‘ ‘ or “’ ‘”).
In python, string is of two types-
Single line string
Text = “Hello World” or Text = ‘Hello World’
Multi line string
Text = ‘hello\ or Text = ‘’’hello
world’ word ‘’’
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Numeric Literals
Numeric values can be of three types –
int (signed integers)
Decimal Integer Literals – 10, 17, 210 etc.
Octal Integer Literals - 0o17, 0o217 etc.
Hexadecimal Integer Literals – 0x14, 0x2A4, 0xABD etc.
float (floating point real value)
Fractional Form – 2.0, 17.5 -13.5, -.00015 etc.
Exponent Form - -1.7E+8, .25E-4 etc.
complex (complex numbers)
3+5i etc.
Numeric values with commas are not considered int or float
value, rather Python treats them as tuple. Tuple in a python is
a collection of values or sequence of values.
You can check the type of literal using type() function. For
e.g.
>>> a=100
>>> type(a)
<class 'int'>
>>> b=10.5
>>> type(b)
<class 'float'>
>>> name="hello“
>>> type(name)
<class 'str'>
>>> a=100,50,600
>>> type(a)
<class 'tuple'>
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Boolean Literals
It can contain either of only two values – True or False
A= True
B=False
Special Literals
None, which means nothing (no value).
X = None
Variables
Variable is an identifier whose value can change. For example
variable age can have different value for different person.
Variable name should be unique in a program. Value of a
variable can be
string : ‘b’, ‘Global Citizen’
number : 10, 71, 80.52
alphanumeric : ‘b10’
In Python, we can use an assignment statement to create
new variables and assign specific values to them.
gender = 'M'
message = "Keep Happy"
price = 987.9
sum = a+b
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Write a Python program to find the sum of two numbers.
Output:
30
Write a Python program to find the area of a rectangle given
that its length is 10 units and breadth is 20 units.
Output:
200
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Lvalues and Rvalues
Lvalue : expression that comes on the Left hand
Side of Assignment.
Rvalue : expression that comes on the Right hand
Side of Assignment
Lvalue refers to object to which you can assign value. It
refers to memory location. It can appear LHS or RHS of
assignment
Rvalue refers to the value we assign to any variable. It can
appear on RHS of assignment
For example (valid use of Lvalue and Rvalue)
x = 10
y = 20
Invalid use of Lvalue and Rvalue
10 = x
20 = y
a+b = c
Note: values cannot comes to the left of assignment. LHS
must be a memory location
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Multiple Assignments
Python is very versatile with assignments. Let’s see in how
different ways we can use assignment in Python:
1. Assigning same value to multiple variable
a = b = c = 25
2. Assigning multiple values to multiple variable
a,b,c = 3,6,9
Note: While assigning values through multiple assignment,
remember that Python first evaluates the RHS and then
assigns them to LHS
Examples:
x,y,z = 10,20,30 #Statement 1
z,y,x = x+1,z+10,y-10 #Statement 2
print(x,y,z)
Output
10 40 11
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
The output of following code fragment
x,y = 7,9
y,z = x-2, x+10
print(x,y,z)
Output
7 5 17
Let us take another example
y, y = 10, 20
In above code first it will assign 10 to y and again it assign
20 to y, so if you print the value of y it will print 20
The output of following code
x, x = 100,200
y,y = x + 100, x +200
print(x,y)
Output
200 400
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Every value belongs to a specific data type in Python. Data
type identifies the type of data which a variable can hold and
the operations that can be performed on those data. Figure
enlists the data types available in Python.
Different Data Types in Python
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Data types are actually classes, and variables are instance
(object) of these classes.
There are various data types in Python. Some of the important
types are listed below
Data Types in Python
Numbers
List
Tuple
Strings
Set
Dictionary
Number
Number data type stores numerical values only. It is further
classified into three different types: int, float and
complex.
Type/Class Description Examples
int integer numbers -12, -3, 0, 123, 2
float floating point numbers -2.04, 4.0, 14.23
complex complex numbers 3 + 4i, 2 - 2i
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Example
>>> quantity = 10
>>> type(quantity)
<class 'int'>
>>> Price = -1921.9
>>> type(price)
<class 'float'>
Sequence
A 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
Strings
Lists
Tuples.
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 or
in double quotation marks For example
>>> str1 = 'Hello Friend'
>>> str2 = "452"
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
We cannot perform numerical operations on strings, even
when the string contains a numeric value. For example str2 is
a numeric string.
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.
#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]
Tuple
Tuple is a sequence of items separated by commas and items
are enclosed in parenthesis ( ). Once created, we cannot
change items in the tuple. Similar to List, items may be of
different data types.
#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')
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Mapping
Mapping is an unordered data type in Python. Currently,
there is only one standard mapping data type in Python
called Dictionary.
(A) 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 [ ].
#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
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Operators
An operator is used to perform specific mathematical or
logical operation on values. The values that the operator
works on are called operands.
For example, in the expression 10 + num, the value 10, and
the variable num are operands and the + (plus) sign is an
operator.
Operands/ Values
Example: sum= a + b
Operators
Here, a, b, sum are operands and operators are = and +
which are performing differently.
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Types of Operators
Python supports following types of operators -
Unary Operator
•Unary plus (+)
•Unary Minus (-)
•Bitwise complement (~)
•Logical Negation (not)
Binary Operator
•Arithmetic operator (+, -, *, /, %, **, //)
•Relational Operator(<, >, <=, >=, ==,!= )
•Logical Operator (and, or)
•Assignment Operator (=, /=, +=, -=, *=, %=, **=, //=)
•Bitwise Operator (& bitwise and, ^ bitwise xor,
|bitwise or)
•Shift operator (<< shift left, >> shift right)
•Identity Operator (is, is not)
•Membership Operator (in, not in)
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Arithmetic Operators
Python supports arithmetic operators (below Table 1.4) to
perform the four basic arithmetic operations as well as
modular division, floor division and exponentiation.
'+' operator can also be used to concatenate two strings on
either side of the operator.
>>> str1 = "Hello"
>>> str2 = "India"
>>> str1 + str2
Output: 'HelloIndia'
'*' operator repeats the item on left side of the operator if first
operand is a string and second operand is an integer value.
>>> str1 = 'India'
>>> str1 * 2
Output: 'IndiaIndia'
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Table 1.4 Arithmetic operators in Python
Operator Operation Description Example (Try in Lab)
+ Addition Adds two numeric values >>> num1 = 5
on either side of the >>> num2 = 6
operator >>> num1 + num2
11
- Subtraction Subtracts the operand on >>> num1 = 5
the right from the operand on >>> num2 = 6
the left >>> num1 - num2
-1
* Multiplicati Multiplies the two values on >>> num1 = 5
on both sides of the operator >>> num2 = 6
>>> num1 * num2
30
/ Division Divides the operand on the >>> num1 = 5
left by the operand on the right >>> num2 = 2
of the operator and returns the >>> num1 / num2
quotient 2.5
% Modulus Divides the operand on the >>> num1 = 13
left by the operand on the right >>> num2 = 5
and returns the remainder >>> num1 % num2
3
// Floor Divides the operand on the >>> num1 = 5
Division left by the operand on the right>>> num2 = 2
and returns the quotient by >>> num1 // num2
removing the decimal part. It is2
sometimes also called integer >>> num2 // num1
division. 0
** Exponent Raise the base to the power of >>> num1 = 3
the exponent. That is, multiply >>> num2 = 4
the base as many times as >>> num1 ** num2
given in the exponent 81
Operators (+) and (*) work in similar manner for other
sequence data types like list and tuples.
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Relational Operators
Relational operator compares the values of the operands on
its either side and determines the relationship among them.
Consider the given Python variables num1 = 10, num2 = 0,
num3 = 10, str1 = "Good", str2 = "Afternoon" for the
following examples in Table 1.5
Table 1.5 Relational operators in Python
Operat Operation Description Example (Try in Lab)
== Equals to If values of two operands are equal, >>> num1 == num2
then the condition is True, False
otherwise it is False. >> str1 == str2
False
>>> num1 != num2
!= Not equal If values of two operands are True
to not equal, then condition is >>> str1 != str2
True, otherwise it is False True
>>> num1 != num3
False
If the value of the left >>> num1 > num2
> Greater operand is greater than the True
than value of the right operand, >>> str1 > str2
then condition is True, True
otherwise it is False.
If the value of the left
< Less operand is less than the >>> num1 < num3
than value of the right operand, False
the condition is true
otherwise it is False
Similarly, there are other relational operators like <= and >=.
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Assignment Operators
Assignment operator assigns or changes the value of the
variable on its left, as shown in Table 1.6
Operator Description Example (Try in Lab)
= Assigns value from right >>> num1 = 2
side operand to left side >>> num2 = num1
operand >>> num2 2
>>> country = 'India'
>>> country
'India'
+= It adds the value of right >>> num1 = 10
side operand to the left >>> num2 = 2
side operand and assigns >>> num1 += num2
the result to the left side >>> num1
operand. 12
Note: x+=y is same as x =x +y >>> num2
2
-= It subtracts the value >>> num1 = 10
of right side operand >>> num2 = 2
from the left side >>> num1 -= num2
operand and assigns >>> num1
the result to left side 8
operand.
Note: x-=y is same as x =x -y
Table 1.6
Similarly, there are other assignment operators like *=,
/=, %=, //=, and **=.
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Logical Operators
There are three logical operators (Table 1.7) supported by
Python. These operators (and, or, not) are to be written in lower
case only. The logical operator evaluates to either True or False
based on the logical operands on its either side
Operator Operation Description Example (Try in Lab)
and Logical If both operands >>> num1 = 10
AND are True, then >>> num2 = -20
condition >>> num1 == 10 and num2 == -20
becomes True True
>>> num1 == 10 and num2 == 10
False
or Logical >>> num1 = 10
If any of the two
OR operands are >>> num2 = 2
True, then >>> num1 >= 10 or num2 >= 10
condition
becomes True True
>>> num1 <= 5 or num2 >= 10
False
not Logical Used to reverse >>> num1 = 10
NOT the logical state >>> not (num1 == 20)
of its operand True
>>> not (num1 == 10)
False
4
0 40 Table 1.7 Logical operators in Python
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Membership Operators
Membership operator (Table 1.8) is used to check if a
value is a member of the given sequence or not. 40 40 40
Operator Description Example (Try in Lab)
in Returns True if the variable or >>> numSeq = [1,2,3]
value is found in the specified >>> 2 in numSeq
sequence and False otherwise True
>>> '1' in numSeq
False
#'1' is a string while
#numSeq contains number 1.
not in Returns True if the >>> numSeq = [1,2,3]
variable/value is not found in >>> 10 not in numSeq
the specified sequence and True
False otherwise >>> 1 not in numSeq
False
Table 1.8 Membership operator
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Bitwise
Bitwise operator works on the binary value of number not
on the actual value. For example if 5 is passed to these
operator it will work on101 not on 5. Binary of 5 is 101,
and return the result in decimal not in binary.
Operato Purpose Action
& Bitwise AND Return 1, if both inputs are 1
^ Bitwise XOR Return 1, if the number of 1 in
input is in odd
| Bitwise OR Return 1 if any input is 1
Shift Operator
Operators Purpose
<< Shift left
>> Shift right
Identity Operators
Operators Purpose
is Is the Identity same?
is not Is the identity not same?
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Expression
An expression is defined as a combination of constants,
variables and operators. An expression always evaluates
to a value. A value or a standalone variable is also
considered as an expression but a standalone operator is
not an expression. Some examples of valid expressions
are given below.
(i) num – 20.4 (iii) 23/3 -5 * 7(14 -2)
(ii) 3.0 + 3.14 (iv) "Global"+"Citizen"
Precedence of operators
An an expression contains more than one operator, their
precedence (order or hierarchy) determines which operator
should be applied first. Higher precedence operator is
evaluated before the lower precedence operator. In the
following example, '*' and '/' have higher precedence than
'+' and '-'.
Note: Parenthesis can be used to override the precedence
of operators. The expression within () is evaluated first.
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
For operators with equal precedence, the expression is
evaluated from left to right.
How will Python evaluate the following expression?
20 + 30 * 40
Solution: #precedence of * is more than that of +
= 20 + 1200 #Step 1
= 1220 #Step 2
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
How will the following expression be evaluated?
15.0 / 4.0 + (8 + 3.0)
Solution:
= 15.0 / 4.0 + (8.0 + 3.0) #Step 1
= 15.0 / 4.0 + 11.0 #Step 2
= 3.75 + 11.0 #Step 3
= 14.75 #Step 4
Statement
It is a programming instruction that does something i.e.
some action takes place.
Example
print (“Welcome to Python class”)
The above statement call print function When an
expression is evaluated a statement is executed
i.e. some action takes place.
a=100
c = b + 20
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Comments
Comments are used to add a remark or a note in the
source code. Comments are not executed by interpreter.
They are used primarily to document the meaning and
purpose of source code.
In Python, a single line comment starts with # (hash
sign).
Python supports 3 ways to enter comments:
1. Full line comment
2. Inline comment
3. Multiline comment
Full line comment
Example:
#This is program of volume of cylinder
Inline comment
Example
area = length*breadth # calculating area of rectangle
Multiline comment
Example 1 (using #)
# Program name: area of circle
# Date: 25/07/2020
#Language: Python
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Multiline comment (using “ “ “) triple quotes
Example
“““
Program: Write a Python program to find the sum of
two numbers
Date: 25/07/2020
Logic: by using addition operator ”””
Input and Output
Sometimes, we need to enter data or enter choices into a
program. In Python, we have the input() function for
taking values entered by input device such as a keyboard.
The input() function prompts user to enter data. It
accepts all user input (whether alphabets, numbers or
special character) as string.
The syntax for
input() is:
variable = input([Prompt])
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Example
>>> sname = input("Enter your first name: ")
Enter your first name: Rishaan
>>> age = input("Enter your age: ")
Enter your age: 4
We can change the datatype of the string data
accepted from user to an appropriate numeric value.
For example, the int() function will convert the
accepted string to an integer. If the entered string is
non-numeric, an error will be generated.
Example
#function int() to convert string to integer
>>> age = int(input("Enter your age: "))
Enter your age: 19
>>> type(age)
<class 'int'>
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)
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Statement Output
print("Hello") Hello
print(10*2.5) 25.0
Function
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.
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
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Python program by importing the module using import
command.
Use of built-in functions makes programming faster and
efficient.
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. A function performs operations on the basis
of argument (s) passed to it and the result is passed back
to the calling point. Some functions do not return any
value.
Let us consider the following Python program using three
built-in functions input(), int() and print():
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
#Calculate square of a number
num = int(input("Enter the first number"))
square = num * num
print("the square of", num, " is ", square)
Some of the most commonly used built-in functions
in Python are listed in Table 3.8 under four broad
categories.
Table below Some commonly used built-in functions
in Python
Input/ Datatype Mathematical Other Functions
Output Conversion Functions
bool() abs()
__import__()
chr() div()
input() len()
dict() mod()
print() range()
float() max()
type()
int() min()
def()
list() pow()
ord() sum()
set()
str()
tuple()
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Example
def drawline():
print("=====================")
print("Welcome to Python language")
drawline()
print("Designed by Class XI")
drawline()
Block and Indentation
Group of statement is known as block like function,
conditions or loop etc.
For Example
def arearec():
a = 10
b=5
c=a*b
Indentation means extra space before writing any
statement.
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Punctuators
Punctuators are symbols that are used in programming
languages to organize sentence structure, and indicate
the rhythm and emphasis of expressions, statements,
and program structure.
Common punctuators are: „ “ # $ @ []{}=:;(),.
A Python Program Structure
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
A Python Program Structure
As we have seen in above figure, a program contains
following components-
Expressions like a+b, a>b etc.
Statements like a=10, c=a+b etc.
Comments, lines starting with #.
Function, block starting with def keyword
Blocks and indentation like if and else blocks
Debugging
Due to errors, a program may not execute or may
generate wrong output. :
1. Syntax errors
2. Logical errors
3. Runtime errors
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
Syntax Errors
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.
For example, parentheses must be in pairs, so the
expression (10 + 12) is syntactically correct, whereas (7 +
11 is not due to absence of right parenthesis. 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.
Logical Errors
A 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.
For example, if we wish to find the average of two numbers
10 and 12 and we write the code as 10 + 12/2, it would
run successfully and produce the result 16, which is
wrong. The correct code to find the average should have
been (10 + 12) /2 to get the output as 11.
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION
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”.
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.
RAJESH SUYAL PGT(CS) K.V.ITARANA, ALWAR, JAIPUR REGION