Computational Thinking
© CS-DEPT DPS MATHURA ROAD
and Programming - 1
Getting started with Python
XI
Introduction To Python
© CS-DEPT DPS MATHURA ROAD
Python is a general purpose interpreted, interactive, object-oriented programming
language. It was created by Guido van Rossum in the late eighties and early
nineties. It was designed with an emphasis on code readability, and its syntax
allows programmers to express their concepts in fewer lines of code.
2
XI
Features of Python
❖ It closely resembles the English language. It is a programmer friendly language.
© CS-DEPT DPS MATHURA ROAD
❖ It is free and open source, i.e. it is freely available (can be downloaded from
www.python.org). Open source means its source code (complete program
instructions) is also available. You can modify, improve/extend an open source
software.
❖ It is a high level language, interpreter based which means that the Python
interpreter interprets and executes the code line by line. It also makes
debugging easier.
❖ It is an object oriented programming language.
3
XI
Features of Python
❖ Python supports modules and packages, which encourages program modularity
© CS-DEPT DPS MATHURA ROAD
and reuse of code.
❖ It is a platform independent portable Programming Language i.e It can work on
various operating systems like. Windows, Linux/UNIX, Macintosh. Smart Phones.
❖ Python can be used in many diverse fields / applications. Some examples of
these applications are Web application, GUI programming, app development,
Game Development, Database application etc.
❖ It is blessed with a large community.
❖ Python can be used to create desktop and web based applications.
❖ It has a rich standard library (https://docs.python.org/3/library) containing
predefined functions for most of the common operations, and a large number of
predefined modules (https://docs.python.org/3/py-modindex.html) for specific
varieties of functions. This makes programming an easier task.
4
XI
Minuses of Python Language
➢ It is not the fastest language. Since Python is an interpreter based language.
© CS-DEPT DPS MATHURA ROAD
Development time might be fast but execution time is not as fast compared
to other languages.
➢ Python has lesser libraries compared to languages like C, Java, Pearl. At
times they have better and multiple solutions than Python.
➢ Not strong on type binding. It is not strong on catching ‘Type mismatch’
issues. If you declare a variable as an integer, and later store a string in it, it
will not complain.
➢ Because of the lack of syntax, Python is an easy language to program in. But
difficult to convert a program written in Python to another language, since
other languages have a structure defined syntax or a strong syntax. 5
XI
Application Domain
Python is used in many diverse applications. A list of few application areas where
© CS-DEPT DPS MATHURA ROAD
Python is used are:
⬣ Web and Internet development
⬣ Database Access
⬣ Desktop GUIs
⬣ Data Sciences
⬣ Network Programming
⬣ Game and 3D Graphics
6
XI
Python Interface
To develop and execute programs in Python,
© CS-DEPT DPS MATHURA ROAD
the Python interpreter is required to be
installed. Python provides an IDLE (Integrated
Development and Learning Environment) for
typing, debugging, editing and executing the
program.
Python’s IDLE can work in two basic modes :
Interactive mode and Script mode.
7
XI
Interactive Mode
When Python IDLE is activated a window entitled
© CS-DEPT DPS MATHURA ROAD
as “Python Shell” will be displayed on the screen.
This screen refers to the interactive mode of
Python.In this mode, the command, one at a time
is entered right of the Python prompt (>>>) and
Python executes the command there and then and gives
the output.
This mode is useful for testing out individual
statements. However, interactive mode does not
save the command.
8
XI
Interactive Mode
© CS-DEPT DPS MATHURA ROAD
Python
Prompt
To show / edit / rerun prior command in interactive window, the up arrow and down
arrow keys can be used. The up arrow key (↑) can be used to scroll backward through
commands history and down arrow key (↓ ) key to scroll forward.
9
XI
Script Mode
In this mode the python statements are typed in the
© CS-DEPT DPS MATHURA ROAD
editor and saved in a .py file.
Then the Python interpreter is used to execute the
contents from the file.
To activate the script mode , follow the given steps:-
● From the python shell window select
File ->New File. A window entitled as
“Untitled” will be opened where the statements
can be entered.
● Once the program is ready, first save the file
using File->Save as .
The file will be saved using .py extension.
10
XI
Script Mode
● To execute the program select
© CS-DEPT DPS MATHURA ROAD
Run ->Run Module (F5 key) .
The output of the program will be
shown in the Python shell window.
The file has to be saved before its
execution.
11
XI
Basics of the Python Language
Python is a case sensitive language.
© CS-DEPT DPS MATHURA ROAD
It means Python differentiates between upper and lower case alphabets.
For example, Print and print are two different words for Python.
Print is a just a word and not a command, whereas print is a valid command in
Python.
12
XI
Python Character Set
© CS-DEPT DPS MATHURA ROAD
Character set is a set of valid characters that a language can recognize.
Uppercase and Lowercase letters (A-Z, a-z)
Python Character Set
Digits(0-9)
Special symbols like +,-,/,*,//,**,(),[],{},<,> etc.
White spaces - blank space, tabs, carriage return etc
Other characters such as ASCII or UNICODE literals
13
XI
TOKENS
© CS-DEPT DPS MATHURA ROAD
KEYWORDS
IDENTIFIERS
TOKENS
OPERATORS LITERALS
PUNCTUATORS
14
XI
TOKENS
Keywords
© CS-DEPT DPS MATHURA ROAD
Keywords are the words that convey special meaning to the
Python interpreter. These are reserved for special purpose
and must not be used as normal identifier names. In python,
keywords contain lower case letters only.
15
XI
TOKENS
Keywords
© CS-DEPT DPS MATHURA ROAD
False class finally is return yield del
None continue for lambda try while global
True def from nonlocal not with else
as elif if or and assert
break import pass except raise in
16
XI
TOKENS
Identifiers
© CS-DEPT DPS MATHURA ROAD
Identifiers are fundamental building blocks of a program and are
used to name different parts of a program, i.e. variables, objects,
functions, lists, tuples etc.
Variables Objects Functions Lists or tuples
17
XI
TOKENS
Rules for naming Python identifiers:
© CS-DEPT DPS MATHURA ROAD
● An identifier is an arbitrarily long sequence of letters and digits
● The first character must be a alphabet letter or an underscore ( _ )
● Identifier names can contain uppercase alphabets (A – Z), lowercase
letters (a-z), digits (0-9) and underscore.
● No special characters other than an underscore can be used.
● Identifier names are case sensitive and can be unlimited in length
● A keyword or reserved word cannot be used as an Identifier
● Names used for object, function, List, String, Dictionary etc. are
examples of Identifiers.
18
XI
TOKENS
Literals
© CS-DEPT DPS MATHURA ROAD
Literals refer to the data items, which do not change their values
during a program execution (often referred to as constant
values). Depending on the data types of the data items, Literals
can further be categorized into different categories :
String literals, Numeric literals and special literals
19
XI
TOKENS
© CS-DEPT DPS MATHURA ROAD
Literals
String Literals Numeric Literals Special Literals
20
XI
String Literals
The text enclosed within quotes forms a string literal in Python. For
© CS-DEPT DPS MATHURA ROAD
example, ‘a’,’aa’,”a” are all string literals in Python. A string literal is
a sequence of characters within quotes (single, double or triple) .
One can form a string literal by enclosing text in both forms of quotes -
single or double.
Some valid string literals are:
‘Astha’,”Mehra”, ’Hello World’,”Raj’s”, “12345”, “1A2B”,
”a-b-0-d”,”return”
21
XI
String Literals
Types of Strings
© CS-DEPT DPS MATHURA ROAD
Python allows you to have two string types, Single line strings and
Multi line strings.
Single line strings - The strings you create by enclosing text in
single quotes or double quotes are single line strings i.e., they must
terminate in one line.
Example: Valid Single line string
Str1 = ‘hello’
Str2=”how are you”
22
XI
String Literals
Multiline strings - Sometimes you need to store some text spread
© CS-DEPT DPS MATHURA ROAD
across multiple lines as one string. For that Python offers multiline
strings which are created in two ways :
● By adding a backslash at the end of the normal single-quoted/
double quoted strings.
Example: Valid multiline string
Str1 = ‘hello\
Friends’
23
XI
String Literals
● By typing the text in triple quotation marks (No backslash
© CS-DEPT DPS MATHURA ROAD
needed)
Example: Valid multiline string
Str2 = '''Hello World
Welcome'''
24
XI
String Literals
Escape Sequences
© CS-DEPT DPS MATHURA ROAD
Python also allows non graphic characters in string values. Non
graphic characters are those which cannot be typed from the
keyboard directly, example backspace, tab, carriage return etc.
These non graphic characters can be represented by using escape
sequences. An escape sequence is represented by a \ (backslash)
followed by one or more characters.
25
XI
String Literals
Escape Sequences
© CS-DEPT DPS MATHURA ROAD
26
XI
String Literals
Size of String: Each character of a Python string takes 1 byte of memory.
© CS-DEPT DPS MATHURA ROAD
Python determines the size of a string by counting the total character
present in the string. Any escape sequence present in a string will take
one byte of memory.
Example Size
‘\\’ 1
‘abc’ 3
‘\ab’ 2
‘Seema\’s pen’ 11
27
XI
Numeric Literal
There are four types of numeric literals: int (Integer), float (floating-point
© CS-DEPT DPS MATHURA ROAD
numbers), bool(Boolean values) and complex. They have the features of
their given data type.
ex
pl
at
ol
t
flo
in
co
bo
1
2 3
4
28
XI
Numeric Literal
© CS-DEPT DPS MATHURA ROAD
Examples of Numeric Literal
int float complex bool
123 45.68 2+3j True
-912 2.3E+3 9-2j False
433 6.6E-2 -12+7j
29
XI
Special Literal
Python has one special literal called None. The None literal is used to
© CS-DEPT DPS MATHURA ROAD
indicate the absence of a value. It is used to indicate the end of a list in
Python.The None value means “There is no useful information” or “There
is nothing here”.
Example :
value1=1
value2=None
print(value2) #displays None
30
XI
Operators
They are tokens which trigger some computation when applied
© CS-DEPT DPS MATHURA ROAD
to variables or other objects in an expression.
Variables and objects to which the computation applies are
called operands. So an operator requires operands to work on.
45 + 79
OPERATOR OPERAND
OPERAND
31
XI
Operators
Depending on the number of operands , operators are classified as:
© CS-DEPT DPS MATHURA ROAD
OPERATORS
UNARY BINARY
OPERATORS OPERATORS
32
XI
Operators
© CS-DEPT DPS MATHURA ROAD
UNARY OPERATORS BINARY OPERATORS
Unary operator Arithmetic Operators
+
Unary operator Relational Operators
-
Logical Operators
Membership Operators
Assignment Operators
33
XI
PUNCTUATORS
They are symbols used in programming to organise sentence
© CS-DEPT DPS MATHURA ROAD
structures.
Most common punctuators are :
‘ (single quote) \ (backslash) {} (Curly braces)
“ (double quote) () (Parenthesis) @ (at the rate)
# (hash) [] (Square , (comma)
bracket)
: (colon) . (dot)
34
XI
BAREBONES OF A PROGRAM
Expression
© CS-DEPT DPS MATHURA ROAD
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 expressions are given
below:
● 100
● 70-20
● 2.7 + 3.4
● " Hello " + " World "
35
XI
BAREBONES OF A PROGRAM
Statement
© CS-DEPT DPS MATHURA ROAD
Expression represents a value, statement is a programming instruction
that does something, that is, some action takes place.
print(“hello”)
if b>5:
Statement is something that gets executed. Not necessary that
statement produces a value, it may or may not yield a value.
a=10, b=a-10, print(a+3), if b>15:
36
XI
BAREBONES OF A PROGRAM
Comments
© CS-DEPT DPS MATHURA ROAD
Comments are used in Python program to allow the programmer to
insert small explanatory notes or description to enhance readability or
understandability of the program.
Python Interpreter does not execute the code given as comment.
Comments can be given as a Single Line Comment or a MultiLine
Comment
37
XI
BAREBONES OF A PROGRAM
Types of Comments
© CS-DEPT DPS MATHURA ROAD
● Single Line Comment – Single Line comment in Python start with the
# symbol. Anything written after # in a line will not be executed by
Interpreter.
Example :
side=float(input("Enter Side-"))
#calculating area Single line comment
area=side**2
print("Calculated area=",area,end=" ")
38
XI
BAREBONES OF A PROGRAM
Types of Comments
© CS-DEPT DPS MATHURA ROAD
● Multi-Line Comment – Multiple line comment or Block comment can
be entered in Python in two ways
○ By adding # symbol in the beginning of every physical line of
Multi-line comment.
side=float(input("Enter Side-"))
#Calculating
#area of Square
area=side**2
39
XI
BAREBONES OF A PROGRAM
Types of Comments
© CS-DEPT DPS MATHURA ROAD
● Multi Line comment can also be entered as triple-quoted Multi-line
string.Comments enclosed in triple–quotes are known as Doc String.
Triple single quotes(’ ’ ’) or triple double quotes (“ “ “) can be
used to write doc string.
Example:
'''The following statement is used to
display the output My First Python'''
print('My First Python')
40
XI
BAREBONES OF A PROGRAM
Blocks and Indentation
© CS-DEPT DPS MATHURA ROAD
Sometimes a group of statement(s) is part of another statement or a
function. Such a group of statements is called a block or a code block or
suite.
Example
if b<5:
print(“Value of b is less than 5”)
Block
print(“Thank you”)
Four spaces (can be changed) together mark the next indent level.This
is a block with all its statements at the same indentation level.
41
XI
Variables
A variable comes into existence when we assign a value to it. Python is not
© CS-DEPT DPS MATHURA ROAD
"statically typed". We do not need to declare the type of a variable prior to its
use. The moment you assign a value to it, a variable in Python is automatically
created.
It is a "dynamically typed" language, the data type of a variable is dependent on
the type of data which it holds.
The creation of a variable is simple, just use the name of the variable, followed
by the = (equals to) symbol and then the value.
My_Name = "DPS Mathura Road"
The above creates a variable called My_Name, and then assigns the address of
the string literal "DPS Mathura Road" to the variable My_Name 42
XI
Variables and Assignments
© CS-DEPT DPS MATHURA ROAD
If we declare variables like :
a= 23
b=11
name = “GOOD”
a,b,and name become pointers
that store the address of the
locations holding the values 23,
11 and “GOOD” respectively.
43
XI
Variables and Assignments
In Python a variable is a pointer/indicator/locator which stores the address
© CS-DEPT DPS MATHURA ROAD
of a memory location.
For ex., the statement x=3 will store a value 3 in some memory location and
variable x will point to that memory location.
id() function is used to find address of
memory location to which variable is
referring
>>>x=3
>>>id(x) #displays memory address
44
XI
Variables and Assignments
Another statement y=3 will also point to same
© CS-DEPT DPS MATHURA ROAD
memory location.
>>>x=3
>>>id(x) #displays memory address
140004345567654
>>>y=3
>>>id(y) #displays memory address
140004345567654
>>>y=2
>>>id(y) #displays memory address
140004345522222
45
XI
Data types - Integer, Float, String or Boolean
The type of a literal/variable/identifier can be determined by the command
© CS-DEPT DPS MATHURA ROAD
type() in Python as shown below:
>>> type(111)
<class 'int'> Integer type
>>> type(12.45) Float type
<class 'float'>
>>> type(True) Boolean type
<class 'bool'>
>>> type("Hello World") String type
<class 'str'>
46
XI
Declaring Multiple Variables
In Python, we can declare (or assign values to) multiple variables in a
© CS-DEPT DPS MATHURA ROAD
single statement. There are two ways of doing this:
(i) var1, var2, var3, . . ., varn = exp1, exp2, exp3,. . ., expn
This statement assign values of expressions exp1, exp2,…, expn to the
variables var1, var2, . . ., varn respectively.
Some examples are:
>>>a,b,c=65,”Hello”,23.5
# Value 65 will be assigned to variable a
#Value “Hello” will be assigned to variable b
#Value 23.5 will be assigned to variable c
47
XI
Declaring Multiple Variables
© CS-DEPT DPS MATHURA ROAD
Num,Str,Val=10,"Computer",24.6
print("Number = ",Num)
print("Value = ",Val)
print("Text = ",Str)
OUTPUT:
Number = 10
Value = 24.6
Text = Computer
48
XI
Declaring Multiple Variables
(ii) var1=var2=var3= . . .=varn = expression
© CS-DEPT DPS MATHURA ROAD
This statement will assign value of expression to all the variables var1, var2, .
. . ,varn .
For example, the statement
>>>a=b=c=d=0
#assigns value 0 to the variables a, b, c, and d.
Note : A variable is not created until some value is assigned to it.
49
XI
Naming a variable
There are certain rules in Python which have to be followed to form valid
© CS-DEPT DPS MATHURA ROAD
variable names.
Any variable which violates any of these rules will be an invalid variable
name.
The rules are:
(i) A variable name must start with an alphabet (capital or small) or an
underscore (_).
(ii) A variable name can consist of UNICODE alphabets, digits, and
underscore(_). No
other character is allowed.
(iii) A Python keyword cannot be used as a variable name.
Examples of some valid variable names are:
st_name, father_name, TotalValue, Age, Bal_Qty, A123, BillNo9 50
XI
Some invalid variable names :
Invalid Variable Name Reason
© CS-DEPT DPS MATHURA ROAD
roll number Space is not allowed
D.P.S No other character (.) is allowed
9years Variable name should not start
with digit
while while is a keyword, so it cannot be
taken as variable name
No# No special character is allowed
51
XI
Simple Input Statement
In Python, data is input from the user during script execution using input()
© CS-DEPT DPS MATHURA ROAD
function.
The input() function takes one argument (called prompt). This argument is
generally a string prompting the user to enter a value. During execution,
input() shows the prompt to the user and waits for the user to input a value
from the keyboard. When the user enters value from the keyboard, input()
returns this value to the script. In almost all cases, we store this value in a
variable.
Prompts the user
to enter value
>>>name=input(“Enter your name :”)
Enter your name : Anu
The name entered by the user is stored in variable “name”
52
XI
Simple Python Script/Program
© CS-DEPT DPS MATHURA ROAD
name1=input("Enter a name: ")
name2=input("Enter another name: ")
print(name1,"and",name2,"are friends")
OUTPUT : Enter a name: Mohit
Enter another name: Alok
Mohit and Alok are friends 53
XI
Simple Python Script/Program
Program to input two numbers and display their sum and product.
© CS-DEPT DPS MATHURA ROAD
n1 = input("Enter first number: ")
n2 = input("Enter second number: ")
sum = n1+n2
print("Sum of the numbers=",sum)
pro = n1*n2
print("Product of the numbers=",pro)
54
XI
Simple Python Script/Program
OUTPUT :
© CS-DEPT DPS MATHURA ROAD
Enter first number: 10
Enter second number: 20
Sum of the numbers= 1020
Traceback (most recent call last):
File "/Users/monicasahni/Documents/multiplevar.py", line 5, in
<module>
pro = n1*n2
TypeError: can't multiply sequence by non-int of type 'str'
>>>
55
XI
Simple Python Script/Program
© CS-DEPT DPS MATHURA ROAD
We observe the following problems with the above code:
● The sum is not correct. Instead of being added, the numbers are
being joined.
● An error occurred in line 5 of the code (pro = n1*n2). The Python
interpreter is showing it as TypeError and flashes the message
“can’t multiply sequence by non-int of type ‘str’”
The solution is to use function int(), float(), and eval().
56
XI
int() function
This function takes a number, expression, or a string as an argument
© CS-DEPT DPS MATHURA ROAD
and returns the corresponding integer value. Different types of
arguments are treated as follows:
1. if argument is an integer value, int() returns the same integer.
For example: int(12) returns 12.
2. if the argument is an integer expression, the expression is evaluated,
and int() returns this value.
For example: int(12+34) returns 46.
3. if the argument is a float number, int() returns the integer part
(before the decimal point) of the number.
For example: int(12.56) returns 12.
57
XI
int() function
4. If the argument is a float expression, the expression is evaluated, and
© CS-DEPT DPS MATHURA ROAD
int() returns the integer part of this value.
For example: int(12+13/5) returns 14.
5. If the argument is a string containing leading +/- sign and digits only,
int() returns the integer represented by this string.
For example: int('12') returns 12.
6. If the string argument contains any character other than leading +/-
sign and digits, then int() results in an error.
For example:
The following statements will result in errors:
int('12/3'), int('12+3'), int (‘23a’)
58
XI
© CS-DEPT DPS MATHURA ROAD
59
int() function
XI
float() function
This function takes a number, expression, or a string as a parameter and returns
© CS-DEPT DPS MATHURA ROAD
the corresponding float value. Different types of parameters are treated as
follows:
1. if the argument is a number, float() returns the same number as a float.
For example: float(12) returns 12.0, and float(12.46) returns 12.46.
2. if the argument is a numeric expression (arithmetic or algebraic), the
expression is evaluated, and float() returns its value.
For example: float(12+34) returns 46.0, and float(12+3/4) returns 12.75.
3. If the argument is a string containing leading +/- sign and a number in
correct format, float() returns the float value represented by this string.
For example: float ('12.45') returns 12.45.
60
XI
float() function
© CS-DEPT DPS MATHURA ROAD
4. If the string argument contains any character other than leading +/-
sign and floating point number in the correct format, then float()
results in an error.
For example: the following statements will result in errors:
float('12.2.3'),float('67.6-'), float('23+3/5')
5. If no argument is passed, float() returns 0.0
61
XI
© CS-DEPT DPS MATHURA ROAD
62
float() function
XI
eval() function
It takes a string (not a number) as an argument, evaluates this string as a
© CS-DEPT DPS MATHURA ROAD
number, and returns the numeric result (int or float as the case may be).
If the given argument is not a string, or if it cannot be evaluated as a
number, then eval() results is an error.
63
XI
eval() function
© CS-DEPT DPS MATHURA ROAD
1
OUTPUT :
8
False
True
18.75
goodgoodgoodgoodgood 64
XI
print() function
It is a function which is used to display the specified content on the
© CS-DEPT DPS MATHURA ROAD
screen.
Syntax:
print (objects, [sep=’ ‘ or <sep-string> end =’\n’ or <end-string>])
The content, called argument(s) is/are specified within the parentheses.
65
XI
print() function
Python is a case-sensitive language. It means that Python differentiates
© CS-DEPT DPS MATHURA ROAD
between capital and small letters. For example, Print (P capital) and print (p
small) are two different words for Python. Where print is a valid command in
Python, Print is just a word and not a command.
In the print command, if the argument is put within quotation marks (single ''
or double ""), then the argument is displayed as it is.
66
XI
print() function
If the argument is not placed within quotation marks, then the interpreter
© CS-DEPT DPS MATHURA ROAD
tries to evaluate the argument and displays the result. This feature is used to
perform calculations.
67
XI
print() function
If the argument is not placed within quotation marks, then the interpreter
© CS-DEPT DPS MATHURA ROAD
tries to evaluate the argument and displays the result. This feature is used to
perform calculations.
68
XI
print() function
© CS-DEPT DPS MATHURA ROAD
We can also pass more than one argument to the print() function. In such a
case the arguments are separated by commas.
69
XI
print() function
We can also pass more than one argument to the print() function. In such a
© CS-DEPT DPS MATHURA ROAD
case the arguments are separated by commas.
Consecutive arguments are separated by commas(,) in print() function.
70
XI
print() function
We see that space is the default separator of values in the output.If we wish,
© CS-DEPT DPS MATHURA ROAD
we can also specify some other string as the separator using the sep argument
of print() function.
Default separator:
space
Separator: @
Separator: ,
Separator: \n
Separator: \t
71
XI
print() function
If we use sep argument to specify the separator, then it must be specified after
all the values to be printed. Otherwise, the interpreter shows a syntax error. An
© CS-DEPT DPS MATHURA ROAD
example is given:
>>>print(10,20,30, sep=”*”,50)
Syntax Error : positional argument follows keyword argument
72
XI
print() function
print() appends a new line character at the end of the line unless you give your
© CS-DEPT DPS MATHURA ROAD
own end argument.
>>>print(“Good Morning”)
>>>print(“How are you”)
OUTPUT :
73
XI
Programs
© CS-DEPT DPS MATHURA ROAD
1. Write a program to input the radius of a circle and then display the area and
the circumference of the circle.
2. Write a program to input the marks (out of 100) of a student in 5 subjects
and then display the total marks along with the percentage.
3. Write a program to input a number n and then display n2, n3 and n4
4. Write a program to input the values of principal, rate and time and then
print the value of simple interest. SI = (P*R*T)/100
5. Write a program to input the temperature in Celsius and convert to
Fahrenheit using the formula:
F = C*9/5 + 32
74
XI
Programs
6. Write a program to calculate the BMI(Body Mass Index) of a person.
© CS-DEPT DPS MATHURA ROAD
Input the weight of the person in kg and height in meters. BMI is calculated
as kg/m2
7. Find outputs of the following commands in Python:
(i) print("Hello") (ii) print(2+3,34-67) (iii) print("2+3",2+3)
(iv) print ('2+3',2+3,sep="=") (v)print(2**3,3**2,sep='*')
(vi) print(2**3, 2**-3, -2**3, (-2)**3, sep=" and ")
75
XI
Programs
8. Find error(s), if any, in the following statements:
© CS-DEPT DPS MATHURA ROAD
(i) print("three') (ii) Print(3) (iii) print(44'+'56)
(iv) print(3,2 sep=': ') (v) print "wisdom" (vi)print['33+44']
(vii) PRINT("15 August 1947")
76
XI
Simplicity of Instructions:
Sample Program to calculate the area of a circle:
© CS-DEPT DPS MATHURA ROAD
a = float(input("Enter radius"))
b = 3.14 * a * a
print(" Area : ", b)
Program with more meaningful variable names:
r = float(input("Enter radius"))
area = 3.14 * r * r
print(" Area : ", area)
77
XI
Tips to be followed while writing a program
Tips to be used are as follows:
© CS-DEPT DPS MATHURA ROAD
● Avoid clever instructions.
● One instruction per task
● Use standards − Every language has its standards, follow them
● Use appropriate comments
bill = float(input("Enter the bill amount"))
total = bill + (10/100) * bill - (5/100) * bill
print("Total = ", total)
bill = float(input("Enter the bill amount"))
tax = (10/100) * bill
discount = (5/100) * bill
total = bill + tax - discount
print("Total = ", total) 78
XI
Clarity and Simplicity of Expressions
An expression in a Python program is a sequence of operators and operands to
© CS-DEPT DPS MATHURA ROAD
perform an arithmetic or logical computation.
Some examples of valid expressions:
● Assigning a value to a variable
● Arithmetic calculations using one or more variables
● Comparing two values
Be careful while writing such expressions
● Avoid expressions which may give ambiguous results
● Avoid complex expressions
79
XI
Simplicity of Instructions:
● Programs are not written purely for the purpose of executing it once by the
© CS-DEPT DPS MATHURA ROAD
computer, one must write clear instructions so that whosoever reads the
program later (even you yourself!!) should be able to understand. It is common
for the programmers not to understand the logic of their own programs after
some time.
● Maintenance and Modification of such programs would be very difficult.
● Names of variable(s) used in a program must represent or identify the purpose of
their use, they must be simple, short and meaningful.
80
XI
Error in a Program
● Error/Bug: Any malfunction, which either “stops the normal execution of the
© CS-DEPT DPS MATHURA ROAD
program” OR “program execution with wrong results” is known as an error/bug
in the program. Removal of Bug from a program is known as debugging.
There are different types of errors in a Python program:
Syntax error: Like other programming languages, Python has its own rules that
determine its syntax. The interpreter interprets the statements only if it is
syntactically (as per the rules of Python) correct. If any syntax error is present,
the interpreter shows error message(s) and stops the execution there. 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.
Such errors need to be removed before the execution of the program
81
XI
Errors in a Program
A logical error is a bug in the program that causes it to behave incorrectly. A logical
© CS-DEPT DPS MATHURA ROAD
error produces an undesired output but without abrupt termination of the execution
of the program. Since the program interprets successfully even when logical errors
are present in it, it is sometimes difficult to identify these errors. The only evidence
to the existence of logical errors is the wrong output.
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. Surely, 16
is not the average of 10 and 12. The correct code to find the average should have
been (10 + 12)/2 to give the correct output as 11.
82
XI
Errors in a Program
A runtime error causes abnormal termination of program while it is executing.
© CS-DEPT DPS MATHURA ROAD
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. For example, we have a statement having division operation in
the program. By mistake, if the denominator entered is zero then it will give a
runtime error like “division by zero”.
A=int(input("Numerator")) The program shown above will throw
B=int(input("Denominator")) an Exception (ZeroDivisionError),
C=A/B; if user enters 0 for the variable B.
print(C) The program shown above will throw an Exception
(ValueError), if user enters a non numeric value
for example Hello for any of the variables A or B.
83
XI
© CS-DEPT DPS MATHURA ROAD
THANK YOU!
DEPARTMENT OF COMPUTER SCIENCE
84
XI