0% found this document useful (0 votes)
4 views120 pages

STD-12th - Chapter - 1 Python Revision Tour-1

This document serves as a revision guide for Python programming, covering essential topics such as tokens, variables, data types, and program structure. It introduces key concepts including keywords, identifiers, literals, operators, and the differences between dynamic and static typing. The content is structured into chapters and sections, providing a comprehensive overview suitable for 12th-grade students.

Uploaded by

solankikshitij70
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)
4 views120 pages

STD-12th - Chapter - 1 Python Revision Tour-1

This document serves as a revision guide for Python programming, covering essential topics such as tokens, variables, data types, and program structure. It introduces key concepts including keywords, identifiers, literals, operators, and the differences between dynamic and static typing. The content is structured into chapters and sections, providing a comprehensive overview suitable for 12th-grade students.

Uploaded by

solankikshitij70
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
You are on page 1/ 120

Chapter -1

Python Revision tour

STD-12th
INDEX
1.1 Introduction 1.8 Expressions
1.2 Tokens in Python 1.9 Statement Flow Control
1.3 Barebones of a Python 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

2
1.1 Introduction

 Python programming language, developed by Guido Van Rossum in early 1990s, has become
a very popular programming language among beginners as well as developers.
 Python can be used to :
 Build a website
 Develop Games
 Program Robots
 Perform Scientific Computations
 Develop Artificial Intelligence Applications
3
1.2 Tokens in Python
1.2 Tokens in Python
 The smallest individual unit in a program is known as a Token or a lexical unit.

 Python has following tokens :


 Keywords
 Literals / Values
 Identifiers (Names)
 Punctuators
 Operators

5
1.2.1 Tokens in Python - Keywords
 Keywords are predefined words with special meaning to the language compiler or
interpreter.

 These are reserved for special purpose and must not be used as normal identifier names.

 Python programming language contains the following keywords :

 False  def  global  pass


 None  del  if  raise
 True  elif  import  return
 and  else  is  try
 assert  except  lambda  while
 break  finally  nonlocal  with
 class  for  not  yield
 continue  from  or 6
1.2.2 Tokens in Python – Identifiers (Names)
 Identifiers are the names given to different parts of the program viz. variables,
objects, classes, 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 names must be made up of only letters, numbers, and underscore (_).
 Variable names cannot begin with a number, although they can contain numbers.

Valid identifiers : Invalid identifiers :


 Myfile DATA-REC contains special character - (hyphen)
29CLCT Starting with a digit
 MYFILE
break reserved keyword
 _CHK
My.file contains special character dot ( . )
 Z2Tez9
 FILE13
 _HJ13 JK 7
8
1.2.3 Tokens in Python – Literals (Values)
 Literals are data items that have a fixed/constant value.

 Python allows several kinds of literals, which are being given below.

String Literals
• Single line Strings
• Multiline Strings

Numeric Literals
• Integer Literals
• Floating/Real Point Literals
• Complex Number Literals

Boolean Literals

Special Literal None 9


1.2.3 Tokens in Python – Literals (Values) – String Literals
 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.


Multiline Strings
Single line strings Multiline strings are strings spread across multiple lines.
Single line strings must terminate With single and double quotes,
in one line i.e., the closing quotes each line other that the concluding line has an end
should be on the same line as that character as \ (backslash)
of the opening quotes. >>>Text1 = "Hello\
World"
>>>Text1 = "Hello World" but with triple quotes,
no backslash is needed at the end of intermediate lines.
>>>Text1 = ‘’’Hello
World ‘’’

10
1.2.3 Tokens in Python – Literals (Values) – String Literals
 In strings, we can include non-graphic characters through escape sequences.
Escape sequences are given in following table :
1.2.3 Tokens in Python – Literals (Values) – String Literals
 In strings, we can include non-graphic characters through escape sequences.
Escape sequences are given in following table :
1.2.3 Tokens in Python – Literals (Values) – Numeric Literals

 Numeric literals are numeric values and these can be one of the following types

13
1.2.3 Tokens in Python – Literals (Values) – Numeric Literals
 int (signed integers) are positive or negative whole numbers with no decimal point.
