0 ratings0% found this document useful (0 votes) 22 views23 pagesPython Revision Tour - I
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
Unit: Computational Thinking and Programming 2 Vs fo webat:empsthondcbn om
Chapter-1 Revision Tour
Cel Le
1 Python Character Set
2 Tokens
Ke ds
3 | Keywords
Identific
’ entifiers
5 Literals / Values
6 Delimiters
Operators
7 pe
Data Ty
Data Types
Variables
9
10 print () function
1 put () function
2 if-else statement
13 Ladder if - else statement (if - elif - else )
Nested if-else statements
14
15 while loop
16 for loop
v7 range () function
break statement
18
19 continue statement.
pass statement
20
age of 23Unit I: Computation
pontine oon 1 Revision Tour
character can represents any ee digit, or any other sign. Following are some of
[[ Unie: Computationel Thinking end Progremming-2 ——=~=~=~S*S*S*« Rests learnpythondcbse.com |]
the python character set.
LETTERS. AtoZandatoz
DIGITS 0-9
SPECIAL SYMBOLS | Space, +-* *\ [] {
& #, under score(_) etc.
WHITE SPACE Blank space, horizontal tab ( - > ), carriage return ,
Newline, Form feed.
OTHER Python can process all ASCII and Unicode characters as
CHARACTERS part of data or literals.
The smallest individual unit in a program is known as token or lexical unit.
Identifier
Keywords or Literals ||}] Delimiters | | Operators
Varuables
Keywords are special identifiers with predefined meanings that cannot change. As
these words have specific meaning for interpreter, they cannot be used for any
other purpose.
Page 20f 23Uri sampythondcbae.com
Chapter-1 Revision Tour
Some Commonly Used Keywords:
‘omputational Thinking and Programming -2 Visit to webs
and exec | not |continue| if | return) except| else
as_| finally | or | def | import | try | class | lambda
assert | for | Pass | del in| while | global | yield
break | from | print | _ elif is | with | raise
Identifiers are names given to identify something. Identifiers are fundamental
building blocks of a program and are used as general terminology for the names
given to different part of the program that is variables, objects, classes, functions,
lists, dictionaries etc. [(UN eum ee et ake ce
There are some rules you have to follow for naming identifiers:
*
An identifier starts with a letter A to Z or a to z or an underscore (_) followed
by zero or more letters, underscores and digits (0 to 9).
* Python does not allow special characters
+
Identifier must not be a keyword of Python.
* python is a case sensitive programming language.
Thus, Sname and sname are two different identifiers in Python.
Some valid identifiers: Mybook, file123, z2td, date_2, no
Some invalid identifier: 2rno,break,my.book,data-cs
Page 3 of 23[[ Unie: Computationel Thinking end Progremming-2 ——=~=~=~S*S*S*« Rests learnpythondcbse.com |]
eae 1 Revision Tour
Literals in Python can be defined as number, text, or other data that represent
values to be stored in variables. The data items which never change their value
throughout the program run. There are several kinds of literals:
nr ert emo
Numeric Literals : The numeric literals in Python can belong to any of the following
different numerical types:
int Used to integer value [Age = 20
float Used for real value Perc = 98.5
‘complex Used to part of complex number |x=1+0i
bool : It is logical literal | Used to logical /Boolean Result = True
Text Literals: is a sequence of letters surrounded by either by single or double or triple
quotes.
String Literal Used to Unicode/Text/String [Name = ‘Johni’, fname="
bytes |ASCII test/string learnpython4cbse.com’
None Type : It is special No - value None(and no other object)
Used to implement the grammatical and structure of Syntax.
lohny"|
Following are the python punctuators.
poe fe eeu
Grouping
. : 3 @ " /# Punctuation
A= xe oe Bit-wise assignment
Operators are special symbols that perform specific operations on one, two, or
three operands, and then return a result.
Page 4 of 23Unit I: Computational Thinking and Programming -2 ‘Visit to website: learnpythondcbse.com
Chapter-1 Revision Tour -I
iors
Description | Operator Example 1 Example 2
If x=10, then +x _
unary plus a | eer If x=-10, then 4x means -10
unary minus Be | sto then Ifx=-10, then +x means 10
means -10
Pek) icles
Addition + | >on10#5 => 15 | >>>'Hello'+’Amjad’ => HelloAmjad
Subtraction = |>>2105 => 5 | >>530-70 -40
Multiplication || * | >>>10*5 => 50_| >>>’Hello’*3 => HelleoHelloHello
>5>17/5.0 => 3.4 | >>28/3 93
Division /
peri7.0/S => 3.4 | >>28/7.0 4.0
Remainder/ | a | > s16%s 1 | >>>13%5 3
Modulo
Exponent ws [ooo2t*3 => 8 | >o026"10.5 => 4
>>>7.0//2 3 | >>es//2 > 2
Floor division
(integer division)
Bitwise Operator
‘We assume the operation! is X and Operation? is Y for better understanding of these
operators
. The AND operator compare two bits and generate a
BitwiseAND | & —|X&Y | result of 1 if both bits are 1; otherwise, it return 0.
Bitwise The EXCLUSIVE ~ OR operator compare two bits and
exclusiveoR | © | xav__| returns 1 if either of the bits are 1 and gives 0 if both
(xOR) bits are 0 and 1.
The OR operator compare two bits and generate a
Bitwise OR 1 |X1y¥ | result of if both bits are complementary; otherwise,
it return 0.
Bitwise ~ Ix The COMPLEMENT operator is used to invert all of the
Complement bits of the operands.
Page Sof 23Unit
‘Computational Thinking and Programming -2
Visit to website
Chapter-1 Revision Tour -I
Is the identity
Identity operator
Return True if both its operands are pointing to
not same?
a is |xixy same object (i.e, both referring to same
. memory location), returns false otherwise
, Return True if both its operands are pointing to
Is the identity
Y | isnot | Xisnoty different object (i.e, both referring to different
memory location), returns false otherwise
Relational Operator
ty eed
We assume the value of variable p as 10 for better understanding of these operators
>>>5<7 TRUE | >>>'Hello’ < ‘Amjad’ FALSE
>o7e5 FALSE | >>>'Amiad’ < ‘Hello’ TRUE
Less than < | >>>5<7<10 => TRUE
>>> S<7 and 7<10
=>_TRUE
Greatertnan | < [>>2> TRUE | >>>’Hello’ > ‘Amjad TRUE
>2>10<10 FALSE__| >>>’Amiad’ > ‘Hello’ FALSE
Less than or TRUE <<< ‘Hello’ <="Amjad’ FALSE
equal to FALSE _| >>>’Amjad’<="Hello’ TRUE
Greater than FALSE | <<< ‘Hello’ TRUE
or equal to TRUE __| >>>’Amjad’>='Hello’ FLASE
a TRUE | >>>'Hello’ TRUE
FALSE __| >>>'Hello’ FALSE
>e>l0l=11 => TRUE => TRUE
Not equal to
>>>10!=10 => FALSE _ | >>>'HI'I'HI => FALSE
Operators: and Shorthand Assignment
Assignment = | ltisusetoassignthe | Awill become 6
value to the variable
Divided and assign
Assign
I back the result to left | >>>p/=2 | pwill become S
quotient
operand
‘Added and assign
Assign sum. + back the result to left | >>>p+=2 | p.will become 12
‘operand
Page 6 of 23
sampythondcbae.cominking and|
Chapter-1 Revision Tour -
gramming -2
Visit to website:
iesrnpythonécbse.com
multiplied and assign
essen) +2 | back the result to left | >>> p*=2 | pwill become 20
product
operand
Taken modulus using
Assign two operands and _ ,
remainder assign the result to ea | Seo
left operand
Assan subtracted and assign
et back the result to left | >>>p-=2 | pwill become
difference
operand
Performed
exponential(power)
Assign ee, |caleulationon | oo . will become 100
Exponent operators and assign
value to the left
operand
Assign floor | Performed floor _
division dame |(ctescontentreeeror=l | aaa | Ea
Logical Operators
If both the operand is true, then the
Logical AND And XandY
es condition becomes True
eaceie ory if any one of the operand is true, then the
condition becomes True
Logical NoT | Not hot x Reverses the state of the operand/
Membership Operators
condition.
>>>3in [1,2,3,4]
Whether The in operator tests if a given value is
variablein | In contained in a sequence or not and
TRUE
sequence return True or False Accordingly
>>>6 not in [1,2,3,4,5]
Whether The not in operator testsifagiven _| True (Because the value
variable not in | notin | value is contained in a sequence or not | 6s not in the
sequence and return True or False Accordingly | sequence.)
>>>4 not in (1,2,3,4,5,6]
FALSE
ge 70f 23leernpythondcbee.com
Unit I: Computational Thinking and Programming -2 Visit to website:
Chapter-1 Revision Tour -I
It is a set of values, and the allowable operations on those values. It can be one of
the following:
[ number [ none [Fncne [ sets [ Mapeing
=—— \— 1
[ imeger [ Floating = [ suring [ Tuple [ ust [pecner
Deer) cry
Integers are whole -P to +251—1 that is- | 7°? 2=10
numbers such as 5,30, | 2147483648 to a ; a
1981,0 etc. They have no | 2147483647 - 1 fexample of
tnt fractional parts. Integers _ | for long integer An pecan eaey
can be positive or unlimited range, an
i subject to available
negative wn >>> c= 4298114
(virtual) memory only
Afloating point number | Anunlimited range, | y= 12.36
will consist of sign (+,-) | subject to available | >>>print(y)
Hoat | sequence of decimals (virtual) memory on | output : 12.36
digits and adot such as | underlying machine | >>>type(y)
0.0, -21.9, 0.98333328, _| architecture.
Complex number in Same as floating point
>>> x= 140)
python is made up of two | numbers because the | 77°"
Complex | fioating point values, one | real and imaginary Gis
(«.real,x.imag)
each for real and parts represented as.
A output: 1.00.0
imaginary part. floats,
itis a unique data type,
consisting of two
constants, True & False. | Two values True (1) | 227 {a#= True
oa We aeeera teenie tell sey a) e vee)
Non-Zero, Non-Null and ao
Non-empty.
ge 8 of 23Unit sampythondcbae.com
Chapter-1 Revision Tour
‘Computational Thinking and Programming -2 Visit to website:
& | none — | Thisis special data type with single value. Its used to signify the absence
2 of value/false in a situation. It is represented by None.
Peteny er
String They can have any character or sign,
including space in them. These are | Example:
immutable data types ‘Boy’, 'Navin’, “ZIG 1981”
List A list is a mutable (can change) sequenc | Lst= [1,2,3,4,"xy2",2.34,[10,.1]]
e data type and it may contained mixed | >>> Lst{0]
data types elements 1
>>> Lst[4]
Se
>>> Lst[6]
{10, 11]
>>> Lst[6][0]
10
Tuple | A tuple in Python is much like alist exce | t = (1,2,3,4,'abc',2.34,(10,11))
pt >>> t(0]
that itis immutable (unchangeable) onc | 1
e created. Tuples are enclosed in () >>> tld]
‘abe!
>>> t(6]
(10,11)
This data type is unordered and mutable. Dictionaries fall under
2 Mappings.
2 Diction- Can store any number of python >35d={1!a"2°b)3°C}
s aries _| objects. What they store is a key value | # here, 1,2 & 3 are the keys
= pairs, which are accessed using key. | >>> print(d)
Dictionary is enclosed in curly brackets. | {1:'a', 2:'b', 3:'c'}
Page 9 of 23Visit to webs
sampythondcbae.com
Chapter-1 Revision Tour
Named labels, whose values can be manipulated during program run, are called
Variables.
Creating a Variable: Python variables are created by assigning value of desired type
to them
Example:
X=10.8 # variable created of numeric (floating point) type
Y=90 # variable created of numeric (integer) type
Name = “My Name” | # variable created of string type
Multiple Assignments:
1. Assigning same value to multiple variables:
=z=100
It will assign value 100 to all three variables x, y and z.
2. Assigning multiple value to multiple variables
p, q,r = 10, 20, 30
It will assign the value order wise that is value 10 assign to variable p, value 20
assign to variable q and value 30 assign to variable r.
The print() function is a buil
x=
in function. It prints/outputs a specified message to
the screen/consol window.
The print() function statement has the following rules:
The print() function allows you to print out the value of a variable and strings
in parenthesis.
Page 10 0f 23,Uri
‘omputational Thinking and Programming -2 ‘Visit to website: learnpythondcbse.com
Chapter-1 Revision Tour
© The print() function will print as strings everything in a comma-separated
sequence of expressions, and it will separate the results with single blanks by
default.
The print() function prints strings in between quotes (either single or double).
If a print statement has quotes around text, the computer will print it out just
as it is written.
© To print multiple items, separate them with commas. The print() function
inserts a blank between objects.
© The print() function automatically appends a newline to output. To print
without a newline, use end separator after the last object.
© The sep separator is used between the values. It defaults into a space
character. For example:
>>> print (10,20,30,40, sep=’*’) # prints a separator *
10*20*30*40
© This ‘end’ is also optional and it allows us to specify any string to be appended
after the last value. For example:
>>> print (10,20,30,40, sep=""’, end=’@’) # Anew endis assigned @
10*20*30*40@
In the above example @ printed at the end of line.
The input() function is able to read data entered by the user and to return the same
data to the running program.
Page 11 0f 23Uri sampythondcbae.com
Chapter-1 Revision Tour
* The input() function is invoked with one argument - it's a string containing a
‘omputational Thinking and Programming -2 Visit to webs
message.
+ The message will be displayed on the console before the user is given an
opportunity to enter anything.
* The result of the input() function is a string.
Examples of input ( ) functions:
)
rollno = input(“Enter your roll no. %)
sname = input(‘Enter your name: ‘)
print (‘My roll no. is:’, rollno)
print (‘My name is:’, sname)
2) “Addition of two number from input () function.
Numl =int (input(“Enter the first number: “))
Num2 =int (input (“Enter the second number: “)))
print (‘The sum of ‘, Numl, * and *, Num2, * i
Numl+Num2, °.7, sep="")
When we execute the above program, it will produce the following output:
Enter the first number: 20
Enter the second numbe
The sum of 20 and 40 is 60
Comments are any text to the right of the # symbol and are mainly useful as notes
for the reader of the program.
For example:
print('Hello World) # Note that print is a function
OR
# Note that print is a function
print (‘Hello World’)
page 12023Unit
‘Computational Thinking and Programming -2 ‘Visit to website: learnpythondcbse.com
Chapter-1 Revision Tour -I
A group of statements which are part of another statement or a function are called
block or code — block or suite in Python
Consider the following Example:
if nicn2:
Tmp =n1
nl=n2
n2=Tmp
print ( “I Understand Block”)
Whitespace is important in Python. Actually, whitespace at the beginning of the
line is important. This is called indentation.
Selection if — else structures choose among alternative courses of action
If student's grade is greater than or equal to 60 Print “Passed “otherwise print “Not Qualified”
Syntax: The if-else execution goes as follows:
if true_or_false_condition: © ifthe condition evaluates to True (its
value is not equal to zero),
the perform if o:
perform if condition_true
tio
else: tatement is executed, and the conditional
statement comes to an end;
perOrmeLe COM ODE alls © ifthe condition evaluates to False (it is
equal to zero),
the per. £ n_false
statement is executed, and the conditional
statement comes to an end.
Page 13 0f 23,Uri
‘omputational Thinking and Programming -2 Visit to webs
sampythondcbae.com
Chapter-1 Revision Tour
Example:
‘reated By Amjad Khan
Program to print whether student
Qualified (percentage>=40)or Not Qualified'''
percentage = float (input ("Enter percentage: "))
if (percentage>=40) :
print ("Qualified")
else:
print ("Not Qualified")
> In the above example, percentage >= 49 is the test
expression.
» Inthe above example, when percentage is greater or
equal to 40, the test expression is true and the body
of if is executed and the boay of else is skipped.
> If percentage is less than to 40, the test expression is
false and the body of else is executed and the body
of if is skipped.
OUTPUT:
/if-else.py ======
Enter percentag:
Not Qualified
39
>>>
/if-else.py
Enter percentage: 45
Qualified
Page 14 0f 23Unit I: Computational Thinking and Programming -2
Chapter-1 Revision Tour -I
Ladder if-else statement (if-elif-else)
If-elif-else is used to check more than just one condition, and to stop when the first
statement which is true is found.
if true_or_false_condition:
perform if condition_true
elif:
perform_elif_condition_true
else:
perform_if_condition_fails
if number >= 0:
if number
else:
else:
check if the number is positive or
negative or zero and display
an appropriate message
by using ladder if statement'''
number = float (input ("
print ("Zero")
print ("+ive number")
print ("-ive number")
‘Visit to website: learnpythondcbse,com
* you mustn't use else without a preceding ifs
© else is always the last branch of the cascade,
regardless of whether you've used elif or not;
'* else is an optional part of the cascade, and
may be omitted;
© iftthere is an else branch in the cascade, only
one of all the branches is executed;
© if there is no else branch, it's possible that
none of the available branches is executed
inter a number: "))
Enter a numbe;
+ive number
>>>
Enter a number:
-ive number
Ladder_if-else.py
28
-1000
Page 1525Uri
‘omputational Thinking and Programming -2 ‘Visit to website: learnpythondcbse.com
Chapter-1 Revision Tour
There may be a situation when you want to check for another condition after a
condition resolves to true. in such a situation, you can use the nested if construct.
In nested if-else instruction placed after if is another if.
For Example:
[check if the number is positive or
Inegative or zero and display
lan appropriate message
loy using nested if statement'''
Inumber = float (input ("Enter a number: "))
if number >= 0:
if number :
print ("Zero")
else:
print ("tive number")
lelse:
print ("
ve number")
Here is important point:
* this use of the if statement is known as nesting; remember that
every else refers to the if which lies at the same indentation level
= RESTART: D:/Amjad_CS
/nested_if-else.py
Enter a number: 10
+ive number
>>>
/nested_if-else.py
Enter a number: 0.0
Zero
>>>
/nested_if-else.py
Enter a number: -20
-ive numberUnit I: Computation
inking and Programming -2 ‘Visit to website: learnpythondcbse.com
Chapter-1 Revision Tour -I
Performing a certain part of the code more than once is called a loop.
Two types of loops:
1) while loop
2) for loop
* The while loop continues to run as
long as the condition is still True. In
other words, it runs while the
condition is True.
; i es |
* Once the condition becomes False
and if the else clause is written in
while, and then else will get reise.
executed.
+ ifyou want to execute more than one statement
inside one while, you must indent all the
while conditional_expression: instructions in the same way;
Seer ane «an instruction or set of instructions executed inside
- the while loop is called the loop's body;
instruction_two «ifthe condition is False (equal to zero) as early as
when itis tested for the first time, the body is not
instruction_three executed even once
: * the body should be able to change the condition’s
value, because if the condition is True at the
instruction_n beginning, the body might run continuously to
Infinity - notice that doing a thing usually
else: decreases the number of things to do).
+ The else part is executed if the condition in the
Instructions of else block
while loop evaluates to False.
17 of 23Unit I: Computational Thinking and Programming -2 ‘Visit to website: learnpythondcbse.com
Chapter-1 Revision Tour -I
Example 2: The following program fragment prints the squares of all integers from 1
to 10.
lamjad_CS/whileLoo
The following program fragment P-PY
prints the squares of all 1
integers from 1 to 10 4
9
16
i-l 25
while i <= 10: is
print(i ** 2) 64
it=1 81
100
In this example, the variable / inside the loop iterates from 1 to 10. Note that after
executing this fragment the value of the variable is defined and is equal to 11,
because when i == 11 the condition i <= 10 is False for the first time.
Example 2:
Ithe following program prints
the squares of all integers
‘from 1 to 10 with else
[RESTART: D:/Amjad_
cS/whileLoopwithE1
i=l
lwhile i <= 10:
print (i)
it.
lelses
print ("Loop ended, i =", 4)
In the above when i == 11 the condition i <= 10 is False
for the first time then the else part is executed and print the last value of i.e. 11
Page 18 0f 23,Unit I: Computational Thinking and Programming -2 ‘Visit to website: learnpythondcbse.com
Chapter-1 Revision Tour
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other
iterable objects.
Its Syntax is:
for in :
Statement Block 1
else: # optional block
Statement Block 2
* The for loop ends when the loop is repeated for the last value of sequence.
* The for loop repeats n number of times, where nis the length of sequence given
in for loop’s header.
Example 1: Print all numbers from 0 to 4
|The following program prints RESTART: D:/Amjad_( cs/|
the all integers forLooy
from 1 to 4 erPy
inside for loop,
for i in range(1,5): inside for loop,
print ("inside for loop, i =', i)| |inside for loop,
inside for loop,
es eb
"
Pw
Example 2: Print all numbers from 0 to 5, and print a message when the loop has
ended:
the following program prints
the all integers
from 1 to 5 with else
[TART: D:/Amjad_CS/forl|
loopwithelse.py ==
ie inside for loop, i = 1|
inside for loop, i = 2|
for i in range (1,6): inside for loop, i = 3
print ("inside for loop, i =", i) inside for loop, i = 4
jelse: inside for loop, i = 5
fe)
print ('Lopp ended i Kopp ended i = 5
Page 19 0f 23,it to website
jpythondcbse.com
gram
Chapter
Python has a built-in function called range() that can generate a
For example:
ex = list(range(0, 10))
print (ex)
Output: [0, 1, 2,3, 4, 5, 6, 7,8, 9]
Syntax of range () Function:
ange (start, stop, step)
|
The number we How much we
want to start want to count by
counting at
The number we
The name of the want to count UP TO
function (but will not include)
+ start is an optional parameter specifying the starting number of the sequence
(0 by default)
+ stop is an optional parameter specifying the end of the sequence generated
(it is not included),
+ and step is an optional parameter specifying the difference between the
numbers in the sequence (1 by default.)
Page 20 0f 23,Unit I: Computational Thinking and Programming -2 ‘Visit to website: learnpythondcbse.com
Chapter-1 Revision Tour
We can use the range() function to control a loop through “counting”
for i in range(0, 20):
print (i + 1)
What will this code do?
— Print the numbers 1 through 20 on separate lines
When we use the range() function in for loops, we don’t need to cast it to a list,
The for loop handles that for us
print ("Table of five...")
f i 5, 51, 5 .
or num in range ( Call the range() function, but don’t
print(num, end=",”) need to cast it to a list
output:
Table of five...
5,10,15,20,25,30,35,40,45,50,
Jump statements are used to transfer the program's control from one location to
another. Means these are used to alter the flow of a loop like-to skip a part of a loop
or terminate a loop
There are three types of jump statements used in python.
1. break
2. continue
3. pass
Page 21 0f23,gramming -2
Chapter-1 Revision Tour -I
The break statement is used to exits the
loop immediately, and unconditionally
ends the loop's operation.
Visit to website:
leernpythondcbee.com
The continue statement is used to skip
the current block and move ahead to
the next iteration, without executing
the statements inside the loop.
for wvar in sequence:
# codes inside loop
if test_expr:
break
# code inside loop
# codes outside for loop
while test_expr:
# codes inside loop
Af test_expr:
break
# code inside loop
L__, 4 codes outside for loop
for u_var in sequence:
(———> # codes inside loop
Af test_expr:
continue
# code inside loop
# codes outside for loop
[—— # codes inside loop
Af test_expr:
continue
# code inside loop
# codes outside for loop
Example:
Example:
¥ Use of break
for letter in 'python':
fF Use of continue
for letter in ‘python":
Af letter=="0':
continue
print (letter}
(LB Pron 365 sha Eh
Fle Est Shell Debug Options
Window Help
poaS
220f23Unit I: Computational Thinking and Programming -2 ‘Visit to website: learnpythondcbse.com
Chapter-1 Revision Tour
In this program, we iterate through This program is same as the break
Ithe "python" sequence. We check if the |example except the break statement has
letter is ‘o’, upon which we break from __[been replaced with continue.
|the loop. Hence, we see in our output
Ithat all the letters up till ‘o” gets printed.
lAfter that, the loop terminates.
‘We continue with the loop, if the string
is ‘o’, not executing the rest of the block.
Hence, we see in our output that all the
letters except ‘0’ gets printed.
* pass in Python basically does nothing, but unlike a comment it is not ignored
by interpreter.
* Itcan be used when a statement is required syntactically but the program
requires no action.
Can be use in loop and conditional statements:
if (something == true):
pass
while (some condition is true):
pass
Page 23 0f 23,