Python Programming
_ Fundamentals
Kuywords ao the roseoued is
1 INTRODUCTION Which bow a sfeciol waaweng Me 0?
In the previous chapter, we have discussed the two modes of interacting with Python, viz.
Interactive mode and Script mode. A Python program, sometimes called a script, is a sequence
of definitions and commands. These definitions are evaluated and the commands are executed
by the Python interpreter, which is known as Python Shell.
Before moving further, we will discuss Python syntax. Python syntax refers to a set of rules that
defines how users and the system should write and interpret a Python program. If you want
to write and run your program in Python, you must familiarize yourself with its syntax. The
syntax to be discussed constitutes all the basic elements of a Python program along with the
concept of variables and its data types that you should understand first.
In the Python programming language, data types are inbuilt and, unlike in C++, declaration of
variables is not required and memory management is automatically done by Python.
Whatever values we assign to the variables, the data type of the variable will be the same as
the data type of the value. Hence, it is said that Python supports dynamic typing.
TM: Data types are inbuilt in Python and, hence, it supports dynamic typing.
Before discussing in detail about variables in Python, we will first discuss basic elements of
Python, viz. character set, tokens, expressions, statements, operators and input-output, etc.
3.2 PYTHON CHARACTER SET
Character set is a set of valid characters recognized by Python. A character represents any
letter, digit or any other symbol. Python uses the traditional ASCII character set. However, the
latest version recognizes the Unicode character set. The ASCII character set is a subset of the
Unicode character set. Python supports the following character sets:
Letters: A-2, a-z
Digits: 0-9
Special Symbols: space + - /*\ ** OUQ//=
SSD WINDS RA ce
Whitespaces: Blank space, tabs (—), carriage return (.J), newline, formfeed
Other Characters: All other 256 ASCII and Unicode characters
=3.3 TOKENS :
|A token is the
Script that is meaningful to the interpreter.
The following categories of tokens t
identifiers, keywords, literals, operators an
5.
delimiters /punctuators. Punctators ay o
Identifiers: The name_of any variable,
constant, function or module is called an
identifier. Examples of identifiers are: abc, 2 “
x12y, india_123, swap, etc.
Keywords: The reserved words of Python, 4.
which have a special fixed meaning for Operators
the interpreter, are called keywords. No
keyword can be used as an identifier. The rr uence
Python keywords have been listed under
Section 3.5.
Literals/Constants: A fixed numeric or non-numeric value is called a literal. It can be defined,
number, text, or other data that represents values to be stored in variables. Examples oflliterals,
2, -23.6, “abc’, ‘Independence’, etc. They are also known as constants.
Operators: An operator is a symbol or a word that performs some kind of operation on
given values and returns the result. Examples of operators are: +, -, **, /, etc.
Punctuators/Delimiters: Delimiters are the symbols which can be used as ‘Separators of
values or to enclose some values. Examples of delimiters are: () {}[].::
Note: # symbol used to insert comments is not a token. Any comment itself is not a token.
For example, !
Observe the following script and enlist all the tokens used in it. For each token, write is
category too.
#Identify tokens in the script
x=68
y=12
z=x/y
print("x, y, z are:",x,y,z)
Tie
x Identifier/Variable |
Variable |
Variable
“Keyword “|
Delimiter/Operator |
Operator
Literal :
Literal
Literaler
We will discuss these tokens in detail in successive sub-topics. But before that we will look
jnto the concept of variables and data types in Python.
Tam a Python variable.
My name is x and I can point
to an arbitrary object. In this
case to an int object.
3.4 VARIABLES AND TYPES
variable is like a container that stores values that you
can access or change. Variable, as the name suggests, has
heen derived from the word “vary” which means that a
variable may vary during the execution of a program,
ie, the value of a variable keeps changing during the
program execution.
in Python, every element is termed as an object. Hence,
a variable is also an object in Python. Fig. 3.2: A Variable in Python
fariables provide a way to associate names with objects.
a
Through a variable we store the value in the memory of a computer. Variable is a named unit
of storage. A program manipulates its value. Every variable has a type and this type defines the
format and behaviour of the variable.
For example, if we write ==
x= 3 (as shown in the state diagram, Fig. 3.3) a 5 |
it will automatically assign the value 3 to variable named x,
which is an integer. Fig. 3.3: State Diagram of Variable x
Similarly, if we type x = 10 (>>> x=10) and then write x (>>> x) and press the Enter key, it will
display 10 as the output in the Python shell (Fig. 3.4).
File Edt Shel Debug Options Window Help
Python 3.6.5 (v3.6.5:£59c0932b4, Mar 28 2018, 16:07:46) [ ~
MSC v.1900 32 bit (Intel)] on win32
Type "copyright", “credits” or “license()" for more infor
mation.
>>> x = 10
>>> x
10
>>>
Fig. 3.4: Value of Variable x Gets Displayed
The above behaviour exhibits that variable x has been given a value 10, which is stored inside a
memory location with the name x. This statement shall store 10 in x but does not get displayed
until and unless we type x (>>> x).
On typing x, value 10 shall be displayed as the output.Es
p
A
E=]
=|
rs
=
(eI
UOTE LSet
>>
>>>
>>>
>>>
>>>
>>>
xis 4,yis Sand zis 8.
After executing the above lines of the code,
Alternatively, we can type this program in script mode also, but for displaying the valued
variables x, y and z, we need to give print() statement explicitly. print() statement jg weet
display the value assigned to a variable. The print() statement can print multiple values 9"
single line. The comma (,) separates the list of values and variables that are printed,
Now save the code with a suitable file name with the extension .py and then run it (Run.
Run Module or press F5).
"TB progienapapy - C/Users/preeti/AppData/Local/Prog
Fie_E6t_Format_Run_Ojtins Window Hep
lees
ya
ijz=ext+ty
ze=ze1
fom 3
8 a as Sn ore ee tae
Python 3.6.5 (v3.6.5:£59c0932b4, Mar 28 2018,
16:07:46) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for
more information.
>>>
===] RESTART: C:/Users/preeti /appbata/Local/Progra
ms/Python/Python36-32/progl_chap4.py
xis: 4
y is: 5
zis: 8
>>
print ("y is:
print ("2 is:
Fig. 3.5: Running Code inside Script Mode
Let us understand this code line by line:
1, x starts with the value 3 and y starts with the value 4.
2. Inline 3, a variable z is created and equals x + y, which is 7.
3. Then the value of zis changed to one more than it currently equals, changing it from 7 108
4. Next, x is changed to the current value of y, which is 4.
5. Finally, y is changed to 5. Note that this does not affect x.
6. So in the end, x is 4, y is 5 and z is 8,
CTM: print() statement is used to display the value assigned to a variable, The print() statement can
multiple values on a single line. The comma (.) separates the list of values and variables that are pfl
abiariable/object has three main components:
Aw gentity of the Variable/Object
7 ype of the Variable/Object
gj Value of the Variable/Object
Every Object/Varlable has
Fig, 3.6: Components of a Variable
ye shall now discuss each of these associated components one by one.
le
1) Identity of the Variable/Object:
Itrefers to the object's (variable in this case) address in the memory which does
once it has been created. The address of an object can be checked using 1
id (object).
syntax: >>> id(variable/object)
For example, >>> id (x)
not change
the method
python 3.6.5 (v3.6.5:£59¢0932b4, Mar 28 2018, 16:0 *
:46) (MSC v.1900 32 bit (Intel)] on win32
qype "copyright", "credits" or "license()" for mor
e information.
>>> x = 10
>>> id (x)
1614996384
>>>
Address of — memory
location storing value 10
ait Shell Debug Options Window Help
Fig, 3.7: Address of a Variable Using id() Method
B) Type of the Variable/Object (Data type
By type we refer to the data type of a variable. In Python, each value is an object and has
a data type associated with it. Data type of a value refers to the value it has and the
allowable operations on those values. A data type in Python can be categorized as follows:
Data Types
Numbers None Sequences Sets Mappings |
I ] | Dictionary
ae Floating Complex Strings Tuple List
Point
Boolean
Fig.
Data Types in Python‘The above figure shows the data types available in Python. We are going to discys,
e above fig
i as follows: y
fundamental data types available in Python le . som ieasou atari
‘ical values. 3 ‘
: data type stores numerical ¢ ;
1. Seeder aoe really have to declare a numeric value to define is type Pre
a easly differentiate one data type from another when i ee pee 1 statene
Python supports three types of built-in numeric data types: 8 poy
numbers and complex numbers.
integers do not form a separate group of instructions but are included in |
‘ong in
(a) int (integer): Integer represents whole numbers
without any fractional part. They can be positive
or negative and have unlimited size in Python
Thus, while working with integers, we need not : >
worry about the size of the integer as a very big-sized integer is automaticaly
handled by Python.
Examples of integers recognized by Python are: ~6, 793, -255, 4, 0, 23466, 45766782964, et.
While writing a large integer value, do not use commas to separate digits. Also, integers shoul
not have leading zeros.
Learning Tip: An integer jn
Python can be of any length
TM: Range of an integer in Python can be from -2147483648 to 2147483647, and long integer has |
unlimited range, subject to available memory. 5
(b) float (floating point numbers): Floating point numbers denote real numbers or
floating point values (i.e., numbers with fractional
part). Floating point numbers are written with a
decimal point that separates the integer from the
fractional numbers.
Learning Tip: The fractional
Part of a floating point number
can also be 0 (zero),
Examples of floating point numbers are: 3.14, 6202.3, -43.2, 6.0, 28879.26, etc.
cm:
Avalue stored as a floating point number in Python can have a maximum of 53 bits of Precision.
(c) Complex numbers: Complex numbers in Python are made up of pairs of real and
J, where ‘x’ is a float and the
Here are some examples of complex numbers:
() >>> x= 2455
>>> print (x.real, x.imag)
2.05.0
(li) >>> y = 4 - 25
>>> print(y.real, y, imag)
4.0 -2.0
i) >>> z=x+y
>>> print(z)
(6 + 33)
UTES Gee ae Gs UeFis &_Shel_ Dug OptersWincow na
python 3.6.5 (v3.6.5: £55c695;
aba,
v.1900 32 bit (Intel)} on winga’ “28 2018,
m ar n32 1 16507346) tase
pe SoPyFAGhe", “credits” or "1icense y= :
pop x2 + 53 ‘Or more informati
de> print (x.real, x.imagy
2.0 5.0
py e423
So> print (y-real, y.imag)
Fig. 3.9: Handling Complex Numbers
¢onplex numbers are not extensively used in Python programming
2, str (string): A string is a sequence of characters th:
numbers and special symbols, enclosed within quotati
(‘or or”). These quotes are not part of the stri
ending of the string. A string may have any character,
Forexample, >>> str = “Hello Python"
>>> print(str)
Hello Python
‘at can be a combination of letters,
ion marks, single or double or triple
ing. They only define the starting and
sign or even space in between them.
CCM: String literals in Python are defined by enclosing text in either type of quotes—single quotes or
double quotes. Multiline strings can be represented by using even triple quotes (").
Escape Sequence
dython allows us to represent a string constituting non-graphic characters as well. Non-graphic
characters are those characters which cannot be directly typed from the keyboard, such as
backspace, tab spaces, carriage return, etc. These non-graphic characters are represented by
‘sng escape sequences. An escape sequence is represented by a backslash (\) followed by one
ormore characters,
Itmust be remembered that an escape sequence is represented as a string with one byte of
‘emory. The following table (Table 3.1) lists escape sequences supported by Python.
Table 3.1: Escape Sequences in Python
NY Backslash(\)
. Single quote (’)
“ Double quote (")
. ASCII Bell (BEL)
we, ‘ASCII Backspace (BS)
Me ASCII Formfeed (FF)
" {ASCII Linefeed (LF)
ASCII Carriage Return (CR)
£ ASCII Horizontal Tab (TAB)
ty ASCII Vertical Tab (VT)
ry
Fy
5
ie
Ss
5
te
iS
=
3
g
a
£
ts
A
Fd
=of the two possible values_,
5. : Boolean data type represents one
3. bool (Boolean): of ers
False. Any expression which can be True or False ha:
CIMA Boolean True value is non-zero, non-null and non-empty.
bop Wns HP
python 3.6.5 ee gcysaTA, War 28 2018, 16:07546) (HSE
Pyreg a2 bit. (intel) } on win32
151900 Seyrignt", neredits” or "nicense()
one
Baers |
333 print (x.zeal, x-imag)
20 5.0
So pea 2
33 felotiy-reat, y-imag)
eo #2.0
Ssoiereety
print (2)
for more informati
Fig, 3.10: Handling boo! (Boolean) Data Type
Examples of Boolean expressions are:
> >>> bool_1 = (6>10)
>>> print (bool_1)
False
> >>> bool_2 = (10<=20)
>>> print (bool_2)
True
4. None: This is a special data type with a single value. It is used to signify the absencet
value/condition evaluating to false in a situation. It is represented by None. Python doit
display anything when we give a command to display the value of a variable containing
value as None, On the other hand, None will be displayed by printing the value oft
variable containing None using print() statement.
For example,
>>> valuel = 20
>>> value2 = None
>>> valuel
20
>>> value2
>>>
Nothing gets displayed. Alternatively, print() statement can be used to display None val
shown below:
>>> print(value2)
Nonecan Shel Debup Options Wndow Hep
python 3.6.5 (v3.6.5:£59c0932b4, Mar 28 2018, 16:0
6) (MSC v-1900 32 bit (Inte1)] on win32 F
ype "copyright", "credits" or "license()" for more +
nformation.
>>> valuel = 20
5>> value2 = None
>>> valuel
20
>>> print (value2)
None
>>>
Fig, 3.11: Handling None
3.4.1 type()
iryou wish to determine the type of a variable, ie, what type of value does it hold/point to,
then type() function can be used.
For example,
Fae ae Sra Oey Options Won Hep
Se pee ENCE ETT OE LSE
Type "copyright", "credits" or “License()" for more informatio "|
a
>>> type (10)
>>> type (8.2)
jeclass '£loat'>
>>>. type (22/7)
"£loat'>
>>> type ('22/7')
[>>> type (-18.6)
>>> type ("Hello Python")
eeiaes easter The Boolean argument given
> type (true) | to. type() function should “have
> taney T (capital letter) for True and
ena E212) | F (capital letter) for False; otherwise
>>> type (895) it will generate an error.
>>>ernatively typed as follows:
‘The above code can be alt
mn wind
ntel)] 2
"license()" £
¢ Or more inform
wcredits" OF
o> x = 30.5
>>> print (x)
30.5
>>> type (x)
>>> x = "HI"
>>> type (x)
>>>
Let us take another example for type()-
Different types of values can be assigned as
xyz = “Hello”
w=18
pi = 3.14 159
c= 3.2+1.55
Since values have types, so every variable will also have its type. Now we will give the folloy
type() statements for the above values and will observe the output for it (Fig. 3.12), my
under:
type (xyz)
type (w)
type (pi)
type (c)
Python
File Est Shel Debug Oplont Window Help
v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more informati
on.
>>> xyz = "Hello"
>>> w= 18
>>> pi = 3.14159
p33 c= 3.2 + 1.55
>>>_type (xyz)
>>> type (w)
>>> type (pi)
>>> _type(c)
>>>
ered
Te co
Fig, 3.12: Use of type() Function
Es
p
A
Bi
=
<
POT ae aad-
¢) Value of the Variable /Object:
variables provide a means to name values so that they can be used and manipulated later
To bind value to a variable, we use assignment operator (=). This process is also terme
as building of a variable.
the assignment operator (=)
i ‘ —— the variable
ues are assigned to variables using assignment operator (=), | ¥@thS —ewane of the vers
For example, consider the statement,
>>> Maths = 87
>>> print (Maths)
Vall
87 |» vaiue of the variable
‘The statements shall yield the output as shown below:
File Edt Shell Debug Options Window “Help
Python 3.6.5 (v3.6. '59c0932b4, Mar 28 2018, 1 *
6:07:46) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for
more information.
>>> Maths = 87
>>> print (Maths)
87
>>>
In the above example, Python associates the name (variable) Maths with the value 87, i.e., the
name (variable) Maths is assigned the value 87 or, in other words, the name (variable) Maths
refers to value 87. Values are also called objects.
In an assignment statement, the variable that is receiving the value must appear on the left
side of the = operator, otherwise it will generate an error.
Forexample, >>> 87 = Maths #this is an error
Or we write x = 10, which means assigning value 10 to variable x. Similarly, we write another
assignment statement as number_1 assigned with value 100, i.e., number_1 = 100, as shown in
the state diagram given below.
ie rT
Vain, lene N
Fig. 3.13: State Diagram of an Assignment Operator
The concept of assignment can be explained as:
There should be one and only one variable on the left-hand side of the assignment operator.
This variable is called the Left value or the L-value. There can be any valid expression on
. ight-hand side of the assignment operator, This expression is called the Right value or
‘value,The statement
L-value = R-value
is called the assignment statement, When the interpreter encounters an assignment stay,
it evaluates the right-hand side expression (R-value) and assigns the value to the let.)
variable (L-value). sig
|
A statement is an instruction that the Python interpreter can execute. For example, Pring a4
a statement and Python executes it and displays the result if there is one. The result o¢ a
statement is a value. Assignment statements do not produce a result. Pring
there is more than one s
tatem,
en
A Python script usually contains a sequence of statements. If t
the results appear one at a time as the statements execute.
el ean place data iato/a variable By ASSIGNING It %0))
ariable, fal
variable None (a
@ Gi) (iii)
Consider two variables, x and y, and we type the following assignment statements:
x = 3. #-variable ‘x’ is assigned 3 as value, refer to Fig. (i)
y = 3 # variable y’is also assigned value 3, so nowy shall be pointing to
x only, refer to Fig. (ii)
y = 2 # variable ‘y’ is assigned another value 2, refer to Fig. (iii)
Now the final value of y becomes 2 and that of x remains 3 as assignment operator erases
the previous value and assigns new value to the variable ‘y’. Thus, it becomes evident that W?
can use assignment operator for assigning values to a variable along with their reassignme™™
Ar
a2 multiple Assignments
4 son, we can declare multiple variables in a single statement. It is used to enhance the
pytl .
in of he Program
ultiP
o
re assignments in Python can be done in the following two ways:
signing multiple values to multiple variables:
‘varl, var2, var3,..., varn = valuel, value2, value3,. . ., valuen
pis statement will declare variables vari, var2. .. varn with values as value1, value2... value
repeetive A :
For example, msg, day, time = ‘Meeting’, 'Mon', '9
Another statement, x, y = 2, 3 bindsxto2 andy to3.
_» assigning same value to multiple variables: .
i} yarl=var2=var3=...=varn = valuel
This statement will declare variables var1, var, ..., varn, all with value as value.
For example, totalMarks = count = 0
ype "copyright", "credits" or "License()" for more informat
ion.
X/¥iZ/P = 2, 40, 34.5, "Vinay"
YZ.
40, 34.5, 'Vinay")
x+y
x-y¥
asb=c=-55
aybyc
(55, -55, ~55)
Fig. 3.15: Multiple Assignments in Python
3.4.3 Variable Names
There are certain rules in Python which have to be followed to form valid variable names. Any
variable that violates these rules will be an invalid variable name. The rules to be followed are:
() A variable name must start with an alphabet (capital or small) or an underscore
character (_).
(i) A variable name cannot contain spaces.
(ii) A variable name can contain any number of letters, digits and underscore (_). No other
characters apart from these are allowed.
ES
Fa
iS
is
5
fr
Sy
€
&
S
Ey
£
cs
5
A
F=s
=
=
(iv) A Python keyword cannot be used as a variable name.
(*) Variable names are case-sensitive, ie., name and NAME are two different variables.
(i) You should always choose names for your variables that give an indication of what they
are used for. In other words, the name should reflect its functionality. For example, a
variable that holds the temperature might be named temperature, and a variable that
holds the speed of a car might be named speed instead of giving x and b.
.python are!
Tota Age, amount, A24, inyg
mes in
Examples of SO ple na
father
unit_per-
ii mes:
r e exam valid variable 92
Following a" nae
me
eo ‘annot start with
Name ©
special symbol (#) is not allowed
llowed in between
Marks,
e valid varia
le name,
some practical
ple 1: Write a Pyth
Exam)
Solution:
nl = input ("Enter firs number?
ni = eval (nl) |
n2 = input ("Enter second number? |
nz = eval (n2)
sum = nl+n2
print ("Sum of the numbers="/ sum)
prod = nl*n2
print ("Product © ", prod)
£ the numbers=
certain average speed
Example 2: A student has to travel a distance of 450 km by car at ac
Write Python script to find the total time taken to cover the distance.
Solution: e
We know that time taken to cover a di
Time = Total Distance/Average Speed
In this problem, we need a data value (av
calculated. So, this value has to be inputte
istance is calculated as:
erage speed) which is not given and neither canitbt
d by the user. ;
Code is:
Distance=450
Speed-eval (input ("Enter average spee!
‘Time=Distance/Speed
P #Calculate time taken
)) #to input speed from the us
print ("Time taken:", Time, "hr")
Example 3: Write a P:
-ython code to calculate si
te sim] i i it ind
amount and rate from the user for a time erate ae byseeatind eon 7
Solution:
Using the formula:
Simple Interest = Principal x Rate x Time/100
pecode:
principal=eval (input ("
inter the value of Principal
"))
"Enter the annual rate of interes:
Rate=eval (input (
Time=5
simple_Int = Principal*Rate*Time/100
amount = Principal+Simple_Int
print ("Simple Interest. =, Simple Int)
print ("Amount payable = %", Amount)
Example 4: Write a program to convert the time inputted in minutes into hours and remaining
minutes.
solution:
time=int (input ("Enter the time in minutes
hours= time/60
mins= time&60
print ("Hours are:", hours)
print ("Minutes are:",mins)
3.5 KEYWORDS IN PYTHON
Keywords are different from variable names. Keywords are the reserved words used by Python
interpreter to recognize the structure of a program. As these words have specific meanings
for the interpreter, they cannot be used as variable names or for any other purpose. For
checking/displaying the list of keywords available in Python, we have to write the following
two statements:
import keyword
print (keyword. kwlist)
Fle_E6t_Shell_Debug Options Window Help
Python 3.6.5 (v3.6.5:£59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 ~
32 bit (Intel)] on win32
Type "copyright", “credits” or "license()" for more information.
>>> import keyword
>>> print (keyword. kwlist)
('False', ‘None’, ‘True’, ‘and', 'as', ‘assert’, ‘break’, ‘class', '
continue', ‘def, ‘del’, ‘elif', ‘else’, ‘except’, 'finally', 'for',
‘from', ‘global', 'if', ‘import’, ‘in’, ‘is', ‘lambda', ‘nonlocal’,
‘not', ‘ort, 'pass', ‘raise’, ‘return’, ‘try’, ‘while’, 'with', "yi
eld")
>>>
3.16: Keywords in Python
TM: All these keywords are in small alphabets except for False, None and True, which start with capital
alphabets,
is
FA
=
i
Bi
bo
2
Python ProgrammiEs
5
A
=
=|
a
=]
=
ra
EF
=
a
CONC TU
3.6 MUTABLE AND IMMUTABLE TYPES
require changing 0
a types, Pytl
eated and assign
+ they are created and assigned values arg cy
Calleg
+ updating the values of certain variables
hon does not allow us to change thes Ug |
In certain situations, we may
ed values. Value |
in a program. However, for certain dat
‘once a variable of that type has been cr
Variables whose values can be changed afte!
mutable variables.
.s whose values cannot be changed a
When an attempt is mat
ed and a new variable is creat
fter they are created and assigned values are
de to update the value of an immutable mats
‘ed by the same name in mem
Variable:
immutable variables.
the old variable is destroy
Python data types can be classifie
> Examples of mutable objects:
.d into mutable and immutable as under:
list, dictionary, set, etc.
int, loat, complex, bool, string, tuple, ete.
> Examples of immutable objects:
ated, cannot be modified.
For example, int is an immutable type which, once cre
Consider a variable ‘x’ of integer type:
pop x =5
Now, we create another variable ‘y’ which is a copy of variable ‘x.
>>> y =x
‘The above statement will make y refer to value 5 of x.
Identifiers x and y point to the same object.
We are creating an object of type int
x=5
‘This statement will create a value 5 referenced by x.
x
> 5
bs
Now, we give another statement as:
pop xexty
‘The above statement shall result in adding up the value of x and y and assigning to x
Thus, x gets rebuilt to 10.
x——> 10
y—>5
The object in which x was tagged is changed. Object x =
object doesn't allow modification after creation. Another example of immutal
5 was never modified, An immutable
ble object
isa string.
‘trings immutable"
>>> str =
>>> str(0] = 'p’
>>> print (str)tement shall result in TypeError on execution.
his + object does not support item assi
srror: ‘str’ obje PP assignment.
el . a ji
cause of the fact that strings are immutable. On the contrary, a mutable type object
is bet -
isis De can be modified even after creation, whenever and wherever required.
sis is
uch 5
FT ist © (20, 20 39)
nev
ist)
(new lis
prin
output:
10, 20/301
pose we need to change the first element inthe above list as:
uP
pow 13st 7 (10r 207 30]
pew 1ist(0} =100
prine(new.His) will make the necessary updation in the list new_list and shall display the
output ast
(100, 20/30]
n is successful since lists are mutable.
python handles mutable and immutable objects differently. Immutable objects are quicker to
access than mutable objects. Also, immutable objects are fundamentally expensive to “change”
because doing so involves creating a copy. Changing mutable objects is cheap.
‘This operatio!
3.7 EXPRESSIONS value/Operands
Anexpression is a combination of value(s), ie., constant, variable
and operators. It generates a single value, which by itself is Vig
an expression. Operands contain the values an operator uses
operator
and operators are the special symbols which represent simple
calculations like addition, subtraction, multiplication, etc.
Fig. 3.17: An Expression in Python
5+274 13
10/2-3 2
B4+12*2-4 28
6-3°%2+7-1 6
> Converting Mathematical Expressions to Equivalent Python Expressions
ihe mathematical expressions that we use in- algebra are not used in the same manner in
computes In maths, you use different operators for mathematical calculations. On the other
, Python as well as other programming languages require different operators for any
Mathematical operation.
For example,
TESA Expression | Operation Being Performed | Programming Expression
3 6 times B 6*B
ake 3 times 12 ae a12
y 4 times x times y ASAXDSSY) ae
ieto programming expressions, you may
a ha
Igebraic expression as shown in the tab vel
When converting some algebraic expression: ;
bis
insert parentheses that do not appear in the al
below:
Apne Pubes cucu
i oh
y=3r*x/2
(3)
2,
y
3tbtc+4
be + 4 z
2 a a=w+2/(b-1)
Be
a= pa
In all the above examples of expressions,
the most important element used is “Operator
which we will discuss now.
3.8 OPERATORS
Operators are special symbols which represent computation, They are applied on operand,
which can be values or variables. Same operator can behave differently on different datatype,
Operators when applied on operands form an expression.
Operators are categorized as Arithmetic, Relational, Logical and Assignment, Value ang
variables, when used with operators, are known as operands.
3.8.1 Mathematical/Arithmetic Operators
‘Anumber of operators are available in Python to form and solve arithmetic or algebraic expression,
Table 3.2: Arithmetic Operators in Python
SL
Zs ‘Addition >>> 55445 >>> ‘Good! +
100 GoodMorning
- Subtraction >>> 55-45 >>> 30-80
10 -50
B Multiplication >>> 5545 >>> 'Good'*3
2475 GoodGoodGood
a Division >>>17/5 >>> 28/3
3.4 9.33333333,
Sea 333333334
3.4
>>> 17.0/5
3.4
% Remainder/ >>> 1785
Modulo 2 Ree poe?
Ee Exponentiati >>> 2ee
‘ponentiation eee >>> 244g
>>> 16*e 5 B56
4.0
Wy Integer Division >3>. 7.9772
3.0 peas /if2)
1#Addition
#Subtraction
#Multiplication
#Division
#Integer Division
#Modulus
#Exponentiation
#Exponentiation
Concatenating Strings
srrings can be added together with the plus (+) operator. To concatenate the string “Hello
python’, give the statement using concatenation operator (+):
>>> "Hello" + "Python"
Output:
'HelloPython'
>>> print ("'how! + tare’ + "you?
, thow! + tare! + 'you?')
Output:
*how' + 'are' + 'you?
Similarly, entering "*****" * 5 will yield:
: howareyou?
>>> print (""hello' * 5 :", 'hello' * 5)
Output:
‘hello' * 5 : hellohellohellohellohello
Unary and Binary operators: An operator can be termed as unary or binary depending
upon the number of operands it takes. A unary operator takes only one operand and a binary
operator takes two operands. For example, in the expression ~6 * 2 + 8 - 3, the first minus sign
‘saunary minus and the second minus sign is a binary minus. The multiplication and addition
operators in the above expression are binary operators.
Precedence of Arithmetic Operators
() (parentheses)
“* (exponentiation)
= (negation) decreasing order
1 (division) // (integer division) * (multiplication) % (modulus)
+ (addition) - (subtraction)UT aoe aA Ue Lt oe
More Examples of Arithmetic Operators
Evaluate the following expressions:
(1) 12+3*4-6/2
(4) 12+ (3 4-6)/2
Solution:
(1) 12+3*4-6/2
=12+12-6/2
=12+ 12-30
= 24-30
=21.0
(4) 124+ (8% 4-6)/2
= 12+ (81-6) /2
=12+75/2
=12+375
= 495
3.8.2 Relational Operators
Relational operators are used for comparing two expressions and result in either True
In an expression comprising both arithmetic and relational operators,
«4-6/2
(2) (12 +3)*4-6
(5) 12° B%4)//2+6
(2) (12+3)*4- 6/2
=15*4- 6/2
=60-6/2
60 - 3.0
= 57.0
(5) 12*(3%4)//2+6
=12*3//2+6
= 36//2+6
=18+6
=24
have higher precedence than the relational operators.
Syntax:
Table 3.3: Relational Operators in Python
Lewermersamrlez |
< less than
> greater than
less than equal to
greater than equal
to
>>> 7<10
True
>>> 71<5
False
>>> T<10<15,
True
>>> 7<10 and 10<15
True
>>> 75
True
>>> 10>10
False
>>> 2<5
True
>>> T<=4
False
>>> 10>=19
True
>>> 1L0>=12
False
(3) 12+3%q_,
6)
(6) 12% 3% vad
*
3) 1243+.)
12434,
oe can
= 12-39 &
9.0
(6) 12% 3% Ws.,
= 12%81//5 , é
= 12//5 +6
=2+6
OF Fal,
the arithmetic Operators
>>>
False
>>> "Goodbye'<'Hello!
True
ello
Goodbye
>>> 'Hello'>' Goodbye!
True
>>> 'Goodbye'>"Hello!
False
>>> 'Hello'<="Goodbye!
False
>>> 'Goodbye'<="Hello!
True
>>> "Hello!
True
>>> 'Goodbye'>="Hello’
False
"Goodbye!mete sss torent SSSWHSIVOMIE HELLO NNT
ee True True
>>> 10!=10 >>> 'Hello'!='Hello'
False False
equal to >>> 1 >>> 'Hello'=="Hello!’
a True True
>>> 1 >>> 'Hello'=='Good Bye!
False False |
ample,
fore print ("23 < 25 2%, 23 < 28) #less than
>
> print ("23 > 25 :", 23 > 25) #greater than
>
23 2", 23 <= 23) #less than or equal to |
go> print ("23 <=
-2.5>=5*4:", 23-2.5>=5*4) #greater than or equal to
go> print ("23 == 25 2", 23
nt ("23 != 25 2", 23 != 25) #not equal to
go> print ("23
25) #equal to
po pri
output
23< 25: True
23> 25 : False
23 <= 23 : True
23-2.5>=5*4: True
23 == 25 : False
23 !=25 : True
+ When the relational operators are applied to strings, strings are compared left to right,
character by character, based on their ASCII codes, and also called ASCII values.
print ("'hello' < "Hello' :", 'hello' < 'Hello')
print (""hi' > hello’ :", ‘hi! > 'hello')
Output:
"hello' < 'Hello' : False
‘hi! > ‘hello : True
Python starts by comparing the first element from each sequence. If they are equal, it goes
on to the next element and so on until it finds elements that differ. Subsequent elements
are not considered (even if they are greater).
a
or If any one of the operand is true, then the condition becomes true.
and If both the operands are true, then the condition becomes true.
not Reverses the state of operand/condition.
For example,
>>> print ("not True < 25 :", not True) #not operator
>>> print ("10 < 25 and 5>6
>>> print ("10 < 25 or 5>6
",10<25and5>6) #and operator
, 10<250r5 >6) for operatorUTE Ca LU lier A
Precedence of Logical Operators
not Decreasing z
and order a
or 3
i tors and yield values,
CTM: Relational operators are also known as Comparison operat yi True oF Fah
the output. i
3.8.3 Shorthand/Augmented Assignment Operators :
A Shorthand Assignment Operator (or compound assignment ore ay or an aUgMeny
operator) is a combination of a binary operation and assignment. Different augment
assignment operators available in Python are as follows:
Note: We assume the value of variable x as 12 for a better understanding of these operat,
Table 3.4: Shorthand/Augmented Assignment Operators in Python
+= added and assign back the result to left operand x+=2 —_The operand/expression/con
written on RHS of operator
change the value of x to 1
-= subtracted and assign back the result to left operand x-= x will become 10
lied and assign back the result to left operand x*=2 x will become 24
/= divided and assign back the result to left operand x/=2 x will become 6
%= taken modulus using two operands and assign the x will become 0
result to left operand
""= performed exponential (power) calculation on x**=2 x will become 144
operators and assign value to the left operand
M= performed floor division on operators and assign x//=2 x willl become 6
value to the left operand
For example,
Shorthand Notation:
a= a b is equivalent to
a = b
a=6
azats Learning Tips:
print (a) 1. Same operator may perform?
a=6 different function depending
on the data type of the val?
onear to which it is applied.
print (a) 2. Division operator */” behave
differently on integer and fst
Output: values.
11
1T AND OUTPUT
, we need to fetch some input from the user. The values inputted by
stored in the variables. Python provides three important functions
guseR INU
5 . ram,
"writing 2 PFS!
write are fetched and
» ving user's input.
for at: input() function is used to get data from the user while working with the
4. inp Jes us to accept an input string from the user without evaluating its value.
ci mode. It enabl ; ;
- function input continues tO read input text from the user until it encounters a new line.
eng simple example to fetch user's name and to display Welcome message
ss Stped with user’s name, The input) function takes String as an argument During
conca jon, input() shows the prompt to the user and waits for the user to input a value
Ce Hoard. When the user enters value from the keyboard, input() returns this
from the key!
value to the script mode. In almost all the cases, we store this value in a variable.
Let us se
he first statement of the above example is executed, the user is prompted to enter his/her
ent j e p ‘
whe ame entered by the users stored inthe variable name After this, the variable name
tare bined with the ‘Welcome’ message and can be used as many times as needed.
6
Bprop2idonaoy- oa
fie tart Rin_Optons_ dow
Gane = input Center your Nane
print (*#elcone', name)
Python 3.6.5 (v3.6.5:f59c0992b4, Mar 28 2018 |*
P¥y¢s07:46) (HSC v-1900 32 bit (Intel)] on W
4n32
Type “copyright”, “credits” or “License ()" f
or more information.
>>
RESTART: C:/Users/preeti/AppData/Local/Prog
rans /Python/Bython36-32/prog2_chap4.PY
Enter your Name : Sonia
Welcome Sonia
Forexample, the program given below is for adding the two values inputted by the user through
input() function.
Shel Debug _Optons_Window Hele
Python 36.5 (w3.6,5:55C0932b4, War 28 2018, 16:07:46) [MSC v.90
032 bit (intel)] on win32
Irype "copyright", "credits" or
>>> num_i= input ("Enter first number: ")
Enter first number: 30
>>> num_2 = input ("Enter second number: ")
Enter second number: 40
>>> result = num_1 + num_2
>>> print ("sum is: ",result)
"License ()" for more information.
eat inthe above figure, we are getting unexpected output on execution. As per the Progra
geting soy output was 70 after adding the two inputted numbers 30 + 40. But instead we are
ent 3040, which signifies that 30 and 40 are fetched as strings and not as numeric value and
‘act as concatenation operator instead of mathematical addition operator.93 apa py = CsenfpeesAppOnaoa Fog"
num I= int (input ( =p
fpuR=2 = int (input ("Encer second numer+ "))
result = nunt + num 2
print ("sun 45 :",resait)
Tart Soong Opors Wor Fe
Sea Sa v3.65: F55CUSIDDN, War Ze 2018, 16507
Fyeneee veigod 32 pit (sntel)) on vind?)
ose nyrignt™, veredita’ oF "License()" £0r more £
formation.
22 eqnt: ¢:/0sers/preeti /appoata/Local/Prograns/Pyth
chap PY
Hence, we need to modify our program using another function int).
int() function converts the inputted striny
as a number and notas a string. Thus, we
2. eval(): This function is used to evaluate the v:
evaluates this string as a number, and retur
or if it cannot be evaluated as a number, then
‘ns the numeric result.
If the given argument is not a string,
results in an error.
For example,
a eval ("15+10'
print (a)
Output:
25
tet Shet_Osbey_Opters Window ee
GT eraTLSSCUSSZOT, MAT ESTOTE TS) TSS VE
i)1 on win32
2 tespyright™, “credits” or “License ()" for more information
>>> eval ("15")
15
>>> eval ("00")
80
>>> eval ("54.67")
54.67
55 eval ("4"545")
sa Error: Argument is not a string
Fraceback (most recent call. la:
File "", Line 1,
‘eval (15)
nypetrros: eval () azg 1 must be a string, bytes or code object
>>> eval ("ietovote")
Traceback (most recent™cal) last):
Bile "epyshell#s>", Lin, in
‘eval ("18tovote”)
File "", line 1
‘etovote Error: Argument cannot be evaluated as a number
st
‘in
syntaxerror: unexpected EOF while parsing
In all of the above programs, we have used built-in functions available in Python libra!
performing numeric and string operations.
We have already discussed output function (print()) in the previous chapter.
g value into numeric value and shall store the vale
‘will obtain the desired result as 70 (sum of 30 ang .
alue of a string. It takes string as an argumeny
eval(
ry ftyPE CONVERSION (TYPE CASTING)
or ene change the data type of a variable in Python from one type £0
: io rsh idata type conversion can happen in two ways:
er
7 ae (forced) when the programmer specifies for the interpreter to convert a
7 iO 7 into another type; oF
at another
ant Oy, when the interpreter understands such a need by itself and does the type
«ample sion aucomatically-
0
state conversion
version, also called type casting, happens when data type conversion takes place
Explicit © ne, |
" the programmer forces it in the program. The general form of an explicit
rately, bn
‘ata PE conversion is:
(new.data.t¥Pe) (expression)
gen expt type conversion, there is risk of data loss since we are forcing an expression
to be of a specific type.
For example, converting a floating value of x = 50.75 into an integer type,
riser the fractional part .75 and shall return the value as 50.
Soo x = 50-75
bpp print (int (x))
50
Following are some of the functions in Python that are used for explicitly converting an
expression or a variable into a different type:
, int(x), will
Table 3.5: Explicit type conversion functions in Python
PerrrencrcrbmaamalausesesisrsDescnpdon |
Converts x into an integer.
int (x)
float (x) Converts x into a floating-point number.
str (x) Converts x into a string representation.
chr (x) Converts x into a character.
> Implicit Conversion
Implicit conversion, also known as coercion, happens when data type conversion is done
automatically by Python and is not instructed by the programmer.
t to float.
Example 5: Program to illustrate implicit type conversion from in'
Tiapiicit type conversion from int to float
hunt = 10 #numi is an integer
nun? = 55.0 #nun2 is a float
Sumi - nual + num2 #sumi is sum of a float and an integer
[print (sumt)
Print (type (sumi))
RESTART: C:/Users/preeti/Appbata/Local/Prograns/PYt
hon/ytnon37~32/prog_smplicit_conv}-PY
>>>Informatics Practices with Python-XI
In the above example, an integer value stored in variable numt is added to a float vaty,
variable num2, and the result gets automatically converted into a float value stored
sum1 without explicitly telling the system. This is an example of implicit data con
The reason for the float value not co!
that allows performing operations (whenever possible) by c
data type without any loss of information.
Example 6: Write a Python code to calculate simple interest and amount payable by p,
the value of principal amount and rate from the user for a time period of 5 years,
(Formula used: Simple Interest = Principal * Rate * Time/1 00)
|B pop scast2 py C/Usen/ceet/AppData/LocaPropramy/yino/ Prion} — ome
ie tat fom tan Opis Winder 9
principal-eval (input ("Enter the value of PE
Rateseval (input ("enter the annual rate of interest I
‘rime=$
[Simple_Int = Principal*Rate*Time/100 t
{Anount= Principal*Sinple_Int
print (*Sinple Interest ~ *,Simple_ Int)
Print ("Amount payable ~ */AnoUnt)
iny,
Versio
rnverted into an integer instead is due to type p,
onverting data into a wide
ler.
Visor Hep
pyehon 3.6.5 ( $9c0932b4, war 20 2018, 16;
{usc v.1900 32 bit (Intel) on win32
[type "copyright", "credits" or "License()" for more int
/osers/preeti /appbata/Local/Prograns/Python
/eython36-32/proq_si_class12.py
Enter the valle of PFincipal:8000 |
fenter the annual rate of interest :15
[Simple interest ~ 6000.0
anoint payable = 1400.0
Let us discuss another way of writing codes using User-defined Functions.
3.11 USER-DEFINED FUNCTIONS
‘A function is a group of statements that exists within a program for the purpose of performing
a specific task. Instead of writing a large program as one long sequence of instructions, ita
be written as several small functions, each one performing a specific part of the task.
> How to Define and Call a Function in Python
A user-defined Python function is created or defined by the def statement followed by the
function name and parentheses (()) as shown in the syntax given belo
Syntax:
def function_name(comma_separated_list_of_parameters):|
ene
Keyword Function Definition
statement(s)
tia
Statements below def begin with four spaces, This is c 4
. alled ind i irement of yt
that the code following a colon must be indented, arate uaeya
tical jmplementation-1
prac
jatvs fine a simple function (which does not return any value) by using the command “def
i and call the function. The output of the function will be “I am learning Functions in
She_Debvg _ Oi
3.6.5 (v3.6.5:£59C0932b4, Har 28 20
ay ivon wwing2 18, 16:07:46) [MSC vel
more information.
incl (.
("I am learning Functions in Python’ Function Definition
Fig. 3.18: Function Definition (Interactive Mode)
practical Implementation-2
towrite a user-defined function to print a right-angled triangle.
a progd.« chap3.py - Cjusers/preeti/AppData/Local/Pr.
file Edt Format _Run Options Window Help
def triangle () =
print ("=")
print ("* *")
print ("* * *") |
print ("* * * *
Window Help
“credits” or “license()" for mo
Edit Shell Debug Options
Type "copyright",
re information.
>>>
rs /preeti/Appbata/Local/Programs/
RESTART: C:/USe:
Pytl 32/prog4—chap3-PY
>>> Invoking the Function
xPractical Implementation-3
To write a Python function to compute area of a rectangle.
- oa
inden Hep
are. sngth, breadth) +
area = length * breadth
return area
12 progs.chap3.py - C/Users/preeti/AppData/Loce.-
Fie
de!
Fle E&t_ Shel Osbop_Optons Wadew Hep
Python 3.6.5 (v3.6.5:£59c0932b4, Mar 28 2018, 16:07:46) [Msc y .|
+1900 32 bit (Intel)] on win32
Type "copyright", "credits" or
a.
>>>
RESTART: C:/Users/preeti/AppData/Local/Programs/Python/Python
36-32/prog5_chap3.py
>>> areaRectangle(30, 20)
600
>>
License()" for more informatio
In the above example, we have given the return statement as:
return area, given in function areaRectangle() which returns the calculated value for area
This function is executed and the calculated value returned back to the function call made at
the shell prompt by passing the arguments for length & breadth respectively.
3.12 INDENTATION IN PYTHON
Python follows a particular style of indentation to define the code, since Python functions
don’t have any explicit beginning or end, like curly braces, to indicate the start and stop for the
function; they have to rely on this indentation. Indentation is shifting of a statement to the right
of another statement. In Python, indentation is used to form suites (blocks of statements). A
suite is a group of statements which is treated as a unit, Ifa suite (let us call it B) is indented
with respect to its above statement (let us call it A), then execution of suite B depends upon
the execution of statement A. This concept is used extensively in conditional statements and
loops (covered later). The concept of indentation can be understood better with the help of
the following figure:
B (Under A)
UCC ee ee)
PACs}
CLC ie ee
F (Under A at the same level as B and C)
G (At the same level as A)
Here we take a simple example with “print” command,ay implemencation-4
race
r ste “print” function right bel
write “Pri low the def funci():
whet : an indented block”, O: tt will show “indentation error:
te
Print/function hasbeen declared
| meediataly below:
es care
Fig. 3.19(a): Improper Indentation Results in Error Generation
smeabove error can be removed by making proper indentation before the print() function. At
Jeast one indent is required to make your code work successfully.
(def funcl () =
print ("I am learning Functions in Python")
‘When you leave indent(spacing)
In front of print() function, it will
give the expected output.
Python 3.6.5 (v3.6.5:£59c0932b4, Mar 28 2018, 16:07:
46) (MSC v.1900 32 bit (Intel)] on win32
Irype "copyright", “credits” or "license()" for more
information.
>>>
RESTART: C:/Users/preeti/AppData/Local/Programs/Pyt
hon/Python36-32/progé_ch3.py
I am learning Functions in Python
>>>
Fig, 3.19(b): Significance of Indentation
ay
TORULES AND CONVENTIONS FOR WRITING PYTHON PROGRAMS
ile ‘ in mata:
Working with Python, the following rules and conventions are to be kept in mind:
marcation or symbol in Python to indicate the
4 State
ment Termination: There is no de! ee
by pressing Ent
ten
cee ofa statement. When you end typing a statement in Python
“whe statement is considered terminated by default.b) Clarity and Simplification of Expression: An expression in a program ig a wack
operators and operands to do an arithmetic or logical computation. Some of a
expressions are:
© Assigning a value to a variable,
© Performing mathematical calculations using one or more variables,
Comparing two values.
Writing unambiguous expressions is a skill that must be developed by every progr,
Following are the guidelines to be kept in mind while writing such expressions: Me,
+ Avoid the usage of expressions that give ambiguous results, creating confusion,
* Avoid using complex expressions.
©) Simplicity of Instructions: The instructions given to a computer must be clear ang siny
so that any user reading those instructions should be able to understand them,"
It has been observed that sometimes even the programmers fail to understand th
their own programs after some time. As a result, the maintenance and Modificatioy
programs becomes very difficult, Following are a few tips that should be kept in m
writing the instruction set:
© logic of
of such
ind Whi
+ Avoid complex instructions.
+ One instruction per task should be given.
+ Follow the standards of a language.
+ Use appropriate comments.
+ Keep the names of the variables short, simple and meaningful.
4) Maximum Line Length: Line length should be of maximum 79 characters.
e) Lines and Indentation: Blocks of code in Python are denoted by line indentation, whichis
implemented using 4 spaces per indentation level.
f) Avoid multiple statements on one line: Although you can type multiple statements using
semicolon (;) between two statements in a single line, it is not recommended.
3.14 COMMENTS
Comments are statements in a script that are ignored by the Python interpreter and, therefore,
have no effect on the actual output of the code. Comments make the code more readable and
understandable for human beings. This makes the revision/modification of the code easier by the
original author of the code and also by some new author who has been assigned the responsibilty
to modify it. Comments are not necessary in a script, but these are highly recommended if the
script is too complex or if it is to be reviewed by multiple people over an interval of time.
‘A comment in Python starts with a hash symbol (#) anywhere in a line and extends till the
end of the line. The following code contains two single line comments:
# This is a single line comment
x=10
y=x+100 # value of x + 100 is assigned to variable y
print (y)15 pEBUGGING
* from computer programs that we code, an exception or error or unusual condition can
rt from in our daily life. Consider a real-life scenario—you leave your house for office
cocit °° car, On the way, the tyre gets punctured and you are forced to stop the car and
yy ee tyre. So, in this scenario, the punctured tyre is the exception which has occurred
lac? "edly. In such situations, we are required to carry along a spare tyre so that we can
he punctured tyre then and there only and can continue with our journey, which is
tion handling.
unexpect
Normal Flow Exception Exception Handling
uikewise, when we are browsing a webpage and that webpage is unreachable because there is
| no network connection or that there is no microphone available to create an audio recording—
| these are examples of exceptions or errors.
| sometimes an application can recover from an error and still provide normal, expected
| ehaviour, sometimes errors get reported to the user, sometimes they get logged to a file, etc.
Itdepends on the specific error and the application. Same is applicable in the field of computer
programming also.
Most application codes written for developing applications have errors in them. When your
application suddenly freezes for no apparent reason, that is usually because of an error. But
weall understand that programs have to deal with errors.
‘The process of finding errors in a program is termed as Debugging.
Due to errors, a program may not execute or may generate wrong output. So it becomes
necessary to find out and remove the errors for the successful execution of a program. Errors
in Python are classified mainly into three types:
(@) Syntax Error
(b) Runtime Error
(9 Logical Error
415.1 Syntax Error
ine error is an error in the syntax of a sequence of characters or tokens that is intended to
Voter 14 Particular programming language. These types of errors are generated when we
ae Be or, in other words, the grammatical rules of a programming language. Syntax
the ange most common type of errors which are easly traceable. They can be corrected
| ogra sy 3s the Feason for the error and an appropriate message about what is wrong in the
\s displayed.
3.31
»,
ca
fy
=
3
—
S
is
5
be
2
ke
€
=
=
2
fs
re
EsFor example,
Eét_Shell_ebug Options Window Help
Python 3.6.5 (v:
46) [MSC v.1
3.6.5:£59¢0932b4, Mar 28 2018, 16:07;
‘900 32 bit (Intel)] on win32
type "copyright", "credits" or “license()" for more
information. wortdll
>>> print "Hello wor: : oe
Syntaxerror: Missing parentheses in call to ‘print’.
Did you mean print ("Hello world')?
>>>
Fig. 3.20: Syntax Error: Invalid Syntax ua
The above statement is an example of syntax error as it violates the language Protocol byng
giving parentheses with the print() function. So, the corrected statement should be:
>>> print ("Hello world")
Hello world
However, some syntactical errors are quite hard to find, Python is case-sensitive, so you my
use the wrong case for a variable and find out that the variable isn’t quite working as jo,
thought it would.
For example,
python 3.6.5 (v3.6.5:£59¢0932b4, Mar 28 2018, 1 *
6:07:46) (MSC v.1900 32 bit (Intel)] on win32
"credits" or “license()" for
>>> Print (445)
‘Traceback (most recent call last):
File "", line 1, in
Print (4+5)
NameError: name 'Print' is not defined
>>
In the above example, we have typed Print() statement instead of print(), which is syntactical?
wrong and needs to be corrected. So the correct statement shall be:
>>> print (445)
9
Most syntactical errors occur at the time of program execution and the interpreter points th!
out for you. Fixing the error is made easy because the interpreter generally tells you what”
fix and with considerable accuracy.
(CTM: Syntax errors are errors that occur due to incorrect format of a Python statement. They
while the statement is being translated to machine language and before being executed.yr
spore examples of SYRUBX eFFOTSaFe shown below in Fg. 3.21
: 21.
Ae
Schon 3-6-5 (3.6.5: T55c083
tase v-i900 38 bie SScSmabi, Way Ze 2018, TerG7E4
faperteopreiohe", Pereitat ot itenee0* tor nore 4
ease) statement
prreaxtrtor: invalid syntax
eames fstaterent2
Zyneanrror: invalid syntax
>>> print ‘hello’ ‘#Statement3-
Zynelxerror: Missing parentheses in eal to *print*
SYaryou mean print (*heilo')2 Cu) S° "Pane.
D3 Tete (47576) a
Gyntaxerror: invalid syntax statement 4
Sxetfor iin range (io)?
or statement
SyntaxSrror: expected an indented block
Es
ther types of Syntax Errors
tatusunderstand the reason behind the occurrence of each error given in the above example.
¢ Statement 1 generates syntax error because of improper closing bracket (square bracket
instead of parenthesis).
2 generates syntax error because of missing parenthesis after ‘i
generates syntax error because of missing parenthesis with print() method.
enerates syntax error because of use of semicolon instead of comma in a list
Statemen keyword.
@ Statement 3
& Statement 4 g
declaration.
© Statement 5 generates syntax error because of improper indentation.
3.15.2 Runtime Error
Aruntime error occurs after Python interpreter interprets the code you write and the computer
begins to execute it. Runtime errors come in different types and some are hard to find.
You know you have a runtime error when the application suddenly stops running and displays
anerror (exception) dialog box or when the user complains about erroneous output, It usually
results in abnormal program termination during execution.
Forexample,
Tie Edt Shel_Oebup Options Window Hep
Python 3.6.5 (v3.6.5:f59C0932b4, Mar 26 2018, 16: “|
07:46) (MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "License()" for mo
re information.
>>> 10*(1/0)
Traceback (nost recent call last):
File "", Line 1, in
10* (1/0)
ZeroDivisionError: division by zero
>
Fig. 3.22: Example of Runtime Errori 't yield any output. Insteay_
cally correct but won't yielc ail
The above statement is syntactically ber by 0 will result in an error upon execu,
generate an error as division of any num Een é
illegal program termination. Some examples of Py'
* division by zero,
+ performing an operation on incompatible types,
+ using an identifier which has not been defined,
+ accessing a list element, dictionary value or object attribute which doesn’t exist,
+ trying to access a file which doesn't exist.
CCTM: Errors are exceptional, unusual and unexpected situations and they are never part of thengy
flow of a program. :
In Python, such unusual situations are termed as Exceptions. Exceptions are usually ning
errors.
3.15.3 Logical Errors
A logical error/bug (called semantic error) does not stop execution but the program behayy
incorrectly and produces undesired/wrong output. Since the program interprets success,
even when logical errors are present in it, it is sometimes difficult to identify these errors
Logical errors are the most difficult to fix. They occur when the program runs without crashing
but produces an incorrect result. The error is caused by a mistake in the program's logic, Yo
won't get an error message because no syntax or runtime error has occurred.
You will have to find the problem on your own by reviewing all the relevant parts of the code,
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 comet
code to find the average should have been (10 + 12)/2 to get the output as 11.
For example,
‘Wlustrating Logical Error
x = float (input (‘enter a nusber: *))
Jy = float (input (‘enter a nusber: *))
Fie {6 Sul_0009 Oneonta ee
RESTART: ¢:/Users/p:
reeti/AppData/Local, i]
Python37-32/prog_logicer: ee
Enter’ a nungers 3 °° Py
Bater nunbes! 4
S35 SN*F89" of the two numbers you hive entered is: 5.0 |
ane eel
_'s a result, you will get 5.0 as the output instead of —
3.5.—
Jem, we will simply add parentheses: z = (x+y)/2
gy 5 prob
pe G
Pres Nt
me catrating Logical Error a
Teste se (input ("Enter a number: '))
XT Hone tinpue (Enter a numbers *))
2° ep)
2 Sam ZI verage of the two numbers you have entered is:',2)
wwe will get the right result as 3.5.
e,10
wen 2
paren Set ey Weer
Sant? C2 /Users/preeti /AppData/Local/Prograns/Python/ “|
1 logicerrori.-py iret!
© venom BYTES
statements, comments, functions, blocks
python program can contain various components like expressions,
and indentation.
tnpression is 2 legal combination of symbols that represents 2 value.
An
sent is a programming instruction.
> stater
additional information added in a program for readability.
e non-executable,
+ npyton, comments begin with the hash (#) symbol/character.
+ avariable in Python is defined only when some value is assigned to t+
friable can hold values of different types at different times.
> Comments ar
> python supports dynamic typing, i-€., 2 Vi
+ Afunetion is a named block of statements that can be invoked by its name.
+ Theinput() function evaluates the data input and takes the result as numeric type
> output is generated through print statement.
sn of operators and operands. Operands are the objects on which operators
» Anexpression is a valid combinal
are applied,
fe used for performing computations in a program.
* Anthmetic, relational and logical operators ar’
ingle, double or triple quotes.
we may use
* Astring is a sequence of characters. To specify a string,
concatenating them. Similarly, the operator
.d on two string operands is used for
times.
* Theeperator + (addition) ap
(muiplication) is used to repeat a string a specific number of
strings are compared lef
* When rea i
‘ational operators are applied in strings, ft to right, character by character,
cording to the
eir ASCII values.
n is evaluated only if
> nit
ile evaluatin
ting a Boolean expression involving ‘and’ operator, the second sub-expres:
efi
agg enresson vets True,
ie evaluat
sae tating an expression involving ‘or operator, the second sub-expression is evaluated only ifthe first
1, umesson yields False
"arable
a name that refers to value. We may also say that a variable associates a name witha data oPled
uch as ny
imber, character, string or Boolean.
EEv
Values are assigned to variables using assignment statement. The syntax for assignment stem,
Variable = expression §
where expression may yield any value such as numeric, string or Boolean.
> Inan assignment statement, the expression on the right-hand side of the equal to operator (2yj,
the-value so obtained is assigned to the variable on the left-hand side of the = operator, met
> Avariable name must begin with a letter or _(underscore character). It may contain any number gf,
or underscore characters. No other character apart from these is allowed. Maa
> Python is case-sensitive. Thus, marks and Marks are different variables.
> The shorthand notion for a = a b is
a =b
> In Python, multiple assignment statements can be specified in a single line as follows:
, , ... = , , .-
> keyword i reserved word that is already defined by Python fora specific use. Keywords cannot be
any other purpose.
fying and removing errors from a computer program is called debugging,
The process of ider
Trying to use a variable that has not been assigned a value gives an error.
Runtime errors occur during the execution of a program.
vvvy
Irregular unexpected situations occurring during runtime are called exceptions.
OBJECTIVE TYPE QUESTIONS —
1. Fill in the blanks.
(a) The smallest individual unit in a program is known as a
(b) A word having special meaning reserved by a programming language Is known as .
(a literal is a sequence of characters surrounded by quotes.
(2) are tokens that trigger same computation/action when applied to variable,
(e) A is a reserved named location that stores values.
(f) Todetermine the type of an object we use .. . function.
{g) The input() always returns a value of . type.
(h) Blocks of codes are represented through ..
(jn typing, a variable can hold values of differen types at ciferent times
{j) In Python, the floating point numbers have precision of digits.
(k) Operators that act upon two operands are referred to as .. operators.
truncates fractional remainders and gives only the whole part as the rest
0) =
(m) The process of identifying and removing errors from a computer program is called ... -
‘Answers: (a) Token (b) Keyword (c) String (d) Operators (e) Variable
(f) type() (g) String (h) Indentation (i) Dynamic {j) 15
(k) Binary (I). Floor division (m) Debugging
2, State whether the following statements are True or False,
(a) Python supports Unicode coding standard.
(b) An identifier must be a keyword of Python.
(c) Default variable initialization is string literal,
(d) 3+C=A is a valid statement.
(e) The input() always returns a value of an integer type.
(f) The print() without any value or name or expression prints a blank
{g) In Python, Boolean type is a sub-type of integer.\sscé-2020" is a valid string in Python,
Me qhon, Integer data type has a fractional Part,
@ ei jiteral in Python means “there’s nothing here
(b) False
(a) True OU
posit rue (h), False (i) False i. Are (e) False (f) True
ripe choice Questions (MCQs):
i ;
3. ch ofthe following are the fundamental building blocks of a Python program?
(i) identifiers (ii) Constants (iH) Punctuse et re
identifier name cannot be composed of special characters other than
(b) ty # (ii) Hyphen (-) (iii) § -
(iii) 4
«) single ine comments in Python begin with evel
oF oL (iy (i) %
(e) which of the following does not represent a complex number?
() K=2 43) (ii) k = complex(2,3)
(iv) K= 443)
Perators given below in Python?
3. Multiplication
6. Subtraction
(iii) 1,3,2,6,4,5
(1) What i the order of precedence of arithmetic o
4, Parenthesis 2. Exponential
4. Division 5S. Addition
() 123,456 ) 2,3,4,5,6,1
(g) What will be the output of the following snippet?
4,6,5,2,3,1
xy=2,6
KY=YKt2
print(xy)
(i) 66 (ii) 44 (ili) 46 (iv) 64
(h) The extension of a Python file is given as—
(i) pt (ii) .pwy (il) py or pyw (iv) -yppy
() The reserved words used by Python interpreter to recognize the structure of a program are termed
as
{i) Identifiers (i
Tokens (iii) Literals (iv) Keywords
(i) Which of the following is a syntactically correct string?
i) “This is great !” (ii) ‘she shouted ‘HELLO’ loudly’
“Goodbye’ (iv) “This “course” is good”
{k) What can be the maximum possible. length of an identifier?
(i) 32 (ii) 63
(iii) 79 (iv) Can be of any length
Answers: (a) (iv) (®) (iv) (c) (ii) (a) (i) (e) (ii ow
(e) (iv) (h) ii) ( (vy a (k) iv)
SOLVED QUESTIONS
1 Consider the following statements in Python interpreter and describe the output/statement required:
{@) Print a message “Hello World”,
a= 19
bei
Cz aay
Print (¢)
(0 To retrieve the
a data type of the inputted string “Hello” stored i
) To describe the
data type of variable ‘b’.
° retrieve the address of variables a and b.
_ —_
ide the variable ‘a’.a
{f) State the output:
pop deb
pod
orb
>>> id(d)
>>> id(b)
(g) >>> a7 "Hello"
popa* 10 ep
(h) To display the value for a, a? an
() >>> a= 15
p> bad
>>> a/b
ie Si jignment stat
a faa ie values of two variables, 2 and b, using multiple assien™ nt statements,
j) To swal
‘ans. (a) >>> print ("He1Lo world")
Hello World
(bp >>> a = 10
>>> b= 12
So>czatd
>>> print (c)
22
{q) >>> a= "Hello"
>>> type (a)
(a) >>> type (b)
(e) >>> ida)
52193248
>>> id (b)
1616896960
() >> d=b
aod
a2
>>> b
12
>>> id(d)
1616896960
>>> id (b)
1616896960
(g) >>> a = "Hello"
>>> avl0
‘Hel loHel loHe1loHe1loHelloHelloHelloHelloHelloHello'
{h) >>> a = 10
>>> ar*2
100
>>> at3
1000
>>> ata
10000
() >>> a= 15
>>> bed
>>> a/b
3.75
>>> a//b
310, 12
2
() 2273 age
30> ar B
Sopa
12
go> b
10
at is the difference between a keyword and a variable?
Keyword is a special word that has a special meaning and purpose. Keywords are reserved and are few.
- Kereeample, int, fat, for, if elif, else, ete, are keywords -
{aviable isthe user-defined name given to a value. Variables are not fited/reserved. These are defined by
Maa iser but they can have letters, digits and a symbol underscore. They must begin with either a letter
tr mnderscore. For example, _age, name, result, etc. are the variable names in Python.
4, what type of error willbe produced when you type:
+ Result = “Python” + 10
fame the error and error message.
ns, The error is: TypeError
* Tne error message Is: Can’t convert ‘int’ object to str implicitly
4. what type of error will be produced when you type:
while True print(“Hello world”)
ans. The error is: Syntax€rror: invalid syntax
2.W
5, What is a function? How is it useful?
fans. A function in Python is a named block of statements within a program. For example, the following
program has a function within it, namely greet_msg().
# progl.Py
def greet_msg():
print("Hello there! !")
name = input ("Your name:")
print(name, greet_msg())
Functions are useful as they can be reused anywhere through their function call statements. So, for the
same functionality, one need not rewrite the code every time it is needed; rather, through functions it
can be used again and agai
6. Find the error.
def minus (total, decrement)
output = total - decrement
return output
Ans, The function header has colon missing at the end. So, we need to add colon (:) at the end of the header line.
Thus, the corrected code will be:
def minus (total, decrement):
output = total - decrement
return output
7. How many types of strings are supported in Python?
‘Ans. Python allows two string types:
(1) Single line Strings—Strings that are terminated in single line
(2) Multiline Strings—Strings storing multiple lines of text
8. What are variable-naming conventions?
Ans. (i) A variable must start with a letter or underscore followed by any number of digits and/or letters.
(ii) No reserved word or standard should be used as the variable name.
(ii) No special character (other than underscore) should be included in the variable name.
liv) Case sensitivity should be taken care of.
9. What is None in Python?
‘Ans, Python has one special type called None. The None type is used to indicate something that has not yet
been created. It is a non-null, unidentified value.10. Identify the types of the following literals:
. sgalse", None
23.789, 23789, True, "True’, "True", False, “False’
Ans, 23.789 Floating point
23789 integer
True Boolean i
‘True’ String
"True" String i
False Boolean
“False” String
None None
21. What the dference pen ger constat Thus SL1 [ong integer valu and Sis
Ans. An lor L suffix indicates that it is a long. BE ;
value.
12, Find the output generated by the following code:
(1) x=2 °
x53
xtsy
ee print (x,y)
(Ans. 5 3) (Ans. 10 -8)
(3) a=5 «@
b=10
be at=ptq**2
print (a,b) print (p,q)
(Ans. 20 300) (Ans. 60 480)
(5) (6)
pteptatr |
rtsptqtr
q-=ptatr
print (p,q,r) print (p,q, r)
(Ans, 27.5 -642.5 62.5) (Ans. 1.7599999999999998 4.96 0.510
13,
Ans.
What is the difference between an expression and a statement in Python?
‘An expression is a combination of symbols, ny Pi
‘Statement’ is defined as any “PIE
Operators and operands. instruction given in Python as per thes!™
‘An expression represents some value,
Statement is given to execute a task _
The outcome of an expressions always avalue, —
fe q
Statement may or may not return
the result.
Print("Hello") is a statement.
4, [Forexampie)3°"°7 10/ig/an expression,
14. Identify the error in the following Python statement:
>>> print ("My name is", first_name)
Write the corrected statement also,
Ans, The above statement is tr
made by defining the variable name before
>>> first_name = 'Rinku!
>>> print ("My name is", first name)
i
i
ving to print the value of an undefined variable first_name. The corr
using it, Le.,ne ete could you pinpoint want to ir
oun ee num 2
seincizeseit)
resem is that input) returns value asa str
ye ae bier 25. Therefore, the output snot 30, TosoWe thepobtene 15 is returned as string ‘15’ and
ooking te MP lem, int() function is to be used while
imeyot a legal statement of Python; it should be print. The
The corrected code is:
P"
AsO og = ant (iMPUt ("Enter Number:") )
augare = num * 2
Sent (result)
eer rogram to obtain temperature In Celsius and convert
ito Fahrenheit using the formula:
i
16 Wag /5#82
Fegissus to Fanrennest
ws eH Vjoat (input ("Enter temp in Celsius :"))
SS in Celsius is :", cels)
ges * 9/5 + 32
wgemperature in Fahrenheit is
a)
int (
be the output produced by the following code?
7. What will
name = ‘Neexu"
age
pri
print ("yo
output should be:
neeru, you are 23 now DUt
you will be 22 next year
sn what willbe the output of the following code?
x, yr 2 6
xpyrye xt?
print (x, y)
ns. 6 4
Explanation: Tt
The next line (se
And then assigns this to
The third line prints x an
49, Wete a Python code to calculate and display th
ius. costPrice = int (input ("Enter cost price
profit = int (input ("Enter profit:'))
sellingPrice = costPrice + profit
print ("Selling Price:', sellingPrice)
Output:
Enter cost price: 50
Enter profit: 12
Selling Price: 62
UNSOLVED QUESTIONS Se
nt to display your name:
class and section,
", 21, "now but", )
, age +1, "next year")
assigns values 2 and 6 to variables x and y respectively.
cond line) of code first evaluates the right-hand side, Le. Ys 2, which is 6, 2+ 2, Le., 6.4;
X,Y, Leu, ky ¥ = 6, 4; 50 x@gets 6 and y gets 4
\d y so the output is 6 4.
.e selling price of an item.
»
he first line of cod
ie
=
=
S
€
Ss
is
SB
A
i
2
€
iS
Pe
FE)
=
i
A
E=4
ts
L
7 He Python command/instruction/stateme!
. Write Python command to display your school name,
a
a the following expressions manually: (r4-0V3
) (243)**3-6/2 (ii) (243) * 5/44 (44 6/2 uy haae ia ee ve
(W) 124(3eeq—eyy2 (vy 12%3% 542° 61/4 fui) 12.965%3 + (260/84
separated by *-".4. Evaluate the above expressions by using IDLE as a calculator and verify the results that yoy gey,
5. Name three runtime errors that occur during Python program execution.
6. What is the difference between an error and exception?
7. Explain the difference between syntax error and runtime error with examples.
8. Identify invalid variable names from the following, giving reason for each:
th, Htag, tags, 9
Group, if, int, total marks, S.l., volume, tot_stren}
9. Find the output of the following code:
(1) (2)
xy
print (x,y)
print (x,y)
@) (4) p=10.
br-atb
print (a/b) print (pq)
(5) p=582 (6) pr2i//s
he
x=p//q
prepare
rheptate
q-=ptq*r
print (p,q,r) print (p,a/r)
10. Write Python expressions equivalent to the following arithmetic/algebraic expressions:
349 2
hy, ae 2 @) 242
(1) Qs (3) 5
(a) ort? (5) 8-6+ fear (6) ute Sat? -
(u, a, tare variables)
11. Write Python expressions to represent the following situations:
(a) Add remainder of 8/3 to the product of 8 and 3.
(b) Find the square root of the sum of 8 and 43,
(c) Find the sum of the square roots of 8 and 43,
(d) Find the integral part of the quotient when 100 is divided by 32.
412. What are operators? What is their function? Give examples of some unary and binary operators.
13, What is an expression and a statement?
14, What all components can a Python program contain?
15, What are variables? How are they important for a program?
116. What is Dynamic Typing feature in Python?
17. Which data type will be used to represent the following data values and why?
(a) Number of months in a year (b) Resident of Delhi or not
(c) Mobile number (4) Pocket money
(e) Volume of a sphere {f) Perimeter of a square
(g) Name of the student (h) Address of the student
25called calculate_area() that takes base and hei
func ‘gs an output. o formula used is:
rte ri base*height
ao Tne function to take a third parameter called shay
Mee the ates Based on the shape, it should calculate the
= length*width.
yd ect
led print_pattern that takes integer number as argi
ight as an input argument and returns an
ipe type. Shape type should be either
area. Formula used:
ee
% ntl pecan
oF
; jument and prints the following
imber is
oad, then t should Pint:
fine
1 sunction that takes amount-in-dollars and dollar-to-rupee conversion price; it then returns the
we (ey converted to rupees.
ae the following code do?
wha
2 10
aebel
3. what isthe error in
=6
a gut the error(s) in the following code fragments:
24 Fi
iu) temperature = 90
print temperature
the following code?
=30
oo.
print (a And b)
@) a,b, c= 2, 8, 9
print (a, b, c)
c, bp ata, b,c
print(a sb; ¢)
(x= 24
4x
(6) Print ("x =" x)
35, What will be the output produced by the following code fragment(s)?
) x= 10
X=X+10
X=X-5
print (x)
X,¥=x-2, 22
Print (X, ¥)
0) tirse
second = 3
thitd = first * second
Print (first, second, third)
third = second * first
Print (first, second, third)
ae = int (input (*side'))
le given as 7
S88 = side * side
Print (side, areay
ee
Sy
Ey
—
HI
E
fa
fe
=
PS
=
Es
&
=
a
3.4326. “Comments are useful and an easy way to enhance readability and understandabitity 6, io
Elaborate with examples.
27. Find errors in the following code fragments.
(a=3
print (a)
b=4
print (b)
s=atb
print (s)
(2) Name = "Prateek"
Age = 26
Print ("your name & age ar
GB) aA=3
S=A+10
New"
Q=a/10
Give the output.
x= 40
yextl
x= 20, y+x
print (x, y)
29. Give the output.
x, y= 20,60 i
Yr X y= x, y-10, x+10
print (x, y)
30, Give the output.
a, b=12, 13
ce, b=at2, a/2
print (a, b, c)
", Name + Age)
28.
31.
Give the output.
a, by © +10, 20, 30
Pra, r=c-5,a43,b-4
print('aandb, :', p, q, x)
ind errors in the following code fragment. (The input entered as X!)
¢ = int (input ("Enter your class:"))
print ("Your class is", c)
33,
Find errors in the following code fragment.
cl= input ("Enter your class")
print ("Last year you were in class" cl-1)
Write a Python program that accepts radius of a circle and prints its area.
Write Python program that accepts marks in § subjects and outputs average marks.
Write a program to find the area of a triangle,
Write a program to input a number and print its fi
38. Write a program to read detalls like name,
same line and then in separate lines,
39. Write a program to read thre:
first and second, second and third numbers,
$
35.
36.
37,
rst five multiples, ie
class, age of a student and then print the details, istBA
2. Gurukul Vidyapeeth is
Every year, with the commen
‘was manually done till date an
problem, develop a Python progra!
obtaining the basic fee amount from tl
the institute.
el
cet and act
out mmer tO
non code that accepts cost of goods sold (cogs),
gD/SOURCE-BASED INTEGRATED QUESTIONS
£ : —
fs igan India-based cargo company that deals wit
Le ‘oss the globe. To do business analysis eae fie
develop a computerized system for the same,
oe ale of various goods within the
lay transactions, they have hired a
i Fevenu
et profit and net profit percentage, INet prot eee OPerating costs (oe), and
nue — cogs ~ oc]
Tosegran calculate Of FOE, wet BOEE
eee AEeECUtEntee cost ot goes
So ee one ee
ee areas anecees proeit
Bo io oot tt poo
Be = jegst00 # wet, profit. perc
print ("Gross profit is', gp) ponies
print (‘Net profit is', np)
Pee ive profit percentage ist, app)
Fie C48 _Shel_Oebug Options Window Hep
Imore information.
>>>
RESTART: C:/Users/preeti/AppData/Local/Progra
ms/Python/Python37-32/prog_revenuel .py
Enter cost of goods sold : 100000
Enter revenue generated : 150000
Enter operating cost : 12000
Gross profit is 50000
Net profit is 36000
Net profit percentage is 25.333333333333336
>>>
a reputed institution in the field of academics and extra-curricular activities.
‘cement of the new session, it hikes fee by 10% for all the students which
id required enormous efforts on the part of the office staff. To solve this
wy that calculates this 10% fee hike every year automatically after
he user and displays it to the parents of the students enrolled with
Se Tor tanOpsers_vindon HD
Bee arto calculate 108 fee hike
amount = int (input ("Enter Amount')) \
fee hike = 0.1*amount
feestifee = anount + fee_hike
foiktcites to pay now:", Eotal,_fee)
Te
La Pyne
Tie tit Shel _Debog Options Window Help 7
SEsTART? C2 /Users/preeti/Appoata/10ce
peStirams /Python/Python37-32/Pros_fee
hike-py
Enter Amount 120000
Fee to pay now: 132000-0
>>>