Examples are a=24, b=-50.
 Floating point literals or real literals floats represent real numbers with both integer and
fractional part. They can be positive or negative.
For example: a=-13.0, b=0.75, pi=3.14 etc. or in Exponent form e.g., 0.17E5, 3.e2, .6E4 etc.

14
1.2.3 Tokens in Python – Literals (Values) – Numeric Literals
 Complex number literals are of the form a + bJ,
where a and b are floats and (J or j) represents −1, which is an imaginary number).
a is the real part of the number, and b is the imaginary part.

a + bJ

Real Part Imaginary Part

15
1.2.3 Tokens in Python – Literals (Values) – Numeric Literals
 The integer literals can be written in :
 Decimal form / Decimal Integer Literal (base 10) : A decimal integer literal contains digits 0
to 9. The first digit cannot be 0. They can be positive numbers or negative numbers.
For example, 231, —76, +23, 2 are decimal integer literals.

 Octal form / Octal Integer Literal (base 8): An octal integer literal contains digits 0-7.
It is written by prefixing 00 before the number where, the first digit is O(zero) followed by
the letter o.
For example, 0o35 number is equivalent to 29 in decimal number system (29)10 = (35)8.
Some more examples of octal integer literal are 0o45, 0o26, 0o345, etc.
An octal integer literal cannot contain the digits 8 and 9. So, 0o28, 0o49, etc., are invalid
octal integer literals.

 Hexadecimal form / Hexadecimal Integer Literal (base 16): A hexadecimal integer


literal contains 16 digits from 0-9 and letters A-F. Here the first digit is O(zero) followed
by the letter x The sequence of digits is preceded by Ox or OX. For example: Ox19F,

0x3C, OXEA, etc. 16


1.2.3 Tokens in Python – Literals (Values) – Numeric Literals

17
1.2.3 Tokens in Python – Literals (Values) – Boolean Literals

 A Boolean literal in Python is used to represent one of the two Boolean values i.e.,
True (Boolean true) or False (Boolean false).

 A Boolean literal can either have value as True or as False.

18
1.2.3 Tokens in Python – Literals (Values) – Special Literal None
 Python has one special literal, which is None.

 None Literal is used to indicate something that has not yet been created. It is legal
empty value in Python

 The None literal is used to indicate absence of value / to define null variable.

 Python can also store literal collections, in the form of tuples and lists etc.

 None is not the same as 0, False, or empty. It typically means "No value".

19
1.2.3 Tokens in Python – Operators
 Operators are tokens that trigger some computation / action when applied to
variables and other objects in an expression.
 The operators can be

 Arithmetic operators ( +, -, *, /, %, **, // )  Logical operators ( and, or )

 Bitwise operators ( &, ^, | )  Assignment operator ( = )

 Shift operators ( <<, >> )  String operator (+, *) (Lesson-2)

 Identity operators ( is, is not )  Membership operators ( in, not in )

 Relational operators ( >, <, >=, <=, ==, != )  Arithmetic-Assignment operators


( /=, +=, -=, */, %=, **=, //=)

20
1.2.3 Tokens in Python – Arithmetic Operators

21
22
1.2.3 Tokens in Python – Bitwise Operators

23
1.2.3 Tokens in Python – Bitwise Operators
 A bitwise operator is used to compare (binary) numbers.

& Returns 1 if both the bits are 1 otherwise 0


Binary Number
Returns 1 if either of the bit is 1 otherwise 0
| No 23 22 21 20 O
Returns 1 if one of the bits is 1 and the other is 0 otherwise U
^ returns false 8 4 2 1 T
P
1=True 0=False 10  1 0 1 0
U
A B A&B A|B A^B
8  1 0 0 0 T
0 0 0 0 0
Bitwise And & 1 0 0 0 8
0 1 0 1 1
1 0 0 1 1 Bitwise Or | 1 0 1 0 10

1 1 1 1 0 Bitwise Xor ^ 0 0 1 0 2
>>> print(bin(x))
>>> x=10
0b1010 >>> print(bin(x&y)) >>> print(bin(x|y)) >>> print(bin(x^y),x^y)
>>> y=8
>>> print(bin(y)) 0b1000 0b1010 0b10 2
24
0b1000
25
1.2.3 Tokens in Python – Shift Operators
 A bitwise operator is used to compare (binary) numbers.

26
1.2.3 Tokens in Python – Right Shift Operators

>> Shifts the bits of the number to the right and fills 0

Binary Number O
U
No 23 22 21 20 T
P
8 4 2 1
U
X=10  1 0 1 0 T

X>>1  1 0 1 5

X>>2  1 0 2

X>>3  1 1

27
1.2.3 Tokens in Python – Left Shift Operators

<< Shifts the bits of the number to the left and fills 0

Binary Number O
U
No 26 25 24 23 22 21 20 T
P
64 32 16 8 4 2 1
U
X=10  1 0 1 0 T

X<<1  1 0 1 20

X<<2  1 0 1 40

X<<3  1 0 1 80

28
1.2.3 Tokens in Python – Identity Operators

29
1.2.3 Tokens in Python – Membership Operators

30
1.2.3 Tokens in Python – Relational / Comparison Operators
 Relational operators are used to compare the values of two operands and return
Boolean true or false accordingly.

31
1.2.3 Tokens in Python – Logical / Boolean Operators
 The logical operators are used on conditional statements, which result into either
true or false.

32
33
1.2.3 Tokens in Python – Arithmetic / Augmented / Compound
Assignment Operators

34
1.2.3 Tokens in Python – 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 programming language are :

‘ ‘’ # \ () [] {} @ : . ` =
Equal

Single Quotes Backslash Curly Bracket


dot Backtick
Double Quotes Parenthesis Colon

Hash Square Bracket

35
1.3 BAREBONES OF A PYTHON PROGRAM
 A Python program may contain various elements such as

 Expressions : The valid combination of both operands and operators makes an


expression which returns a computed result.

36
1.3 BAREBONES OF A PYTHON PROGRAM
 A Python program may contain various elements such as

 Statements: which are programming instructions.

37
1.3 BAREBONES OF A PYTHON PROGRAM
 A Python program may contain various elements such as
 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.

38
1.3 BAREBONES OF A PYTHON PROGRAM
 A Python program may contain various elements such as

 Functions, which are


named code-sections and
can be reused by specifying
their names (function calls).

39
1.3 BAREBONES OF A PYTHON PROGRAM
 A Python program may contain various elements such as

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

40
1.4 VARIABLES AND ASSIGNMENTS
 Variables represent labelled storage locations, whose values can be manipulated
during program run.

41
1.4.1 DYNAMIC TYPING Vs STATIC TYPING
DYNAMIC TYPING STATIC TYPING

A variable pointing to a value of a certain In Static typing, a data type is attached


type, can be made to point to a with variable when it is defined first and
value/object of different type. This is it is fixed. That is, data type of a variable
called Dynamic Typing. cannot be changed in Static Typing

42
1.4.1 DYNAMIC TYPING Vs STATIC TYPING
DYNAMIC TYPING STATIC TYPING

Examples: Perl, Ruby, Python, PHP,


Examples: C, C++, Java, Rust, Go, Scala
JavaScript, Erlang
Assigning same value to multiple Assigning same value to multiple
variables in a single statement. variables in a single statement.
Examples: a = b = c = 10 Examples: a = b = c = 10
Assigning multiple values to multiple
variables in a single statement. Not Possible
Examples: a, b, c = 10, 20, 30

43
1.4.1 DYNAMIC TYPING Vs STATIC TYPING
DYNAMIC TYPING STATIC TYPING

X=3

X=3 X=4 X=5 X=6

X=6
Variable X stores different values at fixed
location (Memory-Address) Memory Address

Variable X stores different values at same


location (Memory-Address)
44
1.4.1 DYNAMIC TYPING Vs STATIC TYPING

45
1.5 SIMPLE INPUT & OUTPUT

 Input() function is used to accept the value for a variable from the user.

 Input() function takes one string argument only but whatever value is being entered
by the user, it will be taken as string argument

input( ) function

always returns a
value of String type.

46
1.5 SIMPLE INPUT & OUTPUT

 To input integer or float values, we can use int() or float() along with input().

47
1.5 SIMPLE INPUT & OUTPUT

 print() function is used to display the output of any command on the screen.

print( ) function

Without any
value/name/Expression
Prints a blank line

48
1.5 SIMPLE INPUT & OUTPUT
 The print statement has a number of features :
 It auto-converts the items to strings
i.e., if you are printing a numeric value, it will automatically convert it into
equivalent string and print it ;

 if you are printing a numeric expressions,


it first evaluates them and then converts the result to string. before printing.

49
1.5 SIMPLE INPUT & OUTPUT

 The print statement has a number of features :

 The separator argument in Python is space by default which can be modified and
can be made to any character, integer or string as per our choice

50
1.5 SIMPLE INPUT & OUTPUT

 The print statement has a number of features :

 The end argument in Python is used to add any string at the end of the output of
the print statement.

51
1.5 SIMPLE INPUT & OUTPUT

 The print statement has a number of features :

 The end argument in Python is used to add any string at the end of the output of
the print statement.

52
1.6 Data Types / Core (Main) Data Types

 Data types are means to identify type of data and set of valid operations for it.

 These are number, boolean, sequence, sets, none, and mapping. Some of the data
types are only available in certain versions of the language.

53
1.6 Data Types / Core (Main) Data Types - Numbers

 In Python, the number data type represents the data that has a numeric value.

 The numeric value can be integer, decimal, or a complex number. These values are
defined as int, float, and complex, respectively.

 ALL READY LEARNED ()

54
1.6 Data Types / Core (Main) Data Types - Boolean

 The Boolean data type provides two built-in values, True and False.

 The truth values of an expression are stored as a Python data type called bool.

 True can be represented by a non-zero value 1, whereas false can be represented by


0.

55
1.6 Data Types / Core (Main) Data Types - Sequence

 A sequence is an ordered collection of similar or different data elements, having the


same or different data types.

 There are three types of sequence data types: string, list, and tuple.

56
1.6 Data Types / Core (Main) Data Types - Sequence

 String: A string can be defined as a collection of one or more characters enclosed in a


single quotation, double-quotation, or triple quotation marks.

 It is represented by the str class. Some of the valid strings in Python are: "xyz",
'"name'", '$$$’.

 A string can hold any type of known characters i.e., letters, numbers, and special
characters, of any known scripted language.

57
1.6 Data Types / Core (Main) Data Types - Sequence
 String: Valid string index/indices are 0, 1, 2….up to length-1 in forward direction

and

-1, -2, -3……. length in backward direction.

Exampl: a=“GREEN VALLEY”

BACKWARD DIRECTION -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1


G R E E N V A L L E Y
FORWARD DIRECTION 0 1 2 3 4 5 6 7 8 9 10 11

58
1.6 Data Types / Core (Main) Data Types - Sequence

 List: Lists in Python contain items of different data types & it is mutable that is
changeable one can change / add / delete a list’s elements. .

 The items stored in the list are separated by a comma (,) and are enclosed using
square brackets [ ].

 A list stores elements in a sequence from Zero(0), one after another….1,2,3….so ..on.

59
1.6 Data Types / Core (Main) Data Types - Sequence

 Tuple: Tuples in Python contain items of different data types & it is immutable that is
non-changeable one cannot make change / add / delete a list’s elements. .

 The elements in a tuple are separated by a comma (,) and are enclosed in
parentheses () & should be at least 2 elements in tuple.

 A tuple stores elements in a sequence from Zero(0), one after another.1,2,3….so ..on.

60
61
1.6 Data Types / Core (Main) Data Types - Set

 A set is an unordered collection of unique elements. It is created like list.

 It can take values of different types but it is mutable.

{ }

62
1.6 Data Types / Core (Main) Data Types - None

ALL READY LEARNED ()

63
1.6 Data Types / Core (Main) Data Types - Mapping

 Consider a telephone directory. Here, a phone number is associated with a particular


person. This is called mapping. A key is there to map a particular data item.

 Dictionary: In Python, a dictionary is a mapping data type, where a key is mapped to


its corresponding value. It is an unordered collection of key:value pairs within { }.

 Values in a dictionary can be of any data type and can be duplicated.

 However, the keys of a dictionary must be unique. They are case-sensitive too.

 The mapping or dictionary data type is best suited when you have a large amount of
data. You just need to know the key to retrieve the data.

64
1.6 Data Types / Core (Main) Data Types - Mapping

 The mapping or dictionary data type is best suited when you have a large amount of
data. You just need to know the key to retrieve the data.

Key1:value1, key2:value2

65
{ }

Key1:value1, key2:value2

66
67
1.7 Mutable Types & Immutable Types
Mutable Immutable

A mutable object can be modified after it Immutable objects cannot be modified


is created. after their creation .
Mutable types are those whose values Immutable types are those that can never
can be changed in place. change their value in place.
Mutable objects: Immutable objects:
list, dictionary, set Int, float, complex, string, tuple

68
1.7 Mutable Types & Immutable Types
Mutable Immutable

Mutable objects: Immutable objects:


list, dictionary, set Int, float, complex, string, tuple

69
70
1.8 Expression

 An expression is a combination of operators, literals, and variables.

 The Python interpreter evaluates the expression and displays the result.

 An expression appears on the right-hand side because it evaluates and assigns the
result of an expression to the identifier on the left-hand side.

71
1.8.1 & 18.2 & 18.3 Expression

 The expressions in Python can be of any type : Arithmetic expressions, String


expressions, Relational expressions, Logical expressions, Compound expressions etc.

 Arithmetic operators ( +, -, *, /, %, **, // )  Logical operators ( and, or )

 Bitwise operators ( &, ^, | )  Assignment operator ( = )

 Shift operators ( <<, >> )  String operator (+, *)

 Identity operators ( is, is not )  Membership operators ( in, not in )

 Relational operators ( >, <, >=, <=, ==, != )  Arithmetic-Assignment operators


( /=, +=, -=, */, %=, **=, //=)

72
1.8.1 & 18.2 & 18.3 Expression (Operator Precedence)
 Precedence means priority.

 If multiple operators are used in a


Python expression, the precedence
rule determines the order in which
they should be executed.

 The following table gives the


precedence order from high to low
for the operators in Python:

73
1.8.1 & 18.2 & 18.3 Expression (Operator Precedence)
 Precedence means priority.

74
1.8.1 & 18.2 & 18.3 Expression (Operator Associativity)
 Associativity: If two operators have the same precedence (priority), then they are
either evaluated from "Left to Right" or from "Right to Left" based on their level.

 Higher precedence operators are operated before the lower precedence operators.

 When an expression contains operators, which have the same precedence (like * and
%), then whichever operator comes first is evaluated first.

75
1.8.1 & 18.2 & 18.3 Expression (Operator Associativity)
 Associativity: If two operators have the same precedence (priority), then they are
either evaluated from "Left to Right" or from "Right to Left" based on their level.

 Almost all the operators except the exponentiation ( ** ) support the left-to-right
associativity.

76
77
1.8.4 Implicit & Explicit Type Conversion
 The process of converting the value of one data type (integer, string, float etc.) to
another is called type conversion.

 Python supports two types of data type conversion:

 Implicit Type Conversion

 Explicit Type Conversion

78
1.8.4 Implicit & Explicit Type Conversion
 Implicit Type Conversion : Python automatically associates variable with the data type
class when it is created. This is known as Implicit type casting.

79
1.8.4 Implicit & Explicit Type Conversion
 Explicit Type Conversion : Explicit type conversion is known as type casting.

 In Python, this type of type casting is done manually, i.e., you can convert the data type
of an object to the required data type using int(), float(), or str() function.

 Type casting in Python is performed by <type>( ) function of appropriate data type, in


the following manner :

<datatype> (expression)

80
1.8.4 Implicit & Explicit Type Conversion
 Explicit Type Conversion :

81
1.8.4 Implicit & Explicit Type Conversion
 Explicit Type Conversion :

82
1.8.5 Math Library Functions
 Python's standard library provides a module namely math for math related functions
that work with all number types except for complex numbers.

 In order to work with functions of math module, you need to first import it to your
program by giving statement as follows as the top line of your Python script :

import math

 Then you can use math library's functions as math.<function-name> .

83
84
85
86
1.9 STATEMENT FLOW CONTROL
 In a program, statements may be executed sequentially, selectively or iteratively.

 A sequential is a statements that are executed one after another in a serial order.

 A conditional is a statement set which is executed, on the basis of result of a condition.

 A loop is a statement set which is executed repeatedly, until the end condition is
satisfied.

87
1.9 STATEMENT FLOW CONTROL
1) A compound statement represents a group of statements executed as a unit.

 The compound statements of Python are written in a specific pattern as shown below :

<compound statement header > :

<indented body containing multiple simple and/or compound statements>

 The conditionals and the loops are compound statements.

88
1.9 STATEMENT FLOW CONTROL
 For all compound statements, following points hold :
 The contained statements are not written in the same column as the control statement, rather
they are indented to the right and together they are called a block.

 The first line of compound statement, i.e., its header contains a colon (:) at the end of it.

89
1.9 STATEMENT FLOW CONTROL
2) Simple Statement : Compound statements are made of simple statements. Any single
executable Statement is 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. It takes the following form pass

 Wherever Python encounters a pass statement, Python does nothing and moves to next
statement in the flow of control.

90
1.10 Sequential Statements
 Statements or instructions that are executed one after another in a serial order are
called sequential control flow statements.

 It means that your program will execute line-by-line.

91
1.10 Conditional or Decision Making Statements
 Statements are also known as Decision-Making statements or Selection statements.

 Conditional statements can be implemented in Python using the following types of


statements:

 if statement

 if-else statement

 if-elif-else statement

 nested if statement

92
1.10 Conditional or Decision Making Statements
Conditional Statements Syntax Example

if statement: It is used to if conditional expression: num = int(input("Enter any number: “))


decide whether a certain statement(s)
if (num > 0):
statement or block of
print( "Number is positive. ")
statements will be executed on
the given condition.
if-else statement: It checks for if conditional expression: num = int(input("Enter any number: “))
the expression given with the if statement(s)
else: if (num > 0):
block. If the expression returns
statement(s) print( "Number is positive. ")
true, the statements written in else:
the if block will be executed. print( "Number is not greater than zero.
Otherwise, the else block will ")
be executed.

93
1.10 Conditional or Decision Making Statements
Conditional Statements Syntax Example

if conditional expression1: num = int(input("Enter any number:”))


if-elif-else statement: It allows
you to check multiple statement(s)
if (num>0):
expressions. If the expression is elif condition expression2:
statement(s) print("Number is positive.”)
true, it executes the subsequent
elif condition expression3: elif (num < 0) :
statements. Otherwise, it
statement(s)
checks for the next expression print("Number is negative.”)
elif ……………………… :
given with the elif block, and so else:
……
on. If all the expressions are else: print("Number is zero.”)
false, the body of else is block of code n
executed. 94
1.10 Conditional or Decision Making Statements
Conditional Statements Syntax Example

num = int(input("Enter any number:”))

if conditional expression:
Nested if: An if statement if num > = 0:
if conditional expression:
inside another if statement is if num == 0:
statement(s)
referred to as a nested if. An if else: print ("Zero " )
statement can be nested when statement(s)
else:
you want to check for another else:
expression after an expression statement(s) print("positive number")

evaluates to true. else:

print("Negative number")
95
1.10.5 Storing Condition / Named Condition
 The all() function returns True[1] if all items in an iterable are true, otherwise it returns
False[0]. It returns Boolean value.

 It is an iterable object such as a dictionary, tuple, list, set, if condition etc.

96
1.11 Range Function
 The range() function is a built-in function of Python. It allows the user to generate a
sequence of numbers.

 There are three ways to implement the range() function in Python:

97
1.11 Range Function

 Range (n) - The range() function returns a sequence of numbers.


By default, it starts with value 0 and increments it by 1.

98
1.11 Range Function

 Range (start,stop) - This function generates a set of whole numbers


starting from start to stop-1.

99
1.11 Range Function

 Range (start,stop) - This generates whole numbers from start till stop-I.

 The step_size indicates the increment or number that comes next in the sequence.

 By default, the step size is 1. The step_size cannot be zero.

100
1.11 Negative Steps in Range Function
 To decrement or display the elements in a reverse order, there should be always

 declare the step size with a negative number (-1 ).

 The value -1 is the last index value of an element of the sequence as shown in the
below example:

101
Range ( 10 , 0 , -1) -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
0 1 2 3 4 5 6 7 8 9 10
Range ( 0 , 10 , 1) 0 1 2 3 4 5 6 7 8 9

102
1.11 Iterative Statements / Looping Statements
 An iterative statement is used to repeat a block of statements or set of instructions for
a specific number of times until the defined condition is met. Repeating a code section
is called iteration or looping.

 There are two types of looping statements:

 for loop

 while loop

103
1.11 Iteration or Looping Statements
Conditional Statements Syntax Example

for loop: It is used to iterate


over the items in a sequence,
for <variable> in <sequence>:
such as a list or string of
characters, performing the statement(s)
same action on each item in
the list.

104
1.11 Iteration or Looping Statements
Conditional Statements Example
while loop: It is an entry-controlled
loop. It executes a set of statements
based on a condition. If the test
expression evaluates to true, then the
body of the loop gets executed.
Otherwise, the loop stops iterating and
the control comes out of the body of
the loop.
Syntax

while <logical expression>:


loop-body
increment/decrement
105
1.12 Jump Statements – Break , Continue & Pass Statement
 The Jump statement allows you to change the flow of a loop.

 It is used to terminate a loop, skip a part of the loop, or exit from the loop at a specific
condition.

 Python supports three types of jump statements: break, continue, and pass.

106
1.12 Jump Statements – Break Statement
 The 'break' is a keyword. It terminates the loop and transfers the control out of the
while or for loop. It helps to stop the iteration in between its execution.

107
1.12 Jump Statements – Break Statement

108
1.12 Jump Statements – Continue Statement
 The ‘continue’ is a keyword. It is used to skip the current iteration and transfers the
control to the top of the loop. The condition of the loop evaluates again and resumes
the loop from the next iteration.

109
1.12 Jump Statements – Continue Statement

110
1.12 Jump Statements – Pass Statement
 The 'pass' is a keyword. It is a null statement or empty statement or
a statement which does nothing. It takes the following form pass

 Wherever Python encounters a pass statement, Python does nothing and moves to next
statement in the flow of control.

 The difference between a comment and a pass statement in Python is that while the
interpreter ignores a comment entirely, pass is not ignored.

 It allows you to create loops, functions, etc. However, you cannot leave the body of the
function or loop empty. In such cases, the pass statement is useful which does nothing
but makes the code syntactically correct.

111
1.12 Jump Statements – Pass Statement

112
1.13 More on Loops
 There are two more things you need to know about loops

 loop else clause

 Infinite loops

 nested loops

113
1.13 More on Loops – Loop else Statement
 The else clause of a Python loop executes when the loop terminates normally, i.e.,
when test-condition results into false for a while loop or for loop

114
1.13 More on Loops – Infinite Loops
 In some cases, the test expression in the while or for loop will never become false, then
the loop keeps on repeating the block of statements infinitely.

 Such a loop never ends. This state of the loop is called an infinite

115
1.13 More on Loops – Nested Loops
 A loop inside a loop is called a nested loop. This is called a loop inside a loop or nested
loop.

 Nested loops are commonly used to print patterns and mathematical matrix
operations.

116
117
j=0 j=1 j=2
i=0 *
i=1 * *
i=2 * * *

118
Python
Revision
tour
chapter completed.
Lesson-1

119
Thank you
[email protected]

You might also like