Page 130 - Computer Science Class 11 With Functions
P. 130
Program 6.1 has been presented in the form of two columns. While the second column comprises the lines of
Python code, the first column shows the line numbers of the Python program. The first column does not form part
of the program and is included to explain the program. The first line of the program begins with a hash character.
Python ignores text on a line beginning with the hash character and up to the end of the line. The text beginning with
a hash character is called a comment. Comments are freely used in a program to facilitate the reading of the program.
In line 2, the variable city is assigned the value 'Delhi'. We can also say that the variable city is mapped to the
string object 'Delhi'. Similarly, in line 3, the variable interestRate is assigned the value 9.5. Lines 4 and 5 are
instructions to display the values of variables city and interestRate, respectively. On the execution of Program
6.1, Python will produce the following output:
city = Delhi
interestRate = 9.5
Program 6.2 The result of applying an arithmetic operation is assigned to the variable amount.
01 # Objective: Given the unit price and quantity purchased,
02 # compute and display the amount payable
03 unitPrice = 50.5
04 quantity = 4
05 amount = unitPrice * quantity
06 print('amount =', amount)
When an expression appears on the right hand side of the operator, as in line 5 of program 6.2, Python first evaluates
the expression, and then the assignment operation is executed. Thus, the variable is assigned the value 202.0 on the
execution of the assignment statement at line 5. Finally, the value of the amount is displayed on execution of line 6.
Assign values to variables prior to use: A variable must be assigned a value, before it is used in an expression. Failure
to do so will result in an error, as shown in Program 6.3 below.
Program 6.3 Illustrates another important point that we should be careful to use the variable names consistently.
Switching the variable name itemPrice to price resulted in an error.
6.3
Results in Error as price is
not declared
Traceback (most recent call last):
File "C:\Users\ADMIN\progs\amount.py", line 3, in <module>
amount=price*qty
NameError: name 'price' is not defined. Did you mean: 'print'?
128 Touchpad Computer Science-XI

