Python Revision Tour Chapter - 1 Sumita Arora
Python Revision Tour Chapter - 1 Sumita Arora
Revision Tour
In Tis Chapter
1.1 Introduction
1.8 Expressions
1.2 Tokens in Python
1.9 Statement Flow Control
1.3 Barebones of aPython Program 1.10 The if Conditionals
1.4 Variables and Assignments 1.11 Looping Statements
1.5 Simple Input and Output 1.12 Jump Statements break and continue
1.6 Data Types 1.13 More on Loops
1.7 Mutable and Immutable Types
1.1 INTRODUCTION
You must have enjoyed learning Python in class XI. Python programming language, developed
by Guido Van Rossum in early 1990s, has become a very popular programming language
among beginners as well as developers. The journey of Python that you started in class XI will
continue in class XII as well. In class XIL, you shall learn more about Python and some advanced
Concepts. Before we start with newer topics and concepts in Python, let us revise all that vou
have learnt in class XI. And this chapter will be doing just the same, i.e., take you to the revision
class.
tour of Python that you learnt in your previous
COMPUTER SCIENCE WITH PYTHON
2 XI
for a1 in range(110) r
punctuators
i f a%2 == 0:<
keywords literals
print(a1)
operators
identifiers
1.2.1 Keywords
Keywords are predefined words with special meaning to the
KEYWORD
A keyword is a word
language compiler or interpreter. These are reserved for having
Special meaning reserved by
special purpose and must not be used as normal identifier
programming language.
names.
1.2.3 Literals/Values
Literals are data items that have a
fixed/constant value.
Python allows several kinds of literals, which are being
given below.
) String Lterals
A string literal is a
sequence of characters surrounded by quotes (single or double or triple quotes).
String literals can either be
single line strings or multi-line strings.
Single line strings must terminate in one line i.e., the closing quotes should be on the
same line as that of the opening quotes. (See below)
Multiline strings arestrings spread across multiple lines. With single and double quotes,
each line other that the concluding line has an end character as \
(backslash) but with
triple quotes, no backslash is needed at the end of intermediate lines. (see below):
Text2 = "Hello\
World "
Multi-line string
Text3 '''Hello
No backslash needed
World'
In strings, you can include non-graphic characters through escape sequences. Escape sequences
are given in following table
i Numeric Literals
can be one of the following types
and these
numeric values
literals are
Numeric
are positive or negative whole
or ints,
just integers
often called
(a) int (signed integers)
decimal point.
numbers with
no
be written in :
1-9. e.g., 1234, 4100 etc.
literals can
The integer
beginning with digits
Decimal
form: an integer
with 0o (zero
followed by letter o) eg ,0035, Oo77 etc.
a n integer
beginning
Octal form: invalid digits.
Octal, 8 and9
are
remember that for letter X) eg., Ox73,
Here do followed by
with Ox (zero
form: an integer beginning hexadecimal
numbers are 0-9 and
Hexadecimal
digits/letters for
remember that valid
0xAF etc. Here
A-F. real numbers
literals floats represent
literals or real
Point Literals. Floating point
a r e numbers
and fractional parts
(b) Floating dividing the integer or in
and are written
with a decimal point
fractional form e.g.,
-13.0, .75, 7. etc.
c a n be
written in
fractional parts. These
having
0.17E5, 3.E2, 6E4
etc.
Exponent form e.g., and J (or j) represents
where a and b are floats
number literals are of
the form a + b], is the imaginary
(c) Complex the real part of
the number, and b
number). a is
-1, which is an imaginary
part.
(ii) Boolean Literalss
one of the two
Boolean values i.e., True (Boolean
is used to represent
A Boolean literal in Python have value as True or
as False.
A Boolean literal c a n either
true) or False (Boolean false).
Literal None
iv) Special None literal is used to indicate
absence of
has one special literal, which is None. The
Python
value.
in the form of tuples and lists etc.
Python can also store literal collections,
1.2.4 Operators
to variables and other
Operators are tokens that trigger some computation /action when applied
objects in an expression.
shift
The operators can be arithmetic operators (t,*7,%, **, 1D,
bitwise operators (&, ", 1),
operators (s, >), identity operators (is, is not), relational operators s H),logical
and
operators (and, or), assignment operator (), membership operators (in, not in),
arithmetic-assignment operators (=t 7%= **=, IA).
1.2.5 Punctuators
Punctuators are symbols that are used in programming languages to organize sentence
structures, and indicate the rhythm and emphasis of expressions, statements, and program
structure.
Most common punctuators of Python programnming language are
"# ) []00,:
Chapter : PYTHON REVISICON TOUR
A Python program may contain various elements such as comments, statements, expression1s etc.
Let us talk about the basic structure of a Python
program.
#This program shows a
program s components
# Definition of function SeeYou () follows
Comments
def SeeYou ()
Function
(begin with # ) print ("Time to say Good Bye !!")
a= 15
Statements
b a-10
Expressions
(comnent beginning
see indented lines) * else: in the middle of a line)
print ("Value of 'a' was 15 or less initially.")
Function call
SeeYou() # calling above defined function SeeYou()
As you can see that the above sample program contains various components like:
Expressions, which are any legal combination of symbols that represents a value.
Statements, which are programming instructions.
Comments, which are the additional readable information to clarify the source code.
Comments can be single line comments, that start with # and multi-line comments that
can be either triple-quoted strings or multiple # style comments.
Functions, which are named code-sections and can be reused by specifying their names
(function calls).
Block(s) or suite(s), which is a group of statements which are part of another statement or
a function. All statements inside a block or suite are indented at the same level.
6 shown below
to these values
as
create labels referring
Python will internally
Jacob'
Student
16
Age
It will assign the values order wise, i.e., 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.
If you want to swap values of x and y, you just need to write as follows
X, y =y,X
ln Python, assigning a value to a variable means, variable's label is referring to that value.
val 3
val 6
3000
3000 3010 3032 3048
[for statement
3
3000
val = 3]
3 4 5 6
6 val 6]
val
Memory address (3000) Memory address [3048] storing
storing value 3 is assigned a value 6 is assigned a label as
Variable val stores values at same location
val for statement val = 6].
(memory-address) and changes values label as
val ffor statement val = 3] Now val no longer is referencing
stored in it.
to memory location 3000.
For example,
name input ( "What is your name ? ')
This 'PriP session is aimed at revising various concepts you learnt in Class X
>>><<
(i) Lists
A List in Python represents a group of comma-separated values of any datatype between
lists:
square brackets eg., following are some
[1, 2, 3, 4, 5]
['a', 'e, 'i', 'o', 'u']
[Neha', 102, 79.5]
In list too, the values internally are numbered from 0 (zero) onwards i.e., first item of the list is
An expression having literals and/or variables of any valid type and logical operators is a
logical expression. For example, these are valid logical expressions:
a or b, b and c, a and not b, not c or not b
Python also provides two string operators + and *, when combined with string operands and
integers, form string expressions.
Following are some legal string expressions
"and"+"then" #would result into 'andthen' concatenation
"and" * 2 # would result into 'andand' replication
ln a
Repeat till the final result is obtained.
mixed arithmetic expression, Python converts all operands up to the type of the largest
(e-8»
operand (type promotion). In the simplest form, an expression is like op1 operator opz
x/y or p * a). Here, if both arguments are standard numeric types, the following coercions a
applied:
I f either argument is a complex number, the other i1s NOTE
converted to complex; conversion 1s a
An implicit type
the
Otherwise, if either performed by
argument is floating point a conversion
compiler without programmers
number, the other is converted to
floating point; intervention.
No conversion if both operands are integers.
Chapter:PYTHON REVISION TOUR 15
Table operator precedence
Operator Description
Parentheses (grouping) Highest
*
Exponentiation
Bitwise nor
+X,-X Positive, negative (unary +, )
,1,11,% Multiplication, division, floor division, remainder
Addition, subtraction
Bitwise AND
Bitwise XOR
Bitwise OR
=, >, >=, <>, !=, =5 Comparisons (Relational operators), identity operators
is, is noot
or Boolean OR Lowest
Example 1.1 Consider below given expressions what. What will be the final result and final data type ?
int int
Here, the operator is /, wvhich always
gives floating pt result.
floating pt
(b) In expression (c) In expression
C = 6.0%3 %
C =6//3 b a
C 2 C 0.0
int float
Example 1.2 How wvonld follouving relational expressious be internally interpreted by Python?
(i) a<= N<=b
(i)p>q<
Solution. ()(p>q) and (q< )
(i)The precedence of logical operators is lower than the arithmetic operators, so constituent
arithmetic sub-expression (if any) is evaluated first and then logical operators are
applied, e.g-
25/5 or 2.0 + 20/10 will be first evaluated as: 5 or 4.
Solution. False
int (b)
5. Function Prototype
No. (General Form) Description Example
1. ceil math.ceil(num) The ceil() function returns the
| math.ceil (1.03) gives 2.0
smallest integer not less than
num.| math.ceil(-103) gives -10.
2 sqrt math.sqrt (num) The sqrt(O function returns the | math.sqrt (81.0) gives 9.0.
square root of num. If num <0,
domain error occurs.
.
log mathlog (num, [base]) The log() function returns the math.log(1.0) gives the natural
natural logarithm for num. A| logarithm for 1.0.
domain error occurS if num 1s
math.log
negative and a range error occurs logarithm(1024,
2) will give
of 1024 to the base 2.
if the argument num is zero.
7. logl10 math.log10 (num) The log10() function returns math.log10 (1.0) gives base 10
the base 10 logarithm for num.| logarithm for 1.0.
A domain error occurs if num is
negative and a range error
occurs if the argument ; zero.
8.
pow math.pow (base, exp) The pow( ) function returns base| mathpow(3.0, 0) gives value of
raised to exp power i.e,. base exp. | 30
A domain error occurs if base =0| math.pow (4.0, 2.0) gives value
and exp =0; also if base <0 and of 42.
exp is not integer.
and returns
precision, math.fmod(-8.3, 6) gives value
result with the sign of x (unlike as-2.3000000000000007
>>><<<
Chapter:PYIHON REVISION TOUR 19
LET US REVISE
A Python program can contain various components like expressions, statements, comments, functions, blockS and
indentation.
promotion or coercion.
and it is done using type conversion
The explicit conversion of an operand to a specific type is called type casting
<type conversion function > ( <expression>)
functions that is used as
1. Compound Statement
statements executed as a unit. The compound
statement represents a group of
A compound shown below:
statements of Python are written in a specific pattern as
<Compound statement header>:
statements>
simple and/or compound
<indented body containing multiple
statements, 1.e., they contain other statements.
are compound
The conditionals and the loops
For all compound statements, following points
hold:
written in the same column as the control statement,
statements are not
The contained called a block.
indented to the right and together they are
rather they are
contains a colon (:) at the end of it.
statement, 1.e., its header
The first line of compound
For exannple:
number1") )
num1 int(input("Enter
number1"))
num2 int (input("Enter The colon (:) at the end of header line
i fnum2< num1: means it is a compOund statement
t num2
* num2
The contained statements within if are
t t+10
indented to the riglt
2. Simple Statement
Compound statements are made of simple statements. Any single executable statement 1S a
3. Empty Statement
The simplest statement is the empty statement i.e., a statement which does nothing. In Python
pass
Wherever Python encounters a pass statement, Python does nothing and moves to next
nothing:
of the if statement is as
The syntax (general form)
shown below: Test False
Expression
if <conditional expression> :
?
statement
True
[statements]
Body of if
For example, consider the following code fragments
using if conditionals
if grade == "A :
print("Congratulations! You did wel1")
ifa>b:
print("A has more than B has")
print("Their difference is", (a-b))
Test False
1.10.2 The if-else Conditional Statement Expression Body of else
?
This form of if statement tests a condition and if the
condition evaluates to true, it carries out statements True
indented below if and in case condition evaluates Body of if
to false, it carries out statements indented below
else.
Chapter 1:PYTHON REVISION TOUR
21
The syntax (general form) of the if-else statement is as shown below
if <conditional expression>
statement
[statements]
else:
statement
[statements]
For example, consider the following code fragments using if-else conditionals
ifa >=e :
Thecolon (:) is in both: the if
print (a, "is zero or a positive number") header as well as else line
if <conditional expression>
statement
[statements]
elif <conditional expression>
statement
[statements]
and
i f <conditional expression>:
statement
[statements]
elif <conditional expression>
statement
[statements]
else
statement
[statements]
COMPUTER SCIENCE WITH PYTHON- X
22
Consider following two example code fragments
i fnum<0:
print (num, "is a negative number. ")
e l i f num== 0 :
print(num, "is equal to zero. ")
else
print (num, "is a positive number. ")
Irogram : "))
number (0..999)
num int (input("Enter a
i f num < 0:
Valid range is e to 999. ")
print ("Invalid entry.
e l i f num < 10:
number is entered")
print("Single digit
elif num < 100
number is entered")
print(" Two digit
e l i f num <= 999:
number is entered")
print("Three digit
else:
print("Invalid entry. Valid range
is 0 to 999.")
4
Enter a number (0..999):
entered
Single digit number is
ify<z
min, mid, max = X, y, Z
else
min, mid, max = x, Z, y
ifx<Z:
min, mid, max =y, X, Z
else
min, mid, max = y, Z, X
else
ifx<y
min, mid, max = z, Xx, y
else:
min, mid, max =
z, y, x
Write
1.4 a
The sample run of this program is just the same as previous program.
The above-given for loop executes a sequence of statements for each of the elements
given sequence [10, 15, 20, 25.
To keep the count, it uses a control variable (element in above case) in that takes a
difteren
value on each iteration. Firstly value 10, then the next value of sequence, 15, then 20 ana
lastly 25.