0% found this document useful (0 votes)
45 views20 pages

Python Revision Tour Chapter - 1 Sumita Arora

computer science class 12 cbse

Uploaded by

aviral.2648
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views20 pages

Python Revision Tour Chapter - 1 Sumita Arora

computer science class 12 cbse

Uploaded by

aviral.2648
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python

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

1.2 TOKENS IN PYTHON

The smallest individual unit in a program is known


as a loken
OKENS
or a lexical unit. The smallest individual unit
in a
program is known as a Token or
Python has following tokens :
a lexical unit.
(ii) Literals
) Keywords (ii) Identifiers (Names)

(o) Operators (o) Punctuators

#A sample Python program

for a1 in range(110) r
punctuators
i f a%2 == 0:<
keywords literals
print(a1)
operators
identifiers

Figure 1.1 Some tokens in a Python program.

Let us revise our understanding of tokens.

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.

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 return
as def finally import not try
1.2.2 ldentifiers (Names
Identifiers are the names given to difterent of the program viz.
parts variables, objects, cissesy
functions, lists, dictionaries and so forth.
The naming rules for Python identifiers can be summarized as follows:
Variable names must only be a
non-keyword word with
no spaces in between.

Variable must be made


names NOTE
up of only letters,
numbers, and underscore (L). Python is case sensitive as it

treats upper and lower-case


Variable names cannot begin with a number, although characters differently.
they can contain numbers.
Chapter 1: PYTHON REVISION TOUR
3
The following are some The following are some invalid identifiers
valid identifiers
DATA-REC contains special character (hyphen)
Myfile DATE9 7_77
MYFILE (other than A -Z, a - z and (underscore))
_DS
29CLCT Starting with a digit
CHK FILE13
z2T0Z9 break reserved keyword
HII3_JK
My.file contains special character dot (.)

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):

> Text1 = "Hello World"


Single line string

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

Escape What it does Escape What it does


