Python Fundamentals
Python Fundamentals
chapt e r
6.L lntroduction
6.2 Python Character Set
6.3 Tokens
6.4 Barebones of a python program
6.5 Variables and Assignments
6.6 Simple Input and Output
5.1 tntroduction
ou must have heard the term IPo
'!
:nd computer actions are
- rrrpl, Process, output. Most (in fac! nearly all) daily life
Sovernea uy rno cycle. That i., *r"." is certain Inpu! certain
Processing and an Output. kind of
)o you know that programs make IpO cycle happen
?
\nywhere and everywhere, where you
want to transform some kind of input
i'ou have some kind of input to certain outpu!
to certain outpu! you have to have
;nstructions that govern the processing. aprogram.A program is a set of
In other words, a program forms the base for
rrocessing.
In this chapter' we shall he talking
about all basic elements that a python
\ ou'll be learning about Python'J program can contain.
basics like charactr, ,rt, tlok rs, expressions,
:'tput and output etc' so, are we statements, simple
all ready to take our first sincere step towards python
programming ? And, here we go :_).
131
I
fl
#t 1.32 COMPUTER SCIENCE WITH PYTHO
tr
{
d
c) \Mhitespaces Btank space, tabs (-+), carriage netunn (J), neWline, form'
c) Other characters Python can process all ASCII and Unicode chanactens as pa
data or literals.
Every component of a Python program is created using the character set, be it stateme
. expressions or other components of a program.
_f1
*._1 loKens
In a passage of text, individual words and punctuation marks are called tokens or lexical u
lexical elements. The smallest individual unit in a program is known as aToken or alexical
Consider the following figure that tells what a token lr.eans.
An English Sentence
\,t.----it
i'Hurray!", he exclaimed, iWe are the world champi*g'+
-Tn,
\\ : t\i\
i"riru; Llntls or
',
t.)k.t!') in an English sentence - here
,.,'i
two /'
.r, I
types of tokens are used and punctuatian characters
A Python Program
A string value or string literal
# A sample prognam
name = "Anya" An integer value or integer literal
age = 15
A floating-point value or floating point literal
contribution = [email protected]
print ( name,_'?Sed'i, aS"\ t contr iOt)fi ,)iy*,
=--'\1r..1i - jnr
&i{=r
r.ttuO,,'d Pu il r)t d a:a
,1:+-_-
i cha,=clers
lndividual lexicat unils or tckens, together make components of a program such as slafements or
expresslons etc. ln above program you can see these tokens : literals, ,
,|)unciuE?ror'.s
., , ,,yi], 1 {i S
! xrvwoao
: :'t/iLtords are the
words that convey a special meaning to the A keyword is a word having
-rnguage compiler/interpreter. These are reserved for special special meaning reserved by
programming langpage.
r-rrpose and must not be used as normal identifier names.
-,.
thon programming language contains the following keywords :
.tentifiers are fundamental building blocks of a program and are used as the general
s .n" =:minology for the names given to different parts of the program aiz.variables, objects, classes,
-:t'tctions, lists, dictionaries etc. Identifier forming rules of Python are being specified below :
c) An identifier is an arbitrarily long sequence of letters and digits.
c) The first character must be a letter; the underscore ( _ ) counts as a letter.
c) Upper and lower-case letters are different. All characters are significant.
c) The digits 0 through 9 can be part of the identifier except for the first character.
c) Identifiers are unlimited in length. Case is significant 1.e.,
Python is case sensitive as it treats upper and lower-case
,f,Lj ffi-f-
characters differently' python is cose sensitive as it
c) An identifier must not be a keyword of Python. treats upper and lower-case
c) An identifier cannot contain any special character characters differentlv'
except for underscore ( _ ).
-'e following are some The following are some inaalid identifiers :
' :.7 identifiers :
-.i'cis I \rciues
:erals (often referred to as constant-:/allr,;s) are data items that have a fixed value. Python
,-r\\-s several kinds of literals :
As vou can notice, one can forrn string literais by enclosing itl.'i 5 *
=
text in both forms of quotes * single quotes or double quotes. ln Python, one can form
Following are some valid string literals in Python : literals by enclosing text i
'Astha' "Rizwan" 'Hello World' "Amy' r" "1,29045" forms of quotes - single
or double quotes.
' 1. -x- @ -w- 25"' 1,1,2F 8D29 1"
Python aliows you to have certain ntmgraphic-chnrtrcters in String values. Nongraphic charr
are those characters that cannot be tvped directly from keyboard er.g., backsphce, tabs, ca:
return etc. (No character is typed when these keys are pressed, only some action takes I
These nongraphic-cllaracterc can be represented by using escape sequences. An escape scque
represented by a backslash (\) followed by one or more characters.
. Follou,ing table (Table 6.1) gives a listing of escape sequences.
In the above table, you see sequences representing \,', ". Though these characters can be
from the keyboard but when used without escape sequence, these carrv a special rnearrin
hal,e a special purpose, ho\,\,ever, if these are to be typed ns it is, then escape sequences sl
.t lo$
be used. (In Python, you can also directly tvpe a dc
C\^c"' quote inside a singie-quoted string and vice-\.ersa
"anu's" is a valid string in Python.)
1. l.Mhat is meant by token ? Name the
tokens avaiiable in Python. ,',.) , :,r I 'r ri
l Python will show you an error the moment you press Enter key after hello (see below).
l
)
r
tile Ec{it Sheli Debug Qptions lVindorv Hejp
Python 3.7.6 {tags/v3.7.6:4336Aa?ae0, Dec L9 20L9,
T 64 bit (AI'{D64) I on win32
r Tlpe "help" r "copyrlght", "creditg"
n >>>5*3
h 18
(ii) Multiline Strings. Sometimes you need to store some text spread across multiple lines as
one single string. For that Python offers multiline strings.
(a) By adding a backslash at the end of normal single-quote I double-quote strings. In normal
strings, just add a backslash in the end before pressing Enter to continue typing text on
the next line.
For instance,
OTE
md
Textl ='heIlo\ Do rtL;l indart ,.t.,ltttt tortlil- A basic string must be completed
,**..* on a single line, or continued
world' 4,*'* t.tittg, t,*pirtp, itt trcr! iint ut'tar
with a backslash (\) as the very
t#,' last character of a line if it is to be
Following figure shows this : closed with a closing quote in
next line.
(b) By tyfins the text triple quotation marks. (No backslash lr-
needed at the end of-in
line).
t yihon allows to type multiline MorE
text-strings by enclosing t-hem A multiline string
in triple quotation marks conti
(both. triple apostrophe until the concluding trip
or triple qJorurror., marks will
work). r-' or triple-apostrophe.
)i
Or
Str2= """He11o
Wonld.
This is another multilrne stning.
...- : : -:
';l-ll.:--'ii$,' +
print( Str2
1::i i.! - - -*
>>> )
He11o
!{or1d -
?his is another multiline string.
Slze of Strings
Python determines the size of
a string as the count of cha
string "abc" is 3 and orheuo,
i"s. i",.,r y.r. ,,;;;"ii';?T;:'JilHilr;!{rffi!r"r:^i:;
to count the"escape ;"?;;;." as
#ffi,J:-tl""}ffiAsure one chaiacter. Consider so
For multiline strings created with triple quotes, while calculating size, the EOL (end-of-line)
::aracter at the end of the line is also counted in the size. For example, if you
have created a
.::ing Str3 as :
Brrl bdr'ls/rr.'lrc-i I ': ) ot lltt
Stn3 = "'a J q'*-*.-*.lltt:c lLnlc'r kc";s) rlrc c'orrsirl- n st n = ' ' ' he\'*----:* Littl oi' !tttarurctliute lirtts urL
t'retl tts fl()l (Etrtl tt.l-l'iticj tlct Loullal itt titc ''i.a oj
bJ4*- itt tlrc
t'itru'ot'tr,rs urtLl cortntet.l
lt\ 4-* thc tnultilirie srrings
' l"'trytlt r.l-tttititiiirte string
follow
::en size of the string str3 is 5 (three characters a, b, c and two EOL characters that
,:raracters a and b resPectivelY).
character at end of the
For maurltiline strings created with single/double quotes and backslash
string ; also you
line, while calculating size, the backslashes are not counted in the size of the
:annot put EOLs using return key in single/double quoted multiline strings
e'g',
Str4 ='a\
b\
c'
he size of string str4 is 3 (only 3 characters, no backslash counted.) /v 6=iT
To check the size of a string, you may also type len(<stringname>) Use len(<object name>) to get
in window shell as the size or length of an object.
.omxyrand on the Python prompt console
.hown in the following figure :
rsigtredl integers) often called just integers or ints, are positive or negative whole
numbers with no decimal Point.
:,.:r (floa'eing point real values) floats represent real numbers and are written with a decimal point
dividing the integer and fractional parts'
:rlex (eomplex numbers) are of the formq+bf,whete a andb arefloats and/(orf ) represents
,,''i, (*ni.n is an imaginary number)' a is the real part of the number'
and b is the imaginary Part.
138 COMPUTER SCIENCE WITH P''-_ -,-
Let us talk about these literal types one by one. A hexadecimal value can contain o:i:m
and letters A-F only i.e., 0XBK9, ::,
lnieger Liierols 0x79AZ etc., are examples oi i'
Integer literals are whole numbers without hexadecimal numbers as ther' .-:
any fractional part. The method of writing invalid letters, i.e.,.letters other than r.-i
integer constants has been specified in the Flooting Point Liierols
following rule :
Floating literals are also called real literai
An integer constant must have at least one literals are numbers having fractional :
digit and must not contain any decimal point. It
These may be written in one of the fzr'. ::
may contain either (+) or (-) sign. A number
called FractionalForm or the Exponent I
with no sign is assumed to be positive.
Commas cannot dppear in an integer constant.
'1..
Fractional form. A real literal in Flac
Form consists of signed or unsigned 'l{
OTE including a decimal point between digir.
Many programming languages such as C, C++, and even The rule for writing a real literal in frac:,
Python 2.x too have two types for integers : int (for small form is :
integers) and long (for big integers). But in Python 3.x, there A real constant in fractional form must ;: t
is only one integer type <class'int'> that works like long
least one digit with the decimal poin: i
integers and can support all small and big integers.
before or after. It rnay also have eithe' - :-
sign preceding it. A real constant with nc : ;'
Python allows three lypes of integer literals :
assumed to be posittve.
(i) Decimal Integer Literals. An integer literal
consisting of a sequence of digits is taken to The following are valid real literal-.
be decimal integer literal unless it begins fractional form :
.,;:)',",:"'::
torm : \,.0r:;',",",*\
I,,tl:J;tli:iJ:?I#Iilil;i*:i:
.iterals in exponent \ '" ""_': \ need arises'
;:;;ruf-j',.:ET:. ,T?.:,rl::1":f'l'
-
,
'.:)E-3,t72.F;3,
, ,.qrirut"nt
to
1t"t#
3'oE3)
III{fi ffi,
-,.^a PYthon one of the True and False are the
"p*."ai"g rs ;; to ,?
U 6.:iT'
followrng or
r .n i{ there is ,-ro
, 3.x will ',l,Jo'"iloot"ur.
'Jp'"'"tt values onl, ,*o Boorean titeral
: _.: of a decimai ffiil;*n
point' "'"':",:_^, (Boolean Pvthon' None
i.e., True y.uru":-in
it right)
-;rrer in
"
real literals
invalid tear
-. folrowing are invarid
litetai> '^' t""; o'ou""iil.,*u" 'lt'":i:j"ot"""tsabsen'ce
or a varue
b = 17 ,225EOZ
literals are available in Spthon ? Start a Python IDE of your choice and do as directed.
2, How many types of integer literals are ;
allowed in python ? How are they
>>>ttt<<<
written ?
Python ?
Arithmetic operotors
10. Name some built-in literals of
ft1thon.
+ Addition _ Subtraction
11. Out of the following literals, determine * Multiplication
their type whether decimal / / Division
octal / % Remainder/ Modulus
hexadecimal integer literal or a floating
point literal in fractional or exponent
** exponent (raise to power)
form or string literal or other ? ll Floor division
723, 0o1,24, OXABC, ,abc,, ,,ABC,,
, Bitwise operotors
1,2.34, 0.3E-0r.,,,ft9hjkj1,,,.
None, True, False
& Bitwise AND
^ Bitwise exclusive OR (XOR)
12. What kind of program elements are the
foltowing ?
I Bitwise OR
'a', 4.38925, ',a,,, ,,main, ?
Shift operotors
13. What witl varl and vatl store
with statements : varl = Z,72tE? and ldeniity operotors
var2 = O.?,IZLEZ ? Vfhat are the types
of vatues stored in varl and var2 ?
is is the identity same ?
is not is the identity not same ?
: : PYTHON FUNDAMENTALS 1.41
" i--)
i-re l'ji 1 [', i 3 A::,,,rirr :;:i;n, c,d_ eiiii;:rs
Less than ,- Assignment
Creater than i,- Assign quotient
Less than or equal to r---. Assign sum
Greater than or equal to i..- Assign product
Equal to '',,.- Assignremainder
Not equal to . Assign difference
i'r-. Assign Exponent
t:-, Assign Floor division
')C)aiJ!CtS ;.',g1ri-'r'" S'',:i, '-jl)?\ i)'tJf -.
Irrre about these operators you will learn in the due course. Giving descriptions and examples
rrot feasible and possible right here at the moment.
lllili* uS REV|SE
- ;ken is the smallest individual unit in a program.
:' ',':on provides
following tokens : l<qwords, identifiers (names),Values (literals), punctuators, operators and comments.
' - i,.word is a reserved word carcying special meaning and purpose.
:'rifiers are the user-defined names for different parts of the program.
- -D_lthon, an identifier may contain letters (a-2, A-Z), iligis (0-9) and a symbol underscore (_). However, an
-.'.tifier mustbeginwith a letter or underscore ; all letters/digits in an identifier are significant.
':"ols are the
fixed values.
' ',",on allows following literals : string literal, numeric (integer, floating-point literals, Boolean literals, special
":1 None and literal collections).
.:-ators are tokens that trigger some computation / action when applied to variables and other objects in an
: "ession.
: -.-ruotors are symbols used to organize programing-sentence structures and indicate the rhythm and emphasis of
-essions, statements and program-strucfurb.