You are on page 1of 60

CH.

1: PYTHON REVISION TOUR - I


What is character set?
Ans.: Character set is a set of valid characters that a language can recognize. A character
represents any letter, digit or any other symbol.
Python has following character set:
Letters: A – Z and a – z
Digits: 0–9
Special Symbols: Space + - * / = # $ % ; : ‘ “ * + , - ( ) < > ? \ / ! & etc.

What are tokens?


Ans.: The smallest individual unit in a program is known as a token.
Python has following tokens.
1. Keywords
2. Identifiers
3. Literals
4. Operators
5. Punctuators
#Program to enter two numbers and print their Sum/Difference.
N = int(input("Enter a Number: "))
if N>10:
Square = N*N
print(“Square of Entered Number is: ",Square)
else:
Cube = N*N*N
print(“Cube of Entered Number is: ",Cube)

1. Keywords: if & else


2. Identifiers: N, Square and Cube
3. Literals: Strings enclosed in double quotes and digit 10
4. Operators: =, >, *
5. Punctuators: ( ) , :
What are keywords?
Ans.: The keywords are the words that convey a special meaning to the language translator in a
program. Keywords are case sensitive. Python has 33 keywords.
e.g. False, True, None, break, continue, class, def, del, if, else, for, while, etc…………..

Keywords in Python programming language


False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield
What are identifiers?
Ans.: Identifiers are the fundamental building blocks of a program. They refer to the names of
variables, objects, functions, lists, classes, dictionaries etc.
e.g. N1 =10, N2=20;
Sum = N1 + N2
print (“The Sum of N1 and N2 is :” , Sum)

N1, N2 & Sum are identifiers.


Rules to create an Identifiers:
1. The first character must be letter or underscore ( _ ).
2. An identifiers can be single character or a string.
3. It can be upper case or lower case letter.
4. Identifiers are case sensitive i.e. Sum is not equal to sum / SUM / sUM / SuM / sUM.
5. The digits can be part of the identifiers.
6. An identifiers can not contain any special character in it.
7. An identifier must not be a keyword of Python.
8. An identifies must not contain any space in between.
Identify the following valid Identifiers.
Num1 = 10
Num2 = 20
Sum = Num1 + Num2
Age = 25
% = 65
Class = XI
class = XIA
Total Marks = 525
What are literals?
Ans.: Literals are constant data that never change their value during program run. Python has
following literals.
(i) String - literal
(ii) Numeric Literals
(iii) Boolean Literals
(iv) Special Literals None
(v) Literal Collections e.g. Lists and Tuples.
What are string literals?
Ans.: A group of characters enclosed in single or double quote is called string in Python. Python
allows two types of string literals.
i. Single-Line String: String must be terminated in one line. E.g.
Name = ‘Krishna’
Address = “Seawoods Darawe, Navi Mumbai”
ii. Multiline String: The string which exceed one line can be written in multiline string. Multiline
strings can be created in two ways:
(a). By adding a backslash at the end of normal single/double quote strings.
Address = “Seawoods Darawe \
Navi Mumbai”

(b). By typing the string in triple quotation marks. No backslash needed at the end of line.
Address = ‘’’Seawood
Darawe
Navi
Mumbai’’’
What are numeric literals?
Ans.: A numeric literals represents any number. Python has three numeric literals.
I. int e.g. 7, 58, 231, -25, +54 etc.
II. float e.g. 25.23, -50.25, 145.0015, etc.
III. complex e.g. a + bj, where a and b are floats and j represents √-1, which is an imaginary
number. The a is the real part of the number, and b is the imaginary part.

What are Boolean literals?


Ans.: A Boolean literal in Python is use to represent one of the two Boolean values i.e. True or
False.
Special Literal None
Ans.: The None literal is used to indicate absence of value. It is also used to indicate the end of
lists in Python.

What are operators?


Ans.: Operators are used to perform arithmetic, logical and conditional operations.
Python has following operators.
 Unary operators: These operators require only one operand to operate upon.
+ Unary plus - Unary minus ~ Bitwise complement not Logical negation

 Binary operators: These operators require two operand to operate upon.


+ Addition - Subtraction * Multiplication / Division % Remainder/Modulus
** Exponent (Raise to power) // Floor Division

 Bitwise Operators:
& Bitwise AND ^ Bitwise exclusive OR (XOR) | Bitwise OR
 Logical Operators:
and Logical AND or Logical OR
 Assignment Operators:
= Assignment
/= Assign Quotient
*= Assign Product
+= Assign Sum
-= Assign Difference
%= Assign Remainder
**= Assign Exponent
//= Assign Floor Division
 Relational Operators:
< Less than > Greater than
<= Less than or equal to >= Greater than or equal to
== Equal to != Not equal to

 Shift Operators:
<< Shift Left >> Shift Right
 Identity Operators:
is is the identity same? is not is the identity not same?

 Membership Operators:
in whether variable in sequence not in whether variable not in sequence

Operand: Variables and constants together are called operand. It is the operand on which the
operators work upon.

What are punctuators?


Ans.: Punctuators are also known as separators. They are used to separate the statements.
e.g. ( ) { } [ ] , ; : * = # ‘ “
Program 1:

#This is First Python Program.


print ( "Welcome to Python Programming." )
print ( "My Name is Krishna." )
print ( "I Study in Don Bosco School." )
print ( "I am in Class XIA." )
print ( "Thank You." )
Program 2:

Comments #This is Second Python Program.


#Program to enter two numbers and print their Sum/Difference.
N1 = int(input("Enter First Number: "))
N2 = int(input("Enter Second Number: ")) Statements
if N1>N2:
Instructions Diff=N1-N2
print("The Two Number Are: ",N1," and ",N2) Statements
print("Difference is: ",Diff)
else :
Block Sum=N1+N2
print("The Two Number Are: ",N1," and ",N2)
Statements
print("Sum is: ",Sum)
Program 3:
#Program to enter two numbers and perform arithmetic operations.
num1 = int(input('Enter First number: '))
num2 = int(input('Enter Second number '))
add = num1 + num2
dif = num1 - num2
mul = num1 * num2
div = num1 / num2
floor_div = num1 // num2
power = num1 ** num2
modulus = num1 % num2
print('Sum of ',num1 ,'and' ,num2 ,'is :',add)
print('Difference of ',num1 ,'and' ,num2 ,'is :',dif)
print('Product of' ,num1 ,'and' ,num2 ,'is :',mul)
print('Quotient of ',num1 ,'and' ,num2 ,'is :',div)
print('Floor Division of ',num1 ,'and' ,num2 ,'is :',floor_div)
print('Exponent of ',num1 ,'and' ,num2 ,'is :',power)
print('Remainder of ',num1 ,'and' ,num2 ,'is :',modulus)
Program 4:
#Program to enter radius of circle and then find its area & perimeter
radius = float(input('Enter The Radius of Circle: '))
area = 3.141 * radius * radius
perimeter = 2 * 3.141 * radius
print('The area of circle of radius',radius,'is = ',area)
print('The perimeter of circle of radius',radius,'is = ',perimeter)
Program 5:

#Program to enter length and breadth of rectangle and theb find its area & perimeter
length = float(input('Enter The Length of Rectangle: '))
breadth = float(input('Enter The Breadth of Rectangle: '))
area = length * breadth
perimeter = 2 * (length + breadth)
print('The area of reactangle of length',length,'and breadth',breadth,'is = ',area)
print('The area of rectangle of length',length,'and breadth',breadth,'is = ',perimeter)
Program 6:

#Program to enter marks of 5 subjects and then calculate total & percent.
phy = float(input('Enter marks of Physics: '))
chem = float(input('Enter marks of Chemistry: '))
maths = float(input('Enter marks of Maths '))
eng = float(input('Enter marks of English: '))
comp = float(input('Enter marks of Computer: '))
total = phy + chem + maths + eng + comp
percent = (total * 100) / 500
print('Total marks scored is = ',total)
print('Percentage scored is = ',percent)
What are comments?
Ans.:
 Comments are used to give additional information about something in the program like
variables, objects, functions, blocks, expressions, statements, etc.
 It helps users and programmers to understand the program better.
 Comments are non executable i.e. interpreter ignores it while executing the program.
There are two types of comments:
Full line comments: It starts with # symbol followed by comments and gets over in a line.
e.g. #Let us learn Python programming.
Multi-line comments: It starts and end with triple-apostrophe(‘ ‘ ‘) or triple quote (“ “ “) followed
by comments. This type of comment is also known as docstring.
e.g. “ ” ”Comments are used to give additional information about something in the program
like variables, objects, functions, blocks, expressions, statements, etc.” ” ”
What is statement?
Ans. An statement is a command or instruction given to the computer to perform some task. An
statement is executed and it is not necessary that a statement results in a value. e.g.
print(“This is Python Programming”)
What are expressions?
Ans. An expression is any legal combination of symbols that represents a value. It can be value
only or it can be complex expressions that produces a value. e.g.
25 # Simple Expression
3.78 # Simple Expression
a+b # Complex Expression
(a + 3) * 7 # Complex Expression
What are blocks in Python?
Ans. A group of statements which are part of another statement or a function are called block or
code-block or suite in Python.
if N1>N2:
Diff=N1-N2
print("The Two Number Are: ",N1," and ",N2)
print("Difference is: ",Diff)
else : Block
Sum=N1+N2
print("The Two Number Are: ",N1," and ",N2)
print("Sum is: ",Sum)
What is a variable in Python?
Ans. A variable in Python represents named locations that refers to a value and whose value can
be used and processed during program run. E.g. In Program 2, N1, N2, Diff and Sum are variables.
What is the use of type( ) function in Python?
Ans. This function is used to determine the type of an object( variables and literals).
>>> a = 9
>>> type(a)
<class 'int'>
>>> a = 'Python'
>>> type(a)
<class 'str'>
>>> a = 2.5
>>> type(a)
<class 'float'>
>>> b = 5
>>> c = a < b
>>> type(c)
<class ‘bool’>
What is the use of input( ) function in Python?
Ans. This is built in function used to get a value from the user and assign to a variable.
Syntax:
Variabel_Name = input(“Message to be displayed for user”)
e.g. Name = input(“Enter Your Name”)

Note: This function always returns a value of string type. So when you are entering any number
and want to perform some mathematical or logical operation then this number must be
converted into number format before performing the mathematical or logical operation
otherwise interpreter will generate an error.
N1 = input("Enter a Number: ")
Next = N1+1 # N1 is in string format
print("The next number is: ",Next)
This error can be resolved in two ways as follows:
(i) N1 = input("Enter a Number: ")
N1 = int(N1) # N1 is converted to integer format
Next = N1+1
print("The next number is: ",Next)

(ii) N1 = int(input("Enter a Number: ")) # N1 is converted to integer format


Next = N1+1
print("The next number is: ",Next)
What is the use of print( ) function in Python?
Ans. Print function is used to print the value of an objects or strings on the screen.
Syntax: print(objects, sep = “StringSeparator “ , end = “EndString“)
Where sep is string separator and end is end string.
The default value of string separator is a space(“ “) and the default value of end is new line.
e.g.
>>> print("My","Name", "Is","Krishna.")
My Name Is Krishna.
>>> print("My","Name", "Is","Krishna.", sep=".....")
My.....Name.....Is.....Krishna.
>>> print("My","Name", "Is","Krishna.",sep=".....",end="*")
My.....Name.....Is.....Krishna.*
print("My","Name", "Is","Krishna.",sep="...",end="*")
print("My","RollNumber","Is","15.",sep=".....",end="**")
print("I","Like","To","Play","Cricket.",sep=".....",end="***")
My...Name...Is...Krishna.*My.....RollNumber.....Is.....15,**I.....Like.....To.....Play.....Cricket***

print("My","Name", "Is","Krishna.",sep="...",end="*")
Print()
print("My","RollNumber","Is","15",sep=".....",end="**")
Print()
print("I","Like","To","Play","Cricket",sep=".....",end="***")
My...Name...Is...Krishna.*
My.....RollNumber.....Is.....15.**
I.....Like.....To.....Play.....Cricket.***
>>> 2 + 3 >>> print("Deepak's Mobile")
>>> 5 – 2 >>> print('Deepak\'s "Mobile“ ')
>>> 4 * 5 >>> print('“Deepak\'s Mobile“ ')
>>> 10 / 2 >>> 'Python' + ' Python' + ' Python‘
>>> 10 // 2 >>> 5 * 'Python ‘
>>> 15 / 2 >>> print("c:\Python\navin's programming")
>>> 15 // 2 >>> print("c:\Python\Navin's Programming")
>>> 15 % 2 >>> print(r"c:\Python\navin's programming")
>>> 15 % 3 >>> print(r"c:\Python\Navin's programming")
>>> 3 ** 5 >>> N1 = 5
>>> 2 + 5 – 3 >>> N2 = 10
>>> (8 + 3) * 2 >>> N1 + N2
>>> “Python” >>> _ * 2
>>> ‘Python’ >>> Program = 'MyProgram'
>>> print(‘Python’) >>> Program
>>> print(‘Deepak’s Mobile’) >>> Program + ' of Python'
>>> print(‘Deepak\’s Mobile’)
>>> Program[0]
-9 -8 -7 -6 -5 -4 -3 -2 -1
>>> Program[1]
>>> Program[2] M y P r o g r a m
>>> Program[8] 0 1 2 3 4 5 6 7 8
>>> Program[9]
>>> Program[-1] >>> a = 5
>>> Program[-2]
>>> b = 10
>>> Program[-9]
>>> a < b
>>> Program[-10]
>>> Program[0:2] True
>>> Program[0:5] >>> a > b
>>> Program[2:9] False
>>> Program[2:] >>> int(True)
>>> Program[:2] 1
>>> Program[:9] >>> int(False)
>>> Program[0:15] 0
Data Types

None Numbers Sequences Mappings

Integer Float Complex Boolean String List Tuple Set Range Dictionary

1. None: It is a special data type which does not store anything.


2. Numbers: The numbers in Python have following core data types:
i. Integers
 Integers (signed)
 Booleans
ii. Floating-Point Numbers
iii. Complex Numbers

Integers Signed: It is the normal integer representation of whole numbers. The numbers can
be positive as well as negative.
e.g. 25, 68, 548, +85, -57, etc.

Booleans: It represents the truth values True (1) and False (0).

Floating-Point Numbers: A number having fractional part is a floating-point number.


Floating-Point Numbers can be written in two forms:
i. Fractional Form: e.g. 25.58, -368.755, 0.00245, etc.
ii. Exponent Notation: e.g. 25.215E05, 0.958E-05, etc.
Complex Numbers: Python represents complex numbers in the form of A + Bj. Where A and B
are real numbers and j is imaginary number equal to the square root of -1 i.e. √-1. e.g.
>>> c1 = 7 + 3.5j >>> c2 = 2.5 + 0.5j
>>> c1 >>> c2
(7+3.5j) (2.5+0.5j)
>>> c1.real >>> c2.real
7.0 2.5
>>> c1.imag >>> c2.imag
3.5 0.5
3. String:
 A string in Python is a sequence of characters.
 String can hold any type of known characters.
 Strings are immutable this means that once defined, they cannot be changed.
 Strings in Python are stored as individual characters in contiguous memory location, with
two- way index for each location.
i. Forward Indexing: Index starts from zero (0).
ii. Backward Indexing: Index starts from minus one (-1).
Backward Indexing -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
STRING M Y P R O G R A M
Forward Indexing 0 1 2 3 4 5 6 7 8 9
Accessing String Elements: >>> STRING[0:] >>> STRING[-1:-10]
String[Index] 'MY PROGRAM' ‘ ‘
String[LowerIndex : UpperIndex] >>> STRING[3:6] >>> STRING[-1:]
'PRO' 'M'
>>> STRING[3:] >>> STRING[6:0]
STRING[0] = ‘M’ = STRING[-10]
'PROGRAM' ‘ ‘
STRING[2] = ‘ ’ = STRING[-8]
>>> STRING[:2] >>> STRING[-10:-1]
STRING[3] = ‘?’ = STRING[-7]
'MY' 'MY PROGRA'
STRING[9] = ‘M’ = STRING[-1]
>>> STRING[-10:0]
STRING[10], STRING[11], STRING[-11], STRING[-12] will give an error i.e. ‘ ‘
IndexError: string index out of range >>> STRING[-10:]
'MY PROGRAM’
STRING*2+ = ‘ : ‘ >>> STRING[-15:]
TypeError: 'str' object does not support item assignment 'MY PROGRAM'
When single index is passed which is out of index range then the interpreter generates an
Index Error but if range of index is passed which are out of index range then the interpreter
returns the elements till available index. E.g.

STRING[3:15]
'PROGRAM‘
STRING[10:20]
‘‘
STRING[-15:15]
'MY PROGRAM‘

NOTE: This applies to list also.


4. List:
 The list in Python is a compound data type because it can store any data type in it.
 The values of a list are enclosed in a square brackets.
 List is mutable i.e. it can be changed/modified.
 A list in Python also gets stored with two - way index for each location.
>>> list = [25, 'Python‘ ,35.5, 35 + 5j, 45] >>> list[-1:-3]
>>> list []
[25, 'Python', 35.5, (35+5j), 45] >>> list[-1:]
>>> list[0] >>> list[0]=50 #Value is changed [45]
25 >>> list >>> list[3:0]
>>> list[1] [50, 'Python', 35.5, (35+5j), 45] []
'Python' >>> list[1:3] >>> list[-5:-1]
>>> list[-1] ['Python', 35.5] [50, 'Python', 35.5, (35+5j)]
45 >>> list[1:] >>> list[-4:]
>>> list[-2] ['Python', 35.5, (35+5j), 45] ['Python', 35.5, (35+5j), 45]
(35+5j) >>> list[:10]
[50, 'Python', 35.5, (35+5j), 45]
5. Tuple:
 Tuple is same as list but immutable.
 The values of a tuple are enclosed in parenthesis.
>>> tuple = (25, ‘Python', 35.5, 35 + 5j, 45)
>>> tuple
(25, 'Python', 35.5, (35+5j), 45)
6. Dictionary:
 Dictionaries are mutable, unordered collections with elements in the form of a key : value
pairs.
 It is used to process huge amount of data in an efficient way.
 Each value is assigned to an unique key.
 Instead of using index number each value is accessed using key.
>>> D = {'DB01':'ADITI','DB02':'AAKASH','DB03':'KRISHNA'}
>>> D
{'DB01': 'ADITI', 'DB02': 'AAKASH', 'DB03': 'KRISHNA'}
>>> D['DB02']
'AAKASH'
>>> dict.get('DB01')
'ADITI'
>>> dict.keys()
dict_keys(['DB01', 'DB02', 'DB03'])
>>> dict.values()
dict_values(['ADITI', 'AAKASH', 'KRISHNA'])
Note:
 Python is an Object Oriented Programming Language.
 Every entity that stores any values or any type of data are called as an object.
 Each object has following attributes: >>> num = 5
 A type >>> type(5)
 A value <class 'int'> num 5
 An id >>> type(num) 25314
<class 'int'>
>>> id(5)
1675191536
>>> id(num)
1675191536
Identity Operators: The identity operators are used to check if both the operands
reference the same object memory. >>> Num1=5
>>> Num2=5
5 25 >>> Num3=25
Num3
>>> Num1 is Num2
25314 32510 True
Num1 Num2
>>> Num1 is Num3
25314 and 32510 are the memory addresses at which 5 and False
25 are stored respectively.

Note: There are certain cases where Python creates different objects even if the values
are same for these objects. These are:
 When any string is entered i.e. more than a character.
 When entered number is greater than integer 256.
 When any float or complex number is entered.
Bitwise Operators: Bitwise operators are similar to logical operators, except that these
operators work on binary representation of data.

~ This operator is used to invert all the bits of the operand.


(Bitwise Complement)
| The OR operator compares two bits and gives 1 if either or both bits
(Bitwise OR) are 1; and 0 if both bits are 0.
& The AND operator compares two bits and gives 1 if both bits are 1;
(Bitwise AND) and 0 if either or both bits are 0.
^ The XOR operator compares two bits and gives 1 if either of the bits
(Bitwise XOR) are 1 and it gives 0 if both bits are 0 or 1.

>>> ~12 ( 1 2 ) 10 = 0 0 0 0 1 1 0 0 ( 1 3 ) 10 = 0 0 0 0 1 1 0 1
-13 11110011 11110010 1’s Complement
+ 1 2’s Complement
1 1 1 1 0 0 1 1 -13
>>> 12 | 13 ( 1 2 ) 10 = 0 0 0 0 1 1 0 0 X Y X|Y
13 ( 1 3 ) 10 = 0 0 0 0 1 1 0 1 0 0 0

00001101 0 1 1
1 0 1
1 1 1

X Y X&Y
0 0 0
>>> 12 & 13 ( 1 2 ) 10 = 0 0 0 0 1 1 0 0 0 1 0
12 ( 1 3 ) 10 = 0 0 0 0 1 1 0 1 1 0 0
00001100 1 1 1

X Y X^Y
0 0 0
>>> 12 ^ 13 ( 1 2 ) 10 = 0 0 0 0 1 1 0 0 0 1 1
1 ( 1 3 ) 10 = 0 0 0 0 1 1 0 1
1 0 1
00000001 1 1 0
Logical Operators: These operators are used to combine two or more expressions
together.

or With this operator if the first expression is true then the remaining
(Logical or) expression are not checked. Result is True if any one expression is
true; False if all the expressions are false.
and With this operator if the first expression is false then the remaining
(Logical and) expression are not checked. Result is False if any one expression is
false; True if all the expressions are true.
not The logical operator negates or reverses the truth value of the
(Logical not) expression.
Operator Precedence
Operator Operator’s Name
Highest
() Parentheses
** Exponentiation
~x Bitwise not
+x, -x Unary Plus, Minus
2/6*5//5%10 *, /, //, % Arithmetic
2+3*5-2*5/3 +, - Arithmetic
2*3**2 & Bitwise AND
2**2**3 ^ Bitwise XOR
| Bitwise OR

<, <=, >, >=, <>, !=, ==, is, is not Relational Operators, Identity Operators

not x Boolean NOT


and Boolean AND
Lowest or Boolean OR
Operator Associativity: It is the order in which an expression having multiple operators of
same precedence is evaluated. Almost all the operators have left-to-right associativity
except (**), which has right-to-left associativity.

random Module: random module is used to generate random


numbers. To work with random number generators, the
random module can be imported in any Python program as
follows:
import random
There are three most common random number generator
functions in random module are:
random( ): It returns the random floating point number N in
the range[0.0, 1.0]. i.e. 0.0<= N <1.0.
randint(a,b): It returns a random integer N in the range (a, b), i.e. a<= N <=b (both range
limits are inclusive). Remember it always generates an integer.

Note: To generate a random floating-point numbers


between range lower to upper limit using random():
i. Multiply random() with difference of upper limit
with lower limit, i.e. (upper limit – lower limit).
ii. Add lower limit to it.
randrange(start, stop, step): It returns random numbers from range start to stop with
step value specified.

random.randrange(15): This will generate random numbers 0 to 15.


random.randrange(5, 15): This will generate random numbers 5 to 15.
random.randrange(5, 15, 2): This will generate random numbers [5, 7, 9, 11, 13, 15]
math Module: Math module is used to perform mathematical operations. To work with
mathematical functions, the math module can be imported in any Python program as
follows:
import math
Find the value of: √a2 + b2 + c2 Find the value of: 2 – y2y + 4y
statistics Module: This module provides many statistics functions such as mean(),
median(), mode() etc. The statistics module can be imported in any Python program as
follows:
import statistics
What is a statement?
Ans. Statements are the instruction given to the computer to perform some
task. Python has three types of statements:
1. Empty Statement
2. Simple Statement
3. Compound Statement
What is an empty statement?
Ans. A statement which does nothing is called empty statement. In Python
an empty statement is pass statement.
What is simple statement?
Ans. Any single executable statement is a simple statement in Python. E.g.
Name = (“Enter Your Name: “)
What is compound statement?
Ans. A compound statement represents a statement or a block of statements
executed as a unit. A compound statement has a following syntax:
<compound statement header> #Header Line
<indented compound statement> #Body

What is statement flow control in Python?


Ans. It is an order in which a computer performs the task to control the flow
of a program. A statement may be executed sequentially, selectively or
iteratively.
What is sequential statement flow of control in Python?
Ans. In this flow of control each statement is executed one after the other.
Statement 1 What is selection statement flow of control in
Python?
Statement 2 Ans. In this flow of control the statement is executed
depending upon a condition-test.
Statement 3
TRUE FALSE
Statement n Condition

Statement 1 Statement 2

Next Statement
What is iterative statement flow of control in Python?
Ans. The iterative statements allow a set of instructions to be executed
repeatedly until a certain condition is fulfilled. The iteration statements are
also called looping statements.

TRUE FALSE
Condition
Exit the Loop

Statement 1
Body of Loop
Statement 2
If statement : Flow Chart SYNTAX:

Start
if(test expression / condition):
statement/s
FALSE statement-x
TRUE
Condition

Statement/s

End
If - else statement : Flow Chart SYNTAX:

Start if(test expression):


statement-1
else:
FALSE TRUE statement-2
Condition
statement-x

Statement 2 Statement 1

End
The range() Function: The range() function of Python generates a list which is a
special sequence type.
Syntax:
range(LowerLimit, UpperLimit, StepValue)
 range(1, 10, 1) will generate a list as [1, 2, 3, 4, 5, 6, 7, 8, 9]
 range(1, 10, 2) will generate a list as [1, 3, 5, 7, 9]
 range(2, 10, 3) will generate a list as [2, 5, 8]
 range(5, 0, -1) will generate a list as [5, 4, 3, 2, 1]
Note: Lower limit and step value are optional.
 range(1, 5) will generate a list as [1, 2, 3, 4] where step value is not passed in
the range() function. By default the step value is 1.
 range(5) will generate a list as [0, 1, 2, 3, 4] where lower limit and step value are
not passed. By default the lower limit value is 0.
Iteration/Looping /Repetition Statements: The iteration or repetition statements
allow a set of instructions to be performed repeatedly until a certain condition is
fulfilled.
There are two types of looping statements in Python:
i.for Loop: The for loop of Python is designed to process the items of any
sequence, such as a list, tuple or string one by one. The for loop is also called as
counting loop because it repeats the statements for certain number of times.
Syntax:
for <variable> in <sequence>:
body of loop
or statements to be repeated
e.g.
for a in range(1, 11): # Each time loop variable a will be assigned
print(a) # a value from 1 to 10 and then printed
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
ii. while Loop: The while loop is a conditional loop that will repeat the instructions
within itself as long as a condition remains true.
Syntax:
initialization
while <condition>:
body of loop
or statements to be repeated
update expression

e.g.
a=1 # initialization
while a<=10 : # condition
print(a) # body
a += 1 # update expression
Attendance = " "
Day = 1
Present = 0
Absent = 0
Choice = "Y"
while Choice == "Y" or Choice == "y":
print("Enter attendance of day ",Day, ":",end =" " )
Attendance = input()
if Attendance =="P" or Attendance == "p":
Present +=1
Day+=1
else:
Absent +=1
Day+=1
Choice = input("Do you want to enter the attendance for next Day? Press Y/N")
if Day>6:
print("You have entered one week attendance")
break

print("Weekly Attendance is as follows:")


print("Total number of days present: ",Present)
print("Total number of days absent: ",Absent)
Jump Statements: There are two jump statements which are used within loops to
jump out of loop-iterations.
i. break Statement: break Statement in Python is used to terminate the loop. The use of
this statement terminates the execution of loop immediately, and then program
execution will jump to the next statements.
e.g.
for a in range(1,11):
if a==5:
print(“Break”)
break
else:
print(a)
ii. continue Statement: The continue statement skips all the remaining statements in
the current iteration of the loop and moves the control back to the top of the loop.
e.g.
password = "abc"
for count in range(5):
p = input("Enter Password: ")
if p!=password:
print("Credential does not match.")
continue
else:
print("You are logged in.")
break
else:
print("You have tried 5 times. Try after sometimes.")

You might also like