sequence [Non-graphic character] sequence [Non-graphic character
Backslash (\) \r Carriage Return (CR)
Single quote (') t Horizontal Tab (TAB)
Double quote (") uxxxx Character with 16-bit hex value
XXXx (Unicode only)
a ASCII Bell (BEL) UxxxxXXXX Character with 32-bit hex value
xXXXXXXx (Unicode only)
\b ASCII Backspace (BS) ASCII Vertical Tab (VT)
ASCII Formfeed (FF) o00 Character with octal value ooo
n New line character xhh Character with hex value hh
Nname Character named name in the
Unicode database (Unicode only)
WITH PYIHON -XI
COMPUTER SCIENCE

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

1.3 BAREBONES OFA PYTHON PROGRAM

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 !!")

# Main program-code follows now

a= 15
Statements

b a-10
Expressions

print (a +3) Blocks

if b5 #colon means it' sa block

print ("Value of 'a' was more than 15 initially.") Inline comments


Indentation ...

(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.

1.4 VARIABLES AND ASSIGNMENTS


Variables represent labelled storage locations, whose values can be
manipulated during
program run.

In Pvthon, to create a variable, just assign to its name the value of


example, to create a variable Student
appropriate type. For
namely to hold student's name
and variable age to hold
student's age, you just need to write somewhat similar to what is
shown belowy
Student= 'Jacob'
Age 16
COMPUTER SCIENCE wITH PYTHON - XI

6 shown below
to these values
as
create labels referring
Python will internally
Jacob'
Student

16
Age

1.4.1 Dynamic lyping to it some value (ofa partint


defined by assigning
have learnt, a variable is
In Python, as you the statement
For instance, after
such as numeric, string etc.).
type
X = 10
value of integer type.
variable x is referring to a
We can say that to variable x, Python will not
a value of
some other type
Later in your program, if you reassign

complain (no error will be raised), e.8, DYNAM


X = 10 A variable pointing to a value of
a certain type, can be made to
print(X) point to a value/object of
X = "Hello World"
different type. This is called

print(X) Dynamic Typing.

Above code will yield the output as:


10
Hello World
values in our case

think of Python variables as labels associated


with objects (literal
So, you can
makes labei refer to new value with new assignment
dynamic typing, Python
a
here); with
illustrates it.
(Fig. 1.2). Following figure
X = 10
int:10

"Hello World" int:10

String: Hello World

Figure 1.2 Dynamic typing in Python variables.

Dynamic Typing vs. Static Typing vith à


is different from Static Typing. In Static typing, a data type is attachea
variable
typing
Dynamicwhen it is defined first and it is fixed. That is, data type of a variable cannot be change
in static yping whereas there is no such restriction in dynamic typing, which is supportecu
Python.
1.4.2 Multiple Assignments
Python is very versatile with assignments. Let's see how.
1. Assigning same value to multiple variables. You can assign same value to nu
variables in a single statement, e.g,
a = b = C = 10

It will assign value 10 to all three variables a, b, c.


Chapter1: PYTHON REVISION TOUR 1
2. Assigning multiple values to multiple variables. You can even assign multiple values to

multiple variables in single statement, eg,


x, y, z = 10, 20, 30

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

[for statement val

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.

Literal values are having a fixed location and variable


(a) In traditionalprogramming languages names reference them as labels.
like C/C++ etc.

(b) In Python programming language

traditional programming languages and in Python.


Figure 1.3 How variables are stored in

1.5 SIMPLE INPUT AND OUTPUT


user interactively, you can use built-in function input( ). The
In Python 3.x, get input from
to
the following manner:
function input() is used in
variable_to_hold_the_value = input (<prompt to be displayed>)

For example,
name input ( "What is your name ? ')

display the prompt as


The above statement will

In [3]: name = input ("uhat is vour rame)

**"What is your name Type your input data here


COMPUTER SCIENCE WITH PYTHON x
10
a number and print its square root.
1.2 Write a program to input

rogram num float (input ( 'Enter a number: "))


**
0.5
num_sqrt =num
print('The square root of, num, "is', num_sqrt)

PYTHON BASIC INPUT/OUTPUT Progress In Python 1.1


iP

This 'PriP session is aimed at revising various concepts you learnt in Class X

Please check the practical component-book - Progress in Computer


Chapter 1 after
Science with Python and fill it there in PriP 1.1 under
practically doing it on the computer.

>>><<

1.6 DATA TYPES


for it. Python offers
Data types are means toidentify type of data and set of valid operations
built-in core data types: (i) Numbers (ii) String (ii) List (iv) Tuple (v) Dictionary.
following
) Data types for Numbers
data types to store and process different types of numeric data:
Python offers following
(a) Integers
Integers (signed)
Booleans
(b) Floating-Point Numbers
(c) Complex Numbers

(a) Integers. There are two types of integers Python:


in

of whole numbers. Python 3.x


(i) Integers (signed). It is the normal integer representation
provides single data type (int) to store any integer, whether big or small.
It is signed representation, ie, the integers can be positive as well as negative.
is
Booleans. These represent the truth values False and True. The Boolean type
a
(i) 0
the values
subtype of plain integers, and Boolean values False and True behave like
and 1, respectively.
double
(b) Floating Point Numbers. In Python, floating point numbers represent machine-level
precision floating point numbers (15 digit precision). The range of these numbers is limited by
underlying machine architecture subject to available (virtual) memory.
(c) Complex Numbers. Python represents complex numbers in the form A + Bj. Complex
numbers are a composite quantity made of two parts: the real part and the inaginary part, both of

which are represented internally as float values (floating point numbers).


Chapler 1: PYTHON REVISION TOUR 11
You can retrieve the two components
using attribute
references. For a complex number z NOTE
z.real gives the real part. Python represents complex
numbers as a pair of floating
Z.imag gives the imaginary part as a float, not as a
point numbers.
complex value.
Table 1.1 The Range of Python Numbers

Data type Range


Integers an unlimited range, subject to available (virtual) memory only
Booleans Fwo values True (1), False (0)

Floating point an unlimited


range, subject to available (virtual) memory on
numbers underlying machine architecture.

Complex Same as floating point numbers because the real and


nunmbers imaginary parts are represented as floats.

(i) Data Type for Strings


All strings in Python 3.x are sequences of pure Unicode characters. Unicode is a system designed to
represent every character from every language. A string can hold any type of known characters
i.e., letters, numbers, and special characters, of any known scripted language
Following are all legal strings in Python:
NOTE
"abed", "1234", "5%&, ????', "SAEEá", "aßyr", T, Valid string indices are 0, 1,
2 .. upto length-1 in forward
"aH", "riae" direction and -1, -2, -3..
length in backward direction.
each character
A Python string is a sequence of characters and
can be individually accessed using
its index.

(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

numbered as 0, second item of the list as 1, 3rd item as 2 and so on.


internally
(v) Tuples NOTE
Tuples are represented as group of comma-separated values of Values of type list are mutable

any date type parentheses, e.g, following


within are some tuples i.e., changeable one can
change/add / delete a list's
p (1, 2, 3, 4, 1 elements. But the values of type
( 2 , 4, 6, 8) tuple are immutable i.e.,
r ('a', 'e', 'i', 'o', 'u') non-changable; one cannot
make changes to a tuple.
h (7, 8, 9, A', °B, 'C)
14 COMPUTER SCIENCE WITH
PYTHON X
1.8 EXPRESSIONSs
An expression in Python is any valid combination of
operators, literals and variables T
expressions in Python can
be of any type : The
arithmetic expressions, string expressions, relational
l
expressions, logicaB expressions, compound expressions etc.
Arithmetic expressions involve numbers (integers, floating-
point nunmbers, complex numbers) and arithmetic operators, An expression in Python is any
eg, 2 + 5 ** 3 , - 8 * 6/5 valid combination of
and atoms. An operators
expression is
An expression having literals and/or variables of any valid composed of one or
more
type and relational operators is a relational expression. For operations.
example, these are valid relational expressions:
X>y, y = Z, z!=X, z
==q, x <y>z, X == y!=z

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

1.8.1 Evaluating Arithmetic Operations


follows these rules:
To evaluate an arithmetic expression (with operator and operands), Python
Determines the order ofevaluation in an expression considering the operator precedence
in the form of
A s per the evaluation order, for each of the sub-expression (generally
<value> <operator><value> e.g., 13 % 3)
Evaluate each of its operands or arguments.
Performs any implicit conversions (e.g., promoting int to float or bool to int for
read the text
For implicit conversion rules of Python,
arithmetic on mixed types).
given after the rules.
Compute its result based on the operator.
with the computed result and carry on the expressiOn
Replace the subexpression
evaluation.

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

not x Boolean NOT

and Boolean AND

or Boolean OR Lowest

Example 1.1 Consider below given expressions what. What will be the final result and final data type ?

(a) a, b 3, 6 (6) a, b 3 , 6 a , b=3, 6.0


C = b/a C =b// a C = b% a

Ans. (a) In expression


C 6/3 b
C 2.0

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 int float int


L

int float

1.8.2 Evaluating Relational Expressions


All comparison operations in Python have the same priority, which is lower than that of any
arithmetic operations. All relational expressions (comparisons) yield Boolean values only i.e.,
True or False.
Further, chained expressions like a<bsc have the interpretation that is conventional in
mathematics it, comparisons in Python are chained arbitrarily, eg, a<b<c is internally
treated as a< b and b< c
16 COMPUTER SCIENCE WITH PYTHON
KI

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< )

(ii) (a<= N) and (N<=b)

1.8.3 Evaluating Logical Expressions


While evaluating logical expressions, Python follows these rules

(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.

So, the overall result will be 5.


(i) The precedence of logical operators among themselves is not, and, or. So, the expression
a or b and not c will be evaluated as:

(not c) )) imilarly, following expression ((p and q) or (not r))


(a or (b and
p and q or not r will be evaluated as :

(it) Important. While evaluating, Python minimizes intemal


work by following these rules
(a) In or evaluation, Python only evaluates the second argument if the first one is false toa
(b) In and evaluation, Python only evaluates the second argument if the first one is true roa

Example 1.3 What will be the output of following expression?


(5 «10) and (10 < 5) or (3 < 18) and not 8 < 18

Solution. False

1.8.4 Type Casting (Explicit Type Conversion)


An explicit type conversion is user-defined conversion that forces an expression to be of specific
type. The explicit type conversion is also known as Type Casting.
in Python is performed by <type>() function of appropriate data type, in the
Type casting
following manner
<datatype> (expression) TYPE CASTING
The explicit conversion of an
where <datatype> is the data type to which you want to
operand to a specific type is
type-cast your expression. called type casting.
For example, if we have (a = 3 and b = 5.0), then

int (b)

will cast the data-type of the expression as int.


Chapter 1: PYTHON REVISION TOUR
17
1.8.5 Math Library Functions
Python's standard ibrary provides a module
namely math for math related functions that work
with all number types for
except complex numbers.
In order to work with functions of math module,
you need to first inmport it to
giving statement as follows as the top line your program by
of your Python script:
import math
Then you can use math library's functions as
math.<function-name>.
Table 1.2 Some Mathematical Functions in math Module

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.

3. exp math.exp(arg) The exp() function returns the


| math.exp (2.0) gives the value
natural logarithm e raised to the | of e*.
arg power.
4. fabs math.fabs (num) The fabs() function returns the | math.fabs
(1.0) gives 1.0
absolute value of num. math.fabs(-10) gives 1.0.
5. floor math.floor (num) The floor() function returns the math.floor (1.03) gives 1.0
largest integer not greater than| math.floor(-1.03) gives -2.0.
num.

.
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.

9. sin The sin function returns the math.sin(val)


math.sin(arg) sine of arg. The value of arg (val is a number).
must be in radians.

10. COS The cos ) function returns the | math.cos(val)


math.cos(arg) cosine of arg. The value of arg | (val is a number).
must be in radians.
COMPUTER SCIENCE WITH PYTHONXI
18

Prototype Description Example


S.Function
No.
(General Form)
The tan) function returns the| math.tan (val)
11. tan math.tan(arg) value of arg (val is a number)
tangent of arg. The
must be in radians.

math.degrees (3.14) would give


The degrees() converts angle x

12. degrees math.degrees(r) from radians to degrees. 179.91

The radians() converts angle


x math.radians (179.91) would
13. radians math.radians(x) give 3.14
from degrees to radians.
math.fmod(7.4, 3.3) gives value
This function returns the
14 fmod math.fmod(x, y) from the
as 0.8000000000000007
modulus resulting
math.fmod(7.4, 3) gives value
division of x withy. as 1.4000000000000004
It is little different from x % y
that it offers more
math.fmod(-7.4, 3) gives value
in the sense t h e a s 1 . 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4

and returns
precision, math.fmod(-8.3, 6) gives value
result with the sign of x (unlike as-2.3000000000000007

x% y, which returns with sign


of y).
is preferred for floats,
fmod
because of higher precision
for
while x % y is preferred
integers.
math.factorial(4) gives value
factorial
math.factorial(arg) This function returns
15. factorial a s 24
of arg as an integer. math.factorial(6) gives value
It will raise ValueError if arg is as 720
not integral or is negative.
value as 2
This function returns the math.gcd (8, 6) gives
math.gcd(x, y) as 4
16. gcd greatestcommon divisor of the math.gcd(28, 20) gives value
integers x and y. If either x or y
is nonzero, then
the value of gcd(x, y) is the
that
largest positive integer
divides both x and y.
gcd(0, 0) returns 0.

DATA HANDLING 1.2


Progress In Python

session is aimed at various concepts you learnt in Class XI.


This PriP revising

Please check the practical component-book - Progress in Computer


Science with Python and fill it there in PriP 1.2 under Chapter 1 after
practically doing it on the computer.

>>><<<
Chapter:PYIHON REVISION TOUR 19

LET US REVISE

A Python program can contain various components like expressions, statements, comments, functions, blockS and

indentation.

Blocks are represented through indentation.


Python supports dynanmic typing i.e., a variable can hold values of different types at different times.
The input(O is used to obtain input from user ; it always returns a string type of value.
Ouput is generated through print() (by calling print function) statement.
Operators are the symbols (or keywords sometimes) that represent specific operations.
An expression is composed of one or more operations. It is a valid combination of operators, literals and variables.
makes it
Types of operators used in an expression determine its type. For instance, use of arithmetic operators
arithmetic expression.

Expressions can be arithmetic, relational or logical, compound etc.


In implicit conversion, all operands are converted up to the type of the largest operand, which is called type

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.9 STATEMENT FLOW CONTROL


be executed sequentially, selectively or iteratively. Every
In a program, statements may iteration.
constructs to support sequence, selection or
programming language provides
A conditional is which is executed, on the basis of result of a
a statement set
condition. A loop is
until the end condition is satisfied.
a statement set which is executed repeatedly,

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

print (num2, num1, t)


COMPUTER SCIENCE WITH
PYTHONX
20

2. Simple Statement
Compound statements are made of simple statements. Any single executable statement 1S a

simple statement in Python.

3. Empty Statement
The simplest statement is the empty statement i.e., a statement which does nothing. In Python

an empty statement is the pass statement.

Ittakes the following formn:

pass
Wherever Python encounters a pass statement, Python does nothing and moves to next

statement in the flow of control.

1.10 THE IF CONDITIONALS

in multiple forms: plain if conditional, if-else conditional


The if conditionals of Python come

and if-elif conditionals.

1.10.1 Plain if Conditional Statement


evaluates to true, a course-of-action
An if statement tests a particular condition; if the condition
set-of-statements is executed. If the condition
is false, it does
is followed i.e., a statement or

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

else The statements in if-block and else are


indented
print(a, "is a negative number")

1.10.3 The if-elif Conditional Statement


Sometimes, you want to check a condition when control reaches else, i.e., condition test in
the form of else if. To serve such conditions, Python provides if-elif and if-elif-else
statements.

The general form of these statements is

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

ifruns >= 100:


print ("Batsman scored a century")
elif runs >= 50:
print ("Batsman scored a fifty")
else
print("Batsman has neither scored a century nor fifty")

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. ")

then prints if the integer entered isa 1/2/3


integer in range 0 999 and
-

1.5 Write a program that


digit number.
inputs an

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.")

of this program are given below


Sample runs

Enter a number (O..999) -3


is 0 to 999.
Invalid entry. valid range

4
Enter a number (0..999):
entered
Single digit number is

Enter a number (0..999): 100


Three digit number is entered

Enter a number (0..999) : 10


TWo digit number is entered
S = = = < * = 3 < * = = *

Enter a number (0. .999) : 3000


Invalid entry. Valid range is 0 to 999.
Chapter: PYTHON REVISION TOUR 23
1.10.4 Nested it Statements
Sometimes you may need to test
additional conditions. For
if in situations,
supports nested-if form of if. A nested if is an if that has anothersuch its if's bodyP'ython aiso
or in elirs
body or in its else's body.
Consider the
following example code using nested-if statements:
X =
int(input ("Enter first number: "))
y int(input ("Enter second number: "))
z
int(input("Enter third number:"))
min = mid = max = None

if x <y and x < z

ify<z
min, mid, max = X, y, Z
else
min, mid, max = x, Z, y

if statements inside anotherif


elif y < x and y < z:
(Nested ifs)

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

print("Numbers in ascending order: ", min, mid, max)

1.10.5 Storing Conditions


Sometimes the conditions being used in code are complex and repetitive. In such cases to make
can use named conditions i.e., you can store conditions in a
your program more readable, you
conditional in the if statements.
name and then use that named

Consider the following example code:


b, C=2, 3

#Store condition in a name


called al11.

all a == 1 and b == 2 and c ==


3 .
this condition is given
TIP
#Test variable. name as all. Using Named or Stored
conditionals reduces repetition.
ifallprint ("Condition fulfilled") It may also improve processing
speed: fewer comparisons are
#Use it again. done
ifallprint("Condition fulfilled again. ")
COMPUTER SCIENCE WITH
PYTHON. V
24
can rewrite the previous program as follows:
Using nested if statements, we
in range 0 999 and then prints if the integer entered
program that inputs an integer
-

Write
1.4 a

number. Use Nested if statements.


is a 1/23
digit
irogram
num int(input("Enter a number (0. .999) "))
i fnum< o r num > 999:
print("Invalid entry. Valid range is 0 to 999. ")
else
if num < 10:
print( "Single digit number is entered")
else
if num < 100:
print("Two digit number is entered")
else:
print("Three digit number is entered")

The sample run of this program is just the same as previous program.

1.11 LOOPING STATEMENTS


and
Python provides wo kinds of loops : for loop and while loop to represent counting loop
conditional loop respectively.

1.11.1 The for LoopP


The for loop of Python is designed to process the items of any sequence, such as a list or a string,
one by one.

The General Form of for loop


The general form of for loop is as given below :

for <variable> in <sequences:


statements_to_repeat
For example, consider the following loop

for element in [10, 15, 20, 25]


print(element + 2, end = ' ')

The above loop would give output as :


12 17 22 27

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.

You might also like