IP Notes.
IP Notes.
tr -1.if'
,, :')...J
~..,.8a~ebonN of a Python Program
Let Ub take our d1-,n1ss1on turlht>r. '\,kn-. ,, .-. ,ll'l.· g(,lflf; to t,J 11,.
c;tntctnn:- of n Python progr.im ,,·h,11 ,lll 11 can ,ontum- fki,ln \H' r
h,n Pa look at followmg s,1mple code Loc.lk .Jl the.' c.~ldl' ,1nd tht11 pwn_"";.-.J ~ [!]~G]
the discu-,sion thc1t followi,. Don t \\ on1 it the.• tlung·, .1re mrl c:t'..!!' to "
r:ght nm;,Xlwy'II becom<• dear "•hen the dis..,i.swn prna,,J.., ~~
fn,91 .,._,..,u=;.1)'1,- L tr This program shows a program's components
• Comrwmt, .,,...---- '-..
tbeg"_1 wit/~ #I # Main program-code follows now
~c,c\ d -# l'\ rt1-.
tJ.'!!'~.
State111e11h
~ J a= 15 ~~ ....., .....
✓
~ Stat1-r-u111:s ,.r:..~. 'J."'-_-•_.:q
f)'{'G 0(11•14/.1-Ju.;: L'I.:;; (
b = a - 10 - -... ~ _~ Evpres.,ion.,
print (a+ 3). ·::,. ~ ~ Bfo,-<i~
if b5: > # colon means lt'., a block )
.
lndemano11 -,::·
................ ~ print (" Value of 'a' was more than 15 initially.") ln/111,1 rommenh
111 1 1
<see bulc11t.•J 1i11~;i·······•... else
·•••._ : • , , ,.v:;,,.::111
1·1 t!r.,J 1111.ldlr,,r
b.-g , ,1;, tw
g
print ( Value of a' was 15 or less initially ." )
As you can see that the abo\'e sample program ct111tnins v,,rious compom•nt.s hl-e:
¢) expressions ¢) statements
¢) comments ¢) blocks and indentation )
There may be other components like f111Tctio11s in a progr<1m but we .1rc not going irito thoSt.~
details as it is beyond the scope of the book.
Let us now discuss various components shovvn in abovt~ sampll.' cudc.
(i} Expre~ s
An expression is any legal combination of symb_9ls that represents a v,1'11e. An e:xprCS!>I O
represents something, \•vhich Python evai~ates and ·,~•i.Jchti~en produces a viiJue
Some examples of expressions are
1s l rESSIONS
• ( •~\'pn>ssio11s 1ha1 urr m/ut>;s v11/y
2 9 .)
~ '-' Ari expn-ulon
~
a + 5
.-omp/n r:\7>n.~io11s that product• a
(3 + 5) / 4 ~'Clim• w/11:11 t•n1luu1,d
No\v from the above .sample code, can you pick out all c,pre..,s10ns ?
These' Mt> : I '.i, t1 - lO, n +- 3, t, > 5
~ ier 3 PYTHON FUNDAMENTALS 55
Statement
~ ex_pression rep:esents something, a ~~~-~tis _~!:9gramming instr~-~~i? ~ _that does
J,2ffi£-tl}}.ng 1.c., some action takes place. Following are some examples of statem~nts ·
P.pint ("Hello") # this statement calls print function
/: . STAHMENT
../ J. f b_ > 5 : # this statement tests if b > s
While an expression- is evaluated, a statement is executed i.e., '-
some action takes place. And it is not necessary that a
i.e., some action takes place. ,,
statement results in a value; it may or may not yield a value.
Some statements from the above sample code are:
NOTE
a= 15
b = a -10 A statement executes and may
or may not yield a value.
print (a+3)
ifb<S:
COMMENTS
"Aomments are the addi-
') Comments ' - ~onal readable information to
Comments are the additional readable information, which is clarify the source code.
read by the programmers but ignored by the Python inter- comments in Python begin with
preter. In Python, comments begin with a symbol # (Pound or symbol# and generally end with
hash character) and end with the end of physical line. end of the physical line. ,,
In the above code, you can see four comments :
(i) The physical lines beginning with # are the full line comments. There are three full line
comments in the above program, which are :
# This program shows a program's components NOTE
#Definition of function See You( ) follows A Physical line is the one
# Main program code follows now complete line that you see on a
computer whereas a logical line
(ii) The fourth comment is an inline comment as it starts is the one that Python sees as
with a '#' in the middle of a physical line, after Python one full statement.
code (see below)
if b < 5 : # colon means it requires a block
'-------- this is i11/im ct1111111,·111
Multi-line Com ments
----~----~
What if you want to enter a multi-line comment or a block comment ?. You can enter a
multi-line comment in Python code in two ways :
~ d a# symbol in the beginning of every physical line part of the multi-line comments, e.g.,
#Multi -line comments are useful for detailed additional information.
# Related to the program in question.
# It helps clarify certain important things.
ii) T e comment as a triple-quoted multi-line string e.g.,
'" Multi-line comments are useful for detailed additional
information related to the program in question.
/
It helps clarify certain important t hings
r
56 INFORMATICS PRACTICES x
This type of multi-line con1mcnt is also known as docstring. N OTI
111111
You c~~,=-~her USC}ripJe-ae2:5trophg_C: l2J triple q.witcs ( )
Comments enclosed in triple
tS? -~ !it~ dqcstrings. The docstrir1g~ a~r:£_~fil'-Y~USefulln.doc11 men-
tation. - --· - ~- ---- , . £· -~ -~-
quotes {" " ") or triple apostrophe
(' ' 'J are called docstrings.
/ .~ ,
(l~ocks and Indentation
/ Sometiflles a g.r:oup.__of statements is part of another statement o_.!_fnnctioo Such a..gro~p_,,,_qf QJ1e
or more statements is called block or code-block or suite. For example,
lour v](Jces together mark if b < 5 :
t/u.• nexl imient-le11el ...._,
........___ print ("Value of 'b' is less than s. ") ~ This is a block with all its
print ("Thank you.") ..-----,,..- statements at same indentation
level.
Many languages such as C, C++, Java etc., use symbols like curly brackets to show blocks but
Python docs not use any symbol for it, rather it uses indentation.
Consider the following example : / BLOCK OR Coo_ E_
- ( . -BLOCK OR SUITE
4
if b < a : " A grollf)~-~ a r e
~~f another~
t mp = a _..,,,- This is c1 /J/ock, 1u1rt o/ if stal<'IIWIII. / are called blnff ttr
a= b Nolin·. all sla/<'111<•11/s i,1 sa11w hloc:k
lllll'l! sa111e il/{lc•11ta1ir111 l1 1'c'I.
1
Python.
,
b =tmp
print ( "Thank you") ~ --' :/'/,is st_c~t·"""'"~ is ,wt J~m·t o/ ifs block as i1
'mlf.; ,s at dijjerenl 11ule11tat1011 h•1•d.
--· -~ "''-l-'Oldlt: wurus m a-n1ctent1fier e.g., loan_amount or use
v rapHdhzmg first. 'letter of the each successive word e.g., loanAmounc.
~:; variables and Assignments ( "\ e>-'r-J..V \) ~
A vJriablc in Python represents nan1ed location that refers to a value and whose values can be
used and processed during progra1n run. For instance, to store name of a student and 1narks of
a student du ring a program run, we require some labels to refer to these marks so that these can
be distinguished easily. Vnrinbles, called as symbolic variables,
serve the purpose. The variables are called symbolic variables VARIABLES
because these are nan1ed labels. For instance, the following ' ' Nameal abels, whose values
/""
statement creates a variable nan1ely 111arks of Numeric type: \._....;-can be used and processed
during program run, are called
marks= 70
Variables.
3.5.1 Creating a Variable "
Recall the state1nent we used just now to create the variable marks:
marks= 70
As you can see, that we just assigned the value of numeric type to an identifier name and
Python created the variable of the type similar to the type of value assigned. In short, after the
above statement, we can say that marks is a numeric variable.
So, wasn't creating variables just that simple? Yes, you are right. In Python, to create a variable,
just assign to its name the value of appropriate type. For example, to create a variable namely
""'ICE~
~ .J '
,'j
. refer I
~ nd
3 _5_3 Variable Definition
So, you see that in Python, a variable is created when you first assign a value to it. It also means
that a variable is not created until some value is assigned to it.
To understand it, consider the following code fragment. Try running it in script mode:
pyJ.1if' ( X)
/
t / / x= 20 •
print (x)
when you run the above code, it will produce an error for the first statement (line 1) only -
name 't not defined (see figure below)
j
r· ""t
[j ~ 3.7.6 5h11
File Edit Shell Debug Options Window Help
-~ ' >>>
=-- - -- - - - = RESTART: C: /Pywork/cpa7_inl.py =
•• Traceback (most recent call last):
• •• ~\.F:.le . "C: /'Pywork/cpa7 inl.py", line 2, in <lDodule>
.a. print( x ) -
NameError: name 'x' is not defined ~ .
>>> I ~
The reason for above error is implicit. As you know that a variable is not created until some value is
assigned to it. So, variable x is not created and yet being printed in line l. Printing/using an
uncreated (undefined) variable results into error.
So, to correct the above code, you need to first assign something
to x before using it in a statement, somewhat like : IMPORTANT
X=0 # variable x created now
A variable is defined only when
print (x)
you assign some value to it
X = 20 U5mg an undefined variable m
print (x) an expression/statement causes
an error called Name Error.
Now this code will execute without any error.
b:z Iii