0 ratings0% found this document useful (0 votes) 161 views21 pagesPython Fundamentals 1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
Pythofi 9)
Fundamentals —
— . ev
In Wis Cha
2.1 tnvodueon
24 Barebones ofa Ptton Progam
22. Python Character Se
25. Variables and Assignments
23. Token
ken, 2.6. Simple input and Output
YWwrropucron }
y
‘You must have heard the term IPO - Input, Process, Output. Most (in fact, nearly all) daily life
and computer actions are governed by IPO cycle, That is, there is certain Input, certain kind of
Processing and an Output
Do you know that programs make IPO cycle happen ?
[Anywhere and everywhere, where you want to transform some kind of input to certain output,
youhave some kind of input to certain output, you have to have a program.
hat govern the jing) In other words, a program forms the base for
processing.
In this chapter, we shall be talking about all basic elements that a Python program can contain.
You'll be learning about Python’s basics like character set, tokens, expressions, statements, simple
input and output etc. So, are we all ready to take our first sincere step towards Python
Programming ? And, here we go :-)-
Scanned with CamScannerCOMPUTER SCIENCE WITH PYTHON,
2.2. PYTHON CHARACTER SET
Character set isa set of valid characters that a language can recognize. A character rep
any letter, digit or any other symbol. Python supports Unicode encoding standard. That
Python has the following character set :
© Letters A-Z, az
© Digits a9
Special symbols space +-*/ **\() [] {}/,
a. <= >= @_(underscore)
© Whitespaces Blank space, tabs (>), carriage return (.1), newline, formfeed,
© Other characters Python can process all ASCII and Unicode characters as part of
data or literals,
2.3. TOKENS
Ina passage of text, individual words and punctuation marks are called tokens or lexical units or
lexical elements. The smallest individual unit in a program is known asa Token or a lexical unit.
Python has following tokens :
() Keywords (i) Identifiers (Names) (ii) Literals
(jv) Operators») Punctuators ead
Let us talk about these one by one.
2.3.1 Keywords
A keyword is a word having
special meaning reserved by
Programming language,
Python programming language contains the following
keywords :
False assert del. = for. in or while
None break elif from is. pass with
True class else global lambda raise yield
and continue except if nonlocal retum
as def finally import. not try
2.3.2 Identifiers (Names)
Identifier forming rules of Python are being specified below :
© An identifier is an arbitrarily long sequence of letters and digits. 4
' , _ © The first character must be a letter; the underscore (_) counts as a letter. L
Scanned with CamScannerXe
‘Copter 2: PYTHON FUNDAMENTALS
‘© Upper and lower-case letters are different. All characters are significant.
‘© The digits 0 through 9 can be part of the identifier except for the first character.
‘© Identifiers are unlimited in length. Case is significant ie,, Python is case sensitive as it
treats upper and lower-case characters differently.
® An identifier must not be a keyword of Python.
‘© An identifier cannot contain any special character except for underscore (_).
The following are some valid identifiers :
Myfile DATES 7.77 z2r@79
MYFILE ps HO13_3k
CHK FILES 2g
The following are some invalid identifiers:
DATA-REC contains special character - (hyphen)
(other than A.-Z, a ~2 and _ (anderacote))
29cLcT Starting with a digit
break reserved keyword,
My. file
Contains special character dot (.)
2.3.3 Literals / Values
Literals (often referred to as constant-Values) are data items that have a fixed value. Python
allows several kinds of literals :
(i) String literals (ii) Numeric literals
(ii) Boolean literals
(iv) Special Literal None _(v) Literal Collections
2.3.3A. String Literals
For example, ‘a’, ‘abc, “abe” are all string literals in Python.
"2 - Unlike many other languages, both single character
“Z enclosed in quotes such as “a” or ‘x’ or multiple characters
1. What is meant by token ? Name the enclosed in quotes such as “abc” or ‘xyz’ are treated as
tokens available in Python. String literals.
2. What are keywords ? Can keywords be
used as identifiers ?
3. What is an identifier ? What are the
identifier forming rules of Python ?
4. Is Python case sensitive ? What is
As you can notice, one can form string literals by enclosing
text in both forms of quotes ~ single quotes or double
quotes. Following are some valid string literals in Python :
‘astha’ "Rizwan"
‘Meant by the term ‘case sensitive’ ? ‘HelloWorld — “Amy?s"
5 Which of the following are valid "129045"
identifiers ang why/why not : "1-x-0-w-25)
Datasec, data, 1 data, datat, my.fil
eee . erage: "112FB0291"
ii, switch, lambda, break
Scanned with CamScannerCOMPUTER SCIENCE Wink PYTHON,
is yhic-characters in String values, Ne i
Python allows you to have certain nongrap) 8 Values. Nongraphic chg
are those characters that cannot be typed directly from keyboard e.g, backspace, tabs, cal
retum etc. (No character is typed when these keys are
STRING LITERALS
A string literals a sequence
Characters surrounded by
(inl or double or tip quot
Following table (Table 2.1) gives a listing of escape sequences, |
Table 2.1 Escape Sequences in Python a
fea What it does Escape | What it does
parece [Nongraphic character] | sequence [Non-graphic character]
\\ Backslash (\) \r Carriage Retum (CR)
\ Single quote (’) \t | Horizontal Tab (TAB) |
\" Double quote (") \wo0.x Character with 16-bit hex value
vox (Unicode only) i
\a ASCII Bell (BEL) \Urococax | Character with 32-bit hex value 5
‘ xe0000%xX (Unicode only) ;
\b ASCII Backspace (BS) Ww ASCII Vertical Tab (VT)
\f ASCII Formfeed (FF) \o00 | Character with octal value o00
\n New line character \xhh Character with hex value hh
\Niname} | Character named name in the
Unicode’ database (Unicode only)
In the above table, you see sequences representing \, ,". Though these characters can be typed
from the keyboard but when used without escape sequence, these carry a special meaning and
have a special purpose, however, if these are to be typed as iti, then escape sequences should
be used. (In Python, you can also directly type a double-quote §
inside a single-quoted string and vice-versa. eg,, "anu's" is a
valid string in Python)
String Types in Python
‘one line} To understand this, try typing the following in IDLE window and see yourselves
Texti= "hello.
there"
4, Unicode and ASCH are two character encodings dscused later in Chapter 13 (Data Represeitation). #
Scanned with CamScannerCChopler 2 : PYTHON FUNDAMENTALS
coe
Python will show you an error the moment you press Enter key after hello (see below)
ee
OS B%8o >FaaE
ao See
Biauthor: Suxtt
6
7
Te fy 6*3
uefa}: a8 Python shows ERROR when
you press Entarkoy without
Yn [2]: Text « * pelle ‘the closing quote
File “cloython-fnput-2-f98177e093519", Line 1
Tertt 2" belle
0
The reason for the above error is quite clear - Python by default creates single-line strings with
ad both single or double quotes. So, if at the end ofa line, there is no closing quotation mark for an
opened quotation mark, Python shows an error.
(ii) Multiline Strings. Sometimes you need to store some text spread across multiple lines as
one single string, For that Python offers multiline strings.
Multiline strings can be created in two ways :
(a) By adding a backslash at the end of normel singlequote | double-quote stings. In normal
strings, just add a backslash in the end before pressing Enter to continue typing text on
the next line. For instance,
Text = 'hello\ Do not indent wien continuing
oe world’ typing in net fine after"
Following figure shows this :
Even though writen in two nes
(separating witha), the textis
considered continous. Thats sting
“ing a baersash (Vat the
‘end of te ne lows you to
continue typing tostin next ine.
1o not forget to close the
string by having a osing
‘quotation mark
In [3]: Text
2 world"
veri
‘would be considered as ‘helloworta”
‘splay the string variable to see it
yourselt
in 4}: Tetd
outa]: ‘hellowrld
Gre ermands net nO Ore!
iwi give outputin Ot: 0
Scanned with CamScanner(©) By typing the text in triple quotation
needed at the end of line). Python a
For example,
Tine sing coated wih
thee single quotes
(opening a wel 2s closing)
Str1=
Hello
World.
‘In [6]: print(Str1)
mie There I Come |!
World,
‘There I Come!!! Cheers.
Cheers. above) oo
Please note itis singe sting
‘one mutine sting
= « eaves
> Or
tae ein. 8X yemere Jj
Qf mor 8G) cen | Str2= """Hello
ARTES codtna 8 salt) Hello World.
3Gauthor: Sunite Sih This is another multiline string.” This is another multiline string.
26
s In [8]: print(Ste2) MN
é Hello Muliine ting erated
7 World. vith hoe single quotes
This is another wltiline string. | opening and dong)
In (9):
Sapa
Size of Strings
Python determines the size of a string as the count of characters in the string. For example, size of
string “abc” is 3 and of ‘hello’ is 5. But if your string literal has an escape sequence contained
within it, then make sure to count the escape sequence as one character. Consider some
‘examples given below :
w sizeis 1 (\\ isan escape sequence to represent backslash)
‘abe size is3
"\ab" sizeis2 ( \a isan escape sequence, thus one character).
“Seema\’s pen” size is 11. (For typing apostrophe (’ sign, escape sequence \’ has been used).
za Amys" sizeis4 Python allows a single quote (without escape sequence) in
double-quoted string and vice-versa,
Scanned with CamScannerChapter 2 : PYTHON FUNDAMENTALS
For multiline strings created with triple quotes, while calculating size, the EOL (end-of-ine)
character at the end of the line is also counted in the size. For example, if you have created a
string St3 as :
Str: ‘But backslashes ( \ ) at the
These (enter keys) are consid- end of intermediate lines are
ba red es EOL (End-f-Line) ro coed in the of
i characters and counted inthe the malin sings.
c ength of multiline string. on"
then size of the string Str3 is 5 (three characters , b,c and two EOL characters that follow
characters a and b respectively),
For multiline strings created with
line, while calculating size,
single/double quotes and backslash character at end of the
the backslashes are not counted in the size of the string ; also you
cannot put EOLs using return key in single/double quoted multiline strings e,
Str4='a\
by
a
‘The size of string Str is 3 (only 3 characters, no backslash counted.)
To check the size ofa string, you may also type len()
rey command on the Python prompt in console window shell as
shown in the following figure :
este -E\PrtenWant. 8X Prteneree
Tiple quoted mine stings
‘also count EOL characters in
the size of the sting.
‘Singleldouble quoted stings
‘yped in mutpe tne with at
the end of each intermediate
fine do not count
in the size ofthe sting.
ni
out [4]
i (5]
2.3.38 Numeric Literals
‘The numeric literals in Python can belons
to any ofthe following our different numerical types:
tive whole
i ints, are positive or nege!
int (signed integers) often called just integers or ints, are pos!
numbers with no decimal point.
and
ting poin value its represent real numbers
Hang es) en yep
. shere a and b are. ar x ree,
cite) items aad sehr
‘and b is the imaginary part.
‘are written with a decimal point
_
Scanned with CamScannerCOMPUTER SCIENCE WITH PYTHON
Let us talk about these literal types one by one.
Integer Literals ;
Integer literals are whole numbers without any fractional part. The method of writing ings
constants has been specified in the following rule :
‘An integer constant must have at least one digit and must not contain any decimal
point. It may contain either (+) or (-) sign. A number with no sign is assumed to be
‘positive. Commas cannot appear in an integer constant.
Python allows three types of integer literals :
( Decimal Integer Literals. An integer literal consisting of a sequence of digits is taken to be
decimal integer literal unless it begins with 0 (digit zero),
For instance, 1234, 41, +97, ~17 are decimal integer literals. a
(i)
For instance, decimal integer 8 will be written as 0010 as octal integer, (8;) =10,)
and decimal integer 12 will be written as 0o14 as octal integer (12yy =14,).
contain only digits 0-7 ; 8 and 9 are invalid digits in an octal number
(iii) Hexadecimal Integer Literals. A sequence of digits preceded by Ox or OX is taken to be
an hexadecimal integer.
For instance, decimal 12 will be written as OXC as
hexadecimal integer.
Thus, number 12 will be written either as 12 (as decimal),
Ool4 (as octal) and OXC (as hexadecimal).
A hexadecimal value can contain digits 0-9 and letters
AF only ie., OXBK9, oxPQR, Ox19AZ etc,, are examples of.
invalid hexadecimal numbers as they contain invalid
letters, ie, letters other than A-F.
Floating Point Literals
Floating literals are also called real literals. Real literals are numbers having fractional parts
‘These may be written in one of the two forms called Fractional Form or the Exponent Form.
1, Fractional form, A real literal in Fractional Form consists of signed or unsigned digits
including a decimal point between digits.
The rule for writing a real literal in fractional form is :
A real constant in fractional form must have at least one digit with the decimal
Point, either before or after. It may also have either + or ~sign preceding it. A real
constant with no sign is assumed to be positive.
The following are valid real literals in fractional form :
20, 17.5, -13.0, — 0.00625, .3 (will represent 0.3), 7. (will represent\7.0)
= Scanned with CamScannerShopter 2 : PYTHON FUNDAMENTALS.
The following are invalid real literals :
7
417/2
17,250.26.2
17,250,262
2. Exponent form. A real literal
exponent, For instance,
A real constant in exponent form
Trantista must be either an integer or a proper real constant, The mantissa is followed
vy a letter E or e and the exponent. The exponent must be an integer.
The following are the valid real literals in exponent form : 152E05, 1.52607, 0.152608, 152.0E08,
152E48, 1520E04, —0.172E-3, 172.E3, .25E-4, 3.3 (equivalent to 3.0E3)
(Even if there is no preceding or following digit of a decimal point, Python 3x will consider
it right)
The following are invalid real literals in exponent form :
17E.
0.17E2.3
17,225E02
tuples in coming chapters ~ for now
‘The last invalid example value given
above (17,225e02) asks for a special
mention here.
Any numeric value with a comma in
its mantissa will not be considered a
legal floating point number, BUT if
you assign this value, Python won't
give you an error. The reason being
is that Python will not consider that
as.a floating point value rather a tuple.
Carefully have a look at the adjacent
figure that illustrates it.
We are not talking about Complex
numbers here. These would be
discussed later when the need arises:
5.8 can be written as 0.58% 10" = 0,58E01, where mantissa part is 0.58 (the
(No decimal point)
(-illegal symbol)
(Two decimal points)
(comma not allowed)
in Exponent form consists of two parts : mantissa and
has two parts : @ mantissa and an exponent. The
(No digit specified for exponent)
(Exponent cannot have fractional part)
(No conima allowed) (Do read following discussion after it
ju
J Python gives no error when
‘you assign a numeric value
init
In [2]: b = 17,225802 wih comm
In [3]: type(a)
out(3]: tuple
In [4]: type(b) en wi nt corn
4 7 the numeric values
ouele]= ele ‘commas in them as
1 umber (int lat)
In [5]: 8 :
uTas atuple-
outs]: (1, 234) or
In [6]: b eons
out [6]: (17, 22500.0)
Scanned with CamScannerCOMPUTER SCIENCE WITH PYTHON
9
2.3.3C Boolean Literals
‘A Boolean literal in Python is used to represent one of the two
Boolean values ie., True (Boolean true) or False (Boolean false).
2.3.3D Special Literal None
[tn [13]: Valued = 1¢ r
pn varie 1D .
a faluel Displaying a vara
oa f38) va ars
not show anything,
‘However, with print
‘The None value in Python means
iS mo useful information” oF "There's |e rag). vatue
nothing here.” Python doesn’t display
anything when asked to display the
value of a variable containing value as
None. Printing with print statement, on
the other hand, shows that the variable
contains None (see figure here).
tn [17]: print(Value2)
lone
iin [28]
Python supports literal collections also such as tuples and lists 3
ete. But covering these here would make the discussion too Boolean Ierals True, Fass
i a special literal are sor
complex for the beginning, So, we'll take them at a later time. Fbasial Newt! oA &
Python,
: 1
Se Bs ABOUT TOKENS Progress In Python 2-1
Start Spyder IDE through Anaconda Navigator or any other IDE of your choice.
the same order
(@) Write the expected result and then write the actual result that Python returned. }
(6) Do write the reason(s) behind the result returned by Python.
) 1. In front of the Python prompt Inf]: in IPythonConsole, type the following statements one by one, in
Solved Sample
Statement to | Expected | Actual ic ‘ 7
be typed result result
. T Tg a
anes | nothing | nothing | Python intemally assigns the value to abc123 but shows nothing.
35 25 | Value of abcl23 is displayed on screen
lee
fo: |
Please check the practical com
¢ g ponent-book ~ Progress in Computer ;
(Science with Python ond fill it there in PriP 2.1 under Chapter 2 after i
Practically doing it on the computer.
ppoticce
Scanned with CamScannerspr 2: PYTHON FUNDAMENTALS
Chopter
Si 2
“soft ate eras? How sany types of
es are available in Python ?
A Wow many types of integer literals are
allowed in Python ? How are they
woitten ?
3. Why ate characters \,, " and tab typed
using escape sequences ?
4, Which escape sequences represent the
newline character and backspace
character? An escape sequence
represents how many characters ?
5. What are string-iterals in Python ?
How many ways, can you create String
literals in Python ? Are there any
differences in them ?
6, Mhat is meant by a floating-point
literal in Python ? How many ways can
a floating literal be represented into ?
7, Write the following real constants into
7 exponent form :
23,197, 7.214, 0.00005, 0.319
8. Write the following real constants into
Ereactional fon
0.13804, 0.417E-06, 0.4E-5,
1202, 12.£02
9, What are the two Boolean literals in
“ython ?
10}\fame some built-in literals of Python.
U,-Out of the following literals, determine
their type whether decimal / octal /
hexadecimal integer literal or a floating
point literal in fractional or exponent
form or string literal or other ?
123, 00124, OxABC, ‘abc’, “ABC”,
12.34, 0.3E-01, “ftghjkjl”,
None, True, False
> What kind of program elements are the
following ?
‘a, 4.38925, “a”, “main” ?
By What will var and var? store
with statements : varl = 2,121E2 and
‘var2 = 0.2,121E2 ? What are the types
of values stored in var1 and var2 ?
- 23M Operators
Operators are tokens that trigger some computation when
applied to variables and other objects in an expression.
Variables and objects to which the computation is
applied, are called operands. So, an operator requires
some operands to work upon.
The following list gives a
brief description of the
operators and their functions
/ operators, in details, will be
covered in next chapter —
Data Handling,
Operators are tokens that
fer some computation /
action when applied to variables
‘and other objects. in an
expression.
Unary Operators
Unary operators are those operators that require one operand
to operate upon. Following are some unary operators :
+
not
Unary plus
Unary minus
Bitwise complement
logical negation
Binary Operators
Binary operators are those operators that require two
operands to operate upon, Following are some binary
operators :
Arithmetic operators
Mu
Addition
Subtraction
Multiplication
Division
Remainder Modulus
exponent (raise to power)
Floor division
Bitwise operators
&
Bitwise AND
Bitwise exclusive OR (XOR)
Bitwise OR
Shift operators
<<
>
Identity operators
is
is not
shift left
shift right
is the identity same ?
is the identity not same ?
Scanned with CamScannerCOMPUTER SCIENCE WITH PYTHON
6
Relational operators Assignment operators
< Less than Assignment
> Greater than Assign quotient
Assign sum
<= Less than or equal to
>= Greater than or equal to
= Equal to
!= Not equal to
*= Assign product
%= Assign remainder
Assign difference
‘Assign Exponent
J/= Assign Floor division
Membership operators
in whether variable in sequence
not in whether variable not
in sequence
Logical operators
and Logical AND
or — Logical OR
More about these operators you will learn in the due course. Giving descriptions and examples
is not feasible and possible right here at the moment.
@3a) Punctuators
Punctuators are symbols that are used in programming
languages to organize sentence structures, and indicate the
Punctuators are symbols that!
are used in programming
languages to. organize!
rhythm and emphasis of expressions, statements, and
vn structure programming-sentence
progr. 7 structures, and indicate the
‘Most common punctuators of Python programming language rhythm and emphasis of
expressions, statements, and
are:
program structure.
""aVOLI(O,2- >
‘The usage of these punctuators will be discussed when the need arises along with normal topic
discussions.
LET US REVISE
et
A token is the smallest individual unit in a program.
hon provides following tokens : keywords, identifiers (names), Values (Iterals), punctuators, operators and comment.
‘A keyword is a reserved word carrying special meaning and purpose.
Identifiers are the user-defined names for different parts of the program.
In Python, an identifier may contain letters (a-z,A-Z), digits (0-9) and a symbol underscore (_). However, 2
ideniifier must begin with a leter or underscore ; all leters/digits in an identifier are significant.
“Literals are the fixed values.
Python allows following literals : string literal, numeric (integer,
floating-point literals, Boolean literals, special
literal None and literal collections).
ied to variables and other objects in an
Operators are tokens that tigger some computation / action when ap
expression. 1
4 Punctuators are symbols used to organize programing: sentence structures and indicate the rhythm and emphasis
expressions, statements and programstrucure
Scanned with CamScanner
|
|
d
7
aBeraumpent ond
Chapter 2 : PYTHON FUNDAMENTALS
2.4 BAREBONES OF A PYTHON PROGRAM,
Let us take our discussion further. Now we are going to talk about the basic structure of a
Python program - what all it can contain, Before we proceed, have a look at following sample
code. Look at the code and then proceed to the discussion that follows. Don't worry ifthe things
are not clear to you right now. They'll become clear when the discussion proceeds.
7 j# This program shows a program’ s components
# Definition of function SeeYou() follows
os def SeeYou()
(bein with #) — Funetion
print ("Time to say Good Bye !!")
# Main progran-code follows now
a= 15
Statements = = a
Espresions
print ani ot
~
if bos # colonmeans it’s a block
y» print ("Value of 'a' was more than 15 initially.
Inline comments
(comment beginning
else: in the mid ofa line)
“a print ("Value of 'a' was 15 or less initially.")
seeYou() # calling above defined function SeeYou()
‘As you can see that the above sample program contains various components like :
© expressions © statements
© comments © function
© blocks and indentation
Let us now discuss various components shown in above sample code.
(i) Expressions
‘An expression is any legal combination of symbols that represents a value. An expression
represents something, which Python evaluates and which then produces a value.
Ea
Some examples of expressions are
5 legal
resins ha ae aol eee a 8
8 } ‘combination cf symbols that
represents ve
ce complex expressions ‘that produce a
9/4 | muewhenear!
ions ?
rrrrrt—5
Scanned with CamScannerS COMPUTER SCIENCE WITH PYTHoy
(i) Statement
While an expression represents something, a statement is a programming instruction that
something i.e., some action takes place. a
Following are some examples of statements :
print ("Hello") # this statement calls print function
instruction
rit that does some
‘ce, some action takes pace,
While an expression is evaluated, a statement is executed i.e, some action takes place. And itis
not necessary that a statement results in a value ; it may or may not yield a value. 4
Some statements from the above sample code are : !
azis
b=a-10 eee
: “A statement executes
print (a+3) “or may not yield a valu oi
if bc: _
(iii) Comments
Comments are the additional readable information, which is Comments are the additional
read by the programmers but ignored by Python interpreter. ‘readable Information to casi}
Im Python, comments begin with symbol # (Pound or hash (re use MS
pads agai an ‘omment in Python bein with
character) and end with the end of physical line. allyl dita il
end ofthe physica ine.
) In the above code, you can see four comments : onan
(i) The physical lines beginning with # are the full line comments. There are three full line
comments in the above program are :
# This program shows a program’ s components
# Definition of function SeeYou( ) follows
4#Main program code follows now
A Physical line isthe of
“complete line that you see
(i The fourth comment is an inline comment as it starts in computer whereas @
the middle of a physical line, after Python code (see i the one that Python sees
below) fonefull statement,
if b <5 :#colonmeans it requires a block
Multi-line Comments
What if you want to enter a multi-
multi-line comment in Python code in froo ways :
() Add a # symbol in the beginning of every physical line part ofthe multi-line comments,
es
line comment or a block comment 2. You can enter @
#Multi-l
## Related to the program in question.
# It helps clarify certain important things.
ine coments are useful for detailed additional information.
Scanned with CamScannerCChopler 2; PYTHON FUNDAMENTALS
(i) Type 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 things |
por 8
\
Tis ypeofmulinecommen sao knowns doting ou SEE
can either use triple-apostrophe ("") or triple quotes (""") to e
write docstrings. The docstrings are very useful in documen- Comments endlosed In ple
tation - and you'll lear about their usage later. eer ee
(iv) Functions
A function is a code that has a name and it can be reused (executed again) by specifying its
name in the program, where needed.
In the above sample program, there is one function namely _USTS:gTE TSH
SeeYou( ). The statements indented below its def statement 4 function is a code that has 2
are part of the function, [All statements indented at the same name and it can be reused
: evel below def SeeYou( ) are part of SeeYou(),] This function is _(executed again) by specifying
ss executed in main code through following statement (Refer to name in the program, where |
sample program code given above) needed
SeeYou() _ # function-call statement
Calling of a function becomes a statement ¢., print is a function but when you call print() to
print something, then that function call becomes a statement,
For now, only this much introduction of functions is sufficient. You will lar about functions in
details in Class 12.
(\) Blocks and Indentation
Sometimes a group of statements i part of another statement or function, Such a group of one
oor more statements is called block or code-block or suite. For example,
Four spaces together mark FD <5?
the ned indeweet ~ pint ("Value of 'b ds less than 5
print ("Thank you.")
‘This black wih ali
‘statements at same indentation
lol
ch as C, CH, Java etc, use symbols like curly brackets t0 show blocks but
Many languages su : 0
on doesn rather it uses indentation.
Python does not use any symbol for it,
PIRES eS
‘group of statements which are part of
eh another statement oF 2 function are |
cr tebe om
Consider the following example :
‘This isa block, part of if sateen
tmp =a ‘
PO Nace al statement insane beck Paton
are have same indentation level
b=tnp
“Tis statement isnot part of
print ("Thank you") “Epp boa He
indentation lve
es
Scanned with CamScannerSo 40 COMPUTER SCIENCE WITH PYTHON .
A group of individual statements which make a single code-block is also called a Suite jy
Python. Consider some more examples showing indentation to create block:
def check() :
_— Block inside function check( )
Two different on
indentation-levels ifc~ Statements requiring
code-block have a colon (:)
print ( Block / suite inside ene
. asa*2 else statement You cannot —_unne
b=b+10 indenta statement ; Python
raise error for that.
‘While working in Python, one should keep in mind certain style rules and conventions. In the following lines,
wwe are giving some very elementary and basic style rules :
Aatement Termination Python does not use any symbol to terminate a statement. When you end a physical
Codeine by pressing Enter key, the statement is considered terminated by default.
ylaximum Line Length Line length should be maximum 79 characters.
Lines and Indentation Blocks of code are denoted by line indentation, which is enforced through 4 spaces (not
tabs) per indentation level.
Blank Lines Use two blank lines between top-level definitions, one blank line between method/function definitions.
Functions and methods should be separated with wo blank lines and Class definitions with three blank lines.
Avoid multiple statements on one line Although you can combine more than one statements in one line using.
Symbol semicolon (;) between two statements, but it is not recommended.
Whitespace You should always have whitespace around
"3
operators and after punctuation but not with parentheses. Python
considers these 6 characters as whitespace : ‘ (space), ‘\n’
4. What is an expression in Python ? (newline), “\t’ (horizontal tab), “Wv’ (vertical tab), ‘\P (formfeed)
2. What isa statement in Python ? How is
a statement different from expression ?
and ‘\r’ (carriage return)
3, What is a comment ? In how many ways
can you create comments in Python ?
4, How would you create multiline
comment in Python ?
5, What is the difference between full-line
comment and intine comment ?
What is a block or suite in Python ?
How is indentation related to it ?
Case Sensitive Python is case sensitive, so case of statements is
Very important. Be careful while typing code and identifer-names.
)
Docstring Convention Conventionally triple double quotes
ate used for docstrings.
Idehtifier Naming You may use underscores to separate words in
an identifier e.g., loan_amount or use CamelCase by capitalizing
first letter of the each word e.g, LoanAmount or loanAmount
Scanned with CamScanner‘Chopter 2: PYTHON FUNDAMENTALS
eS
COMPONENTS OF A PROGRAM Progress InPython 2.2
jon 2.
iP
‘This is another program with different components
def oe a = dace Ph
| pone HO
#main code
dpe
Fill the appropriate components of program from the above code.
Science with Python and fill i there in PriP 2.2 under Chapter 2 after
é Please check the practical component-book ~ Progress in Computer
practically doing it on the computer.
moot,
2.5 VARIABLES AND ASSIGNMENTS
‘A variable in Python represents named location that refers o 8 value and whose values can be
it and processed during program run. For instance fo store ram ofa student and marks of
otudent during a program run, we require some labels to refer to these marks so that these can
be distinguished easily. Variables, called as symbolic variables,
conve the purpose. The variables are called symbolic variables yaypeq labels, whose values can
because these are named labels. For instance the following he ysed and processed dung
‘ble namely marks of Numeric type: program run, areal Variables
statement creates a varial
marks = 70
2.5.1 Creating « Variable
Recall the statement we used
marks =70
just now to create the variable marks : .
AAs you can see, that we just assigned the value of numeric type to an identiior name es
Python created the variable of the tyPe similar tothe type of value assigned. In short, after
above statement, we can say that marks 18 2 numeric variable.
So, creating variables was just that simple only ? Yes, you 7°
right. In Python, to create a variable, just assign to its name the
value of appropriate type. For example, 10 create a variable
Pee ariable age to hold
namely Student to hold student's name and variable
student's age, you just need to write ‘somewhat similar to what
is shown below :
Student = "Jacob!
Age = 16
Scanned with CamScannerPr |
COMPUTER SCIENCE WITH PYTHON
a
Python will internally create labels referring to these values as shown below :
Student | e}———+} ‘Jacob’
Age 16 |
Isn't it simple?? © Okay, let's now create some more variables.
TrainNo ="T#1234 # variable created of String type J
balance = 23456.75 # variable created of Numeric (Floating point) type
rol1No = 105 # variable create of Nuneric(integer) type
Same way, you can create as many variables as you need for your program.
IMPORTANT — Variables are Not Storage Containers in Python
If you have an earlier exposure to programming, you must be having an idea of variables. BUT
PYTHON VARIABLES ARE NOT CREATED IN THE FORM MOST OTHER PROGRAMMING
LANGUAGES DO. Most programming languages create variables as storage containers ¢,
Consider this :
5
age = 20
Firstly value 15 is assigned to variable age and then value 20 is assigned to it.
Traditional Programming Languages’ Variables
[Variable is a container in traditional
programming languages like C, C++,
415 ——_ i, itis a named storage location that|
stores a value in it)]
Statement
age
> 202530
Variable age is created as a container at a memory address,
: say 202530, and it stores value as 15 in it.
Notice memory address
(ocation) of variable Statement
age did not change with
change in its value age= 2
age x %. this statement will change the contents of the
: 20 location where variable age is created, i.e.,
aa With this statement, the location of the variable did
‘D> maw not change, only its contents changed.
‘This is ow traditionally variables were created in programming languages like C, C+, Javacete.
ee Lae
Scanned with CamScannerChopter 2 : PYTHON FUNDAMENTALS
Python’s Handling of Variables
BUT PYTHON DOES THIS DIFFERENTLY
Let us see how Python will do it,
Memory has literals/val
ees values at defined memory locations, and each memory location has a
When you give statement age =
ge = 15, variable age will
location where value 15 isstored fe,a8. He crested aaa poiingomenery
‘age now referring to location 20216 that has value 15
sment age = 20, the label age will not be having the same location as
0 value 20, which is at different location ie,
‘Now age is referring to location 20296
‘And when you give state!
earlier. It will now refer t
Zea,
14 415 M6
20200 20216 20282
variable age’s value is changed:
So this time memory location o!
i The
unlike other programming languages.
aes hange (This rule is not forall types of
in the next chapter, where We talk about Mutable
ave fixed
ytime theit
to you
‘Thus variables in Python donot hi
location they refer to changes eve
variables, though). It will become clea
and Immutable types.
Scanned with CamScannera 44 COMPUTER SCIENCE Wity PrTHON
Walves and Rvalues
Broadly Ivalue and rvalue can be thought of as :
Wvalue : expressions that can come on the Ihs (left hand side) of an assignment,
value : expressions that can come on the rhs (right hand side) of an assignment,
€8., you can say that
the objects to whig] |
a=2 You can assign a value gf Y
b=10 expression. Lalues can come
|hs oF rhs of an assignment
But you cannot say statement,
Fvalues are the literals an
expressions that ae assigned
ERROR con
values. Rvalues can come on ths
of an assignment statement.
frames can come on ths of an assignment, they are Ivalues, ,
Il as ths of an assignment,
HNGReo ge aaa
2.5.2 Multiple Assignments inpythen sana ove
ple Assig er :
Python is very versatile with assignments. Let’s see in how Yatiable means, variables
many different ways, you can use assignments in Python
Lvalues can come on hs as well
1. Assigning same value to multiple variables
You can assign same value to multiple variables ina single statement, eg,
It will assign value 10 to all three variables a, b,c That is,
all three labels a,b,c will refer to +
same location with value 10.
2. Assigning multiple values to multiple voriables
You can even assign multiple values to multiple variables in single statement, eg,
X,Y, 2=10, 20, 30
Iewill assign the values order wise, ie, first variable is given first value, second variable the second
value and so on. That means, above statement will assign value 10 to x, 20 to y and 30 to z
This style of assigning values is very useful and compact. For example, consider the code given
below :
x, y= 25, 50
print (x, y)
It will print result as
2550 —esnssisicisauabiaaiieunaeslls se
Scanned with CamScanner| 00 ,o0w
‘Chopter 2 : PYTHON FUNDAMENTALS
Because xis having value 25 and y is having 50. Now, if you want to swap val
just need to write : , ° i ened
% Vey x
print (x,y)
Now the result will be
50 25
Because this time the values have been swapped and x is having value 25 and y is having 50.
ae assigning values through multiple assignments, please remember that Python first
Valuates the RHS (right hand side) expression(s) and then assigns them to LHS, e $e
a,b, c=5, 10,7
b,c, a=a41, b+2,c-1 ‘# statement2
print (a, b, c)
# statement
© Statement assigns 5, 10 and 7 to a,b and c respectively.
© Statement2 will first evaluate RHS ie, «+1, b+2, c~1 which will yield
fe 541, 10+2,7-1=6, 12,6
‘Then it will make the statement (by replacing the evaluated result of RHS) as :
b,c, a=6, 12,6
Thus, b= 6, c= 12 and a=6
© The third statement print (a, b, ¢) will print
66 12
Isn't this easy ? Now can you guess the output of following code fragment?
P,q=3,5
q, r=p-2, p+2
print (p,q, r)
Please note the expressions separated with commas are evaluated from left to right and
assigned in same order e.g,
x=10
yy y= x42, x45 ;
will evaluate to following (after evaluating expressions on ths of = operator)
ys y= 42, 15
ie, firstly it will assign first RHS value to first LHS variable i.e.,
y=12
able ie,
then it will assign second RHS value to second LHS variable i.
a in 15.
So if you print y after this statement y will contain 19.
2, The output should be :3.15
Scanned with CamScanner