23UINTC33 - PYTHON Programming
UNIT II
Iterative Control- While Statement- Infinite loops- Definite vs. Indefinite Loops-Boolean Flag. String,
List and Dictionary, Manipulations Building blocks of python programs, using ranges.
Iterative Control
Iteration statements or loop statements allow us to execute a block of statements repeatedly as long
as the condition is true.
(Loops statements are used when we need to run same code again and again)
TypeofIterationStatementsInPython3
In Python Iteration(Loops)statements are of three types:-
1. While Loop
2. For Loop
3. Nested Loops
1. WhileLoopInPython
While Loop In Python is used to execute a block of statement till the given condition is true. And
when the condition is false, the control will come out of the loop.
The condition is checked every time at the beginning of the loop.
While Loop Syntax
while(<condition>):
statements
[Link]/AP – DEPARTMENT OF COMPUTER SCIENCE AND APPLICATION -RASC Page 1
23UINTC33 - PYTHON Programming
Flow chart of While Loop
PythonFlowchartofWhileLoop
ExamplesOfWhileLoop
[Link]/AP – DEPARTMENT OF COMPUTER SCIENCE AND APPLICATION -RASC Page 2
23UINTC33 - PYTHON Programming
x =0 x =1
while(x<5): print(x) while (x <= 5):
x =x +1 print(―Welcome ―) x =
x+1
Output:-
0 Output:-
1 Welcome
2 Welcome
3 Welcome
4 Welcome
Welcome
[Link]/AP – DEPARTMENT OF COMPUTER SCIENCE AND APPLICATION -RASC Page 3
23UINTC33 - PYTHON Programming
WhileLoopWithElseInPython
Theelsepartisexecutediftheconditioninthewhileloopbecomes False.
SyntaxofWhileLoopWithElse
while (condition):
loopstatements
else:
elsestatements
Exampleof WhileLoopWithElse
x =1
while(x<5):
print(‗insidewhileloopvalueofxis‗,x)
x=x+1else:
print(‗insideelsevalueofxis‗,x)
Output:-
insidewhileloopvalueofxis1
insidewhileloopvalueofxis2
insidewhileloopvalueofxis3
insidewhileloopvalueofxis4 inside
else value of x is 5
2. For Loop In Python
For loop in Python is used to iterate over items of any sequence, such as a list or a string.
For Loop Syntax
For val in sequence:
statements
Flow chart of For Loop
[Link]/AP – DEPARTMENT OF COMPUTER SCIENCE AND APPLICATION -RASC Page 4
23UINTC33 - PYTHON Programming
Python Flow chart of For Loop
[Link]/AP – DEPARTMENT OF COMPUTER SCIENCE AND APPLICATION -RASC Page 5
23UINTC33 - PYTHON Programming
ExampleSofForLoop
foriinrange(1,5): for i in [1,2,3,4] : print(―WELCOME‖)
print(i)
Output :-
Output:- WELCOM
1 E
2 WELCOM
3 E
4 WELCOM
E
WELCOM
E
****The range()Function In Python
The range()function is a built-in that is used to iterate over a sequence of numbers.
Syntax Of range()Function range(start,stop[,step])
The range()Function Parameters
start: Starting number of the sequence.
stop: Generate numbers up to, but not including this number.
step(Optional):Determines the increment between each numbers in the sequence
Example1ofrange()function
For i inrange(5): Example2ofrange()function
print(i) For i in
range(2,9):
Output print(i)
:-0 Output
1
2 :-2
3
3 4
4 5
6
7
Example3 of range()function using step
parameter 8
foriinrange(2,9,2): Example 4 of range() function
print(i) For i in range(0,-10,-2):
Output print(i)
RunCode
:-2 Output:-
4
6 0-2
-4
8 -6
-8
[Link]/AP – DEPARTMENT OF COMPUTER SCIENCE AND APPLICATION -RASC Page 6
23UINTC33 - PYTHON Programming
For Loop With Else In Python
The else is an optional block that can be used with for [Link] block with
[Link] did not encounter any
break.
Example 1of For Loop With Else
list=[2,3,4,6,7]
for i in range(0,len(list)): if(list[i]==4):
print(‗listhas4‘) else:
print(‗listdoesnothave4‘)
Run Code
Output:-
Listhas 4
listdoesnothave5
Example 2 of For Loop With Else
For i inrange(0,len(list)): if(list[i]==5):
print(‗5isthereinthelist‘) break
else:
print(‗listdoesnothave5‘) Run Code
Output:-
listdoesnothave5
[Link]/AP – DEPARTMENT OF COMPUTER SCIENCE AND APPLICATION -RASC Page 7
23UINTC33 - PYTHON Programming
NESTED loops in Python:
The placing of one loop inside the body of another loop is called nesting. When you "nest
"two loops, the outer loop takes control of the number of complete repetitions of the inner
loop
1. Nestedwhileloop
Syntax :
Initialization
while (condition):
initialization of inner loop while(condition):
------
------
Update expression of inner loop
Update expression of outer loop
Examples
[Link]/AP – DEPARTMENT OF COMPUTER SCIENCE AND APPLICATION -RASC Page 8
23UINTC33 - PYTHON Programming
[Link]
Syntax
for iterating_var in sequence:
foriterating_varinsequence:
statements(s)
statements(s)
Example
23UINTC33 - PYTHON Programming
Infinite loops
An infinite loop is an iterative control structure that never terminates (or eventually
terminates with a system error). Infinite loops are generally the result of programming errors.
Such infinite loops can cause a program to “hang,” that is, to be unresponsive to theuser. In such
cases, the program must be terminated by use of some special keyboard input (such as ctrl-C) to
interrupt the execution.
EX:
Definite vs .Indefinite Loops
A definite loop is a program loop in which the number of times the loop will iterate can
be determined before the loop is executed. Although it is not known what the value of n will be
until the input statement is executed, its value is known by the time the while loop is reached.
Thus, it will execute “n times.”
23UINTC33 - PYTHON Programming
EX:
sum =0
current=1
n=input('Entervalue:') while current <= n:
sum =sum +current
current=current+ 1
Anindefiniteloopisaprogramloopinwhichthenumberoftimesthattheloopwill iterate cannot
be determined before the loop is executed.
EX:
which = input("Enter selection: ")
whilewhich!='F'andwhich!='C':
which5=input("Pleaseenter'F'or'C': ")
Boolean Flags and Indefinite Loops
A single Boolean variable used as the condition of a given control statement is called a
Boolean flag.
List Structures
23UINTC33 - PYTHON Programming
What Is a List?
A list is a linear data structure, meaning that its elements have a linear ordering. That is,
there is a first element, a second element, and soon. In which each item in the list is identified by
its index in which each item in the list is identified by its index value.
EX:
Common List Operations
Operations commonly performed on lists include retrieve, update, insert, delete (remove)
and append.
EX:
34
23UINTC33 - PYTHON Programming
List Traversal
A list traversal is a mean so accessing, one-by-one, the elements of a list.
EX:
Lists(Sequences)in Python
Python List Type
A list in Python is a mutable, linear data structure of variable length, allowing mixed-type
elements. Mutable means that the contents of the list may be altered. Lists in Python use zero
based indexing. Thus, all lists have index values 0 ... n-1, where n is the number of elements in
the list. Lists are denoted by a comma-separated list of elements within square brackets.
An empty list is denoted by an empty pair of square brackets,[].Elements of a list
are accessed by using an index value within square brackets.
EX:
lst5 [1,2,3]
lst[0] ➝ 1 access of fi rst element
lst[1]➝2accessofsecondelement lst[2]
➝ 3 access of third element
23UINTC33 - PYTHON Programming
Tuples
A tuple is an immutable linear data structure. Thus, in contrast to lists, once a tuple is
defined, it cannot be altered. Otherwise, tuples and lists are essentially the same. To distinguish
tuples from lists, tuples are denoted by parentheses instead of square brackets.
EX:
student5('JohnSmith',48,'ComputerScience', 3.42)
Another difference between tuples and lists is that tuples of one element must include a
comma following the element. Otherwise, the parenthesized element will not be made into a
tuple.
An empty tuple is represented by a set of empty parentheses, (). (We shall later see the
usefulness of the empty tuple.) The elements of tuples are accessed the same as lists, with square
brackets, Thus, delete, update, insert, and append operations are not defined on tuples.
Sequences
A sequence in Python is a linearly ordered set of elements accessed by an index number.
Lists, tuples, and strings are all sequences. Strings, like tuples, are immutable ; therefore, they
cannot be altered.
23UINTC33 - PYTHON Programming
Nested Lists
Lists and tuples can be nested within each other to construct arbitrarily complex data
structures.
EX:
class_grades5=[[85,91, 89], [78,81, 86], [62,75, 77], ...]
class_grades[0][0]➝[85, 91, 89][0]➝85
Iterating Over Lists(Sequences)in Python
For Loops
A for statement is an iterative control statement that iterates once for each element in a
specified sequence of elements. Thus, for loops are used to construct definite loops.
Variable k is referred to as a loop variable.
EX:
For chin'Hello':
23UINTC33 - PYTHON Programming
print(ch)c
The Built-in range Function
Python provides a built-in range function that can be used for generating a sequence of
integers that a for loop can iterate over. The values in the generated sequence include the starting
value, up to but not including the ending value.
EX:
Sum =0
for k in range(1, 11):
sum= sum +k
Thisforloopaddsuptheintegervalues1–[Link],therangefunctiongeneratesa
23UINTC33 - PYTHON Programming
sequence of consecutive integers. A “step” value can be provided, however. Range (0, 11, 2)
produces thesequence [0,2, 4, 6,8, 10],with astep valueof2. Asequence can also begenerated
“backwards” when given a negative step value. For example, range (10, 0, 2 1) produces the
sequence [10,9, 8, 7, 6, 5, 4, 3, 2, 1].
Iterating Over List Elements vs. List Index Values
An index variable is a variable whose changing value is used to access elements of an
indexed data structure. However, there are times when the loop variable must iterate over the
index values of a list instead.
While Loops and Lists(Sequences)
Forsituationsinwhichasequenceistobetraversedwhileagivenconditionistrue,a while loop is
the appropriate control structure to use.
EX:
23UINTC33 - PYTHON Programming
Python String
Last Updated : 12 Jun, 2025
A string is a sequence of characters. Python treats anything inside quotes as a string. This includes
letters, numbers, and symbols. Python has no character data type so single character is a string of
length 1.
s = "GfG"
print(s[1]) # access 2nd char
s1 = s + s[0] # update
print(s1) # print
Output
f
GfGG
In this example, s holds the value "GfG" and is defined as a string.
Creating a String
Strings can be created using either single (') or double (") quotes.
s1 = 'GfG'
s2 = "GfG"
print(s1)
print(s2)
Output
GfG
GfG
Multi-line Strings
If we need a string to span multiple lines then we can use triple quotes (''' or """).
s = """I am Learning
Python String on GeeksforGeeks"""
print(s)
s = '''I'm a
Geek'''
print(s)
Output
I am Learning
Python String on GeeksforGeeks
I'm a
23UINTC33 - PYTHON Programming
Geek
Accessing characters in Python String
Strings in Python are sequences of characters, so we can access individual characters
using indexing. Strings are indexed starting from 0 and -1 from end. This allows us to retrieve
specific characters from the string.
The Building Blocks of Python:
Variables and Data Types
Input and Output
Operators
1. Variables and Data Types:
What is Variable?
Variables are containers where you can store data in your programs. Just like giving a name to a box
so you know what's inside, you give your variables names to help you use their data laterExamples:
name = "Hossen" # String
grade = 97 # Integer
height = 6.1 # Float
is_student = True # Boolean
Varibale Naming Conventions:
Variable naming conventions are essential to maintain code readability and follow best practices.
Here are the rules and conventions for naming variables in Python:
Must start with a letter or the underscore character
Cannot start with a number
Can contain letters, numbers, and underscores (A-z, 0-9, and _)
They are case-sensitive (age, Age and AGE are three different variables)
Cannot use any reserved words or keywords
If you have a longer name, use snake_case (preferred), camelCase, or PascalCase.
Variable Casting:
If you want to specify the data type of a variable, it can be achieved by casting.
x = str(5) # x will be '5'
y = int(5) # y will be 5
z = float(5) # z will be 5.0
Get the Type of Variable:
You can get the data type of a variable with the type() function.
23UINTC33 - PYTHON Programming
x=5
y = "Refat"
z = True
print(type(x))
print(type(y))
print(type(z))
Assign Multiple Variables
Python allows you to assign values to multiple variables in one line:
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
N.B. String variables can be declared either by using single or double quotes.
Types of Data
In programming, data types are an important concept. Variables can store different types of data, and
each type has its own unique capabilities. Python comes with several built-in data types by default,
which can be organized into the following categories:
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
None Type: NoneType
2. Input and Output
Input:
Python’s input() function allows you to capture input from the user. The input is always treated as a
string unless explicitly converted.
name = input("What is your name? ")
Output:
The print() function is used to display information. You can combine strings and variables for a
more interactive experience.
age = 25
print("I am", age, "years old.")
# Using f-strings for adding dynamic value:
print(f"I am {age} years old.")
3. Operators
Operators are special symbols or keywords that perform operations on data. They tell the computer
what kind of operation or action to perform (eg. +, -, *, /).
Operands are the values or variables that operators work on - They're the data, the operator uses to
23UINTC33 - PYTHON Programming
do its job.
Python divides the operators into the following groups:
Arithmetic operators: Arithmetic operators are used with numeric values to perform common
mathematical operations:
x+y # Addition
x-y # Subtraction
x*y # Multiplication
x/y # Division
x%y # Modulus
x ** y # Exponentiation
x // y # Floor division
Assignment operators: Assignment operators are used to assign values to variables.
x=8
x += 8
x -= 8
Comparison operators: Comparison operators are used to compare two values:
x == y # Equal
x != y # Not Equal
x>y # Greater than
x<y # Less then
x >= y # Greater than or equal to
x <= y # Less than or equal to
Logical operators: Logical operators are used to combine conditional statements:
x < 5 and x < 10
# Returns True if both statements are true
x < 5 or x < 4
# Returns True if one of the statements is true
not(x < 5 and x < 10)
# Reverse the result, returns False if the result is true
Identity operators: Identity operators are used to compare the objects, not if they are equal, but if
they are the same object, with the same memory location:
x is y
# Returns True if both variables are the same object
x is not y
# Returns True if both variables are not the same object