MODULE I - FUNDAMENTALS OF PYTHON
Features of Python – Data types: Numbers, Strings & its
operations, Boolean – Operators – List & its operations, Tuples &
its operations, Dictionaries & its operations – Arrays – Input and
Output – Conditions statements: if, if-else, if-elif-else – Looping
statements: while, for
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
FEATURES OF PYTHON
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
WHY TO LEARN PYTHON?
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
FEATURES OF PYTHON
Following are important Features of Python Programming
• It supports functional and structured programming methods
as well as OOP.
• It can be used as a scripting language or can be compiled to
byte-code for building large applications.
• It provides very high-level dynamic data types and supports
dynamic type checking.
• It supports automatic garbage collection.
• It can be easily integrated with C, C++, COM, ActiveX, CORBA,
and Java.
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
DATA TYPES: NUMBERS, STRINGS & ITS OPERATIONS
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
DATA TYPES: NUMBERS, STRINGS & ITS OPERATIONS
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
Values and Variables
• In this chapter we explore some building blocks that are used
to develop Python programs.
• We experiment with the following concepts:
numeric values
variables
assignment
Identifiers
reserved words
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
INTEGER VALUES
• The number four (4) is an example of a numeric value.
• In mathematics, 4 is an integer value.
• Integers are whole numbers, which means they have no
fractional parts, and they can be positive, negative, or zero.
• Examples of integers include 4, −19, 0, and −1005.
• In contrast, 4.5 is not an integer, since it is not a whole
number.
• Python supports a number of numeric and non-numeric
values.
• In particular, Python programs can use integer values.
• The Python statement print(4) prints the value 4
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
Example –Integer value entered in python editor and its behavior
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
Use of + symbol for normal arithmetic addition
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
Use of Int() & str() functions in python
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
How + operator works with string
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
“type” function to find the expression type(whether its int or str)
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
Variables and Assignment
• Variables are nothing but reserved memory locations to
store values. This means that when you create a variable
you reserve some space in memory.
• Based on the data type of a variable, the interpreter
allocates memory and decides what can be stored in the
reserved memory.
• Therefore, by assigning different data types to variables,
you can store integers, decimals or characters in these
variables.
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
Python Identifiers
• A Python identifier is a name used to identify
– a variable,
– function,
– class, module
– or other object.
• 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 punctuation characters such as @, $, and %
within identifiers.
• Python is a case sensitive programming language.
Thus, Manpower and manpower are two different identifiers in Python.
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
Floating-point Types
• Python supports non-integer numbers, and they are called
floating point numbers.
• The name implies that during mathematical calculations
the decimal point can move or “float” to various positions
within the number to maintain the proper number of
significant digits.
• The Python name for the floating-point type is float.
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
STRING
String data type written is python in single or double code
x = ‘hello’
y = “Crescent”
z = input()
print(“ here is an example”, x, y, z)
Name = “Crescent”
Len(Name)
Output : ?
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
STRING
Index no start o and lenth7
Name[2]
Output e
Name[2:8]
Output escent
Name.upper()
Output ‘CRESCENT’
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
Python Strings
String Literals
String literals in python are surrounded by either single quotation marks, or double
quotation marks.
'hello' is the same as "hello".
You can display a string literal with the print() function:
Example
print("Hello")
print('Hello')
Assign String to a Variable Example
a = "Hello"
Assigning a string to a variable is done with the variable print(a)
name followed by an equal sign and the string:
Multiline Strings
You can assign a multiline string to a variable by using three double quotes Or three single
quotes:
Example
You can use three double quotes:
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
Strings are Arrays
Like many other popular programming languages, strings in Python are arrays of bytes
representing unicode characters.
However, Python does not have a character data type, a single character is simply a string
with a length of 1.
Square brackets can be used to access elements of the string.
Example
Get the character at position 1 (remember that the first character has the position 0):
a = "Hello, World!"
print(a[1])
String Methods
Python has a set of built-in methods that you can use on strings.
Example
The strip() method removes any whitespace from the beginning or the end
:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
String Methods
The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))
The split() method splits the string into substrings if it finds instances of the separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
Check String
To check if a certain phrase or character is present in a string, we can use the
keywords in or not in. Example
Check if the phrase "ain" is present in the following text:
txt = "The rain in Spain stays mainly in the plain"
x = "ain" in txt
print(x)
String Methods
Example
Check if the phrase "ain" is NOT present in the following text:
txt = "The rain in Spain stays mainly in the plain"
x = "ain" not in txt
print(x)
String Concatenation
To concatenate, or combine, two strings you can use the + operator.
Example Example
Merge variable a with variable b into variable c: To add a space between them, add a " ":
a = "Hello" a = "Hello"
b = "World" b = "World"
c=a+b c=a+""+b
print(c) print(c)
Write a Python program to check whether two strings are equal or not.
PROGRAM:
string1 = input("Enter first string: ")
string2 = input("Enter second string: ")
if string1 == string2:
print("\nBoth strings are equal to each other.")
print(string1,"==",string2)
else:
print("\nStrings are not equal.")
print(string1,"!=",string2)
OUTPUT:
Enter first string: CRESCENT
Enter second string: CRESCENT
Both strings are equal to each other.
CRESCENT == CRESCENT
Write a Python program to display reverse string.
PROGRAM:
# Python Program to Reverse String
string = input("Please enter your own String : ")
string2 = ‘ '
i = len(string) - 1
while(i >= 0):
string2 = string2 + string[i]
i=i-1
print("\nThe Original String = ", string)
print("The Reversed String = ", string2)
OUTPUT:
Please enter your own String : Python
The Original String = Python
The Reversed String = nohtyP
Python Built-in String Methods
Python Built-in String Methods
Python Built-in String Methods
Formatting Operator
%s - String (or any object with a string representation, like numbers)
%d – Integers
%f - Floating point numbers
%.<number of digits>f - Floating point numbers with a fixed amount of digits to the right
of the dot.
%x/%X - Integers in hex representation (lowercase/uppercase)
Control codes within strings.
The characters that can appear within strings include letters of the alphabet
(A-Z, a-z), digits (0-9), punctuation (., :, ,, etc.), and other printable symbols
(#, &, %, etc.).
In addition to these “normal” characters, we may embed special characters
known as control codes.
Control codes control the way text is rendered in a console window or paper
printer.
The backslash symbol (\) signifies that the character that follows it is a
control code, not a literal character.
The string ’\n’ thus contains a single control code. The backslash is known as
the escape symbol, and in this case we say the n symbol is escaped.
The \n control code represents the newline control code which moves the
text cursor down to the next line in the console window. Other control codes
include \t for tab, \f for a form feed (or page eject) on a printer, \b for
backspace, and \a for alert (or bell)
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
Control codes within strings Example Program
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
BOOLEAN EXPRESSION & OPERATORS
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
Boolean Expressions
• Arithmetic expressions evaluate to numeric
values; a Boolean expression, sometimes called
a predicate, may have only one of two possible
values: false or true.
• The simplest Boolean expressions in Python are
True and False.
Boolean Expressions
Example : Boolean Expressions
EXPRESSIONS AND ARITHMETIC
3.1 Expressions
A literal value like 34 and a variable like x are examples of a simple expressions. Values
and variables can be combined with operators to form more complex expressions.
sum = value1 + value2;
This is an assignment statement because is contains the assignment operator (=).
The variable sum appears to the left of the assignment operator, so sum will receive a
value when this statement executes. To the right of the assignment operator is an
arithmetic expression involving two variables and
x = 10, y = 10
1. x+y
If x and y are numbers
• 10 + 10 = 20
If x and y are string
• 10 + 10 = 1010
2. x-y
If x and y are numbers
• 10 - 10 = 0
3. x*y
If x and y are numbers
• 10 * 10 = 100
If x is string and y is number
• 10101010101010101010
If x is number and y is string
• 10101010101010101010
4. x/y
If x and y are numbers
• 10 /10 = 1
5. x // y
If x and y are numbers
• 10 // 10 = 1
6. x % y
If x and y are numbers
• 10 % 10 = 1
7. x ** y
If x and y are numbers
• 10 ** 10 = 10 10 =
10000000000
Arithmetic operators in Python
Operator Meaning Example
x+y
+ Add two operands or unary plus
+2
x-y
- Subtract right operand from the left or unary minus
-2
* Multiply two operands x*y
Divide left operand by the right one (always results into
/ x/y
float)
Modulus - remainder of the division of left operand by the
% x % y (remainder of x/y)
right
Floor division - division that results into whole number
// x // y
adjusted to the left in the number line
** Exponent - left operand raised to the power of right x**y (x to the power y)
Example #1: Arithmetic operators in Python
When you run the program, the output will be:
ADDITION, SUBTRACTION, MULTIPLICATION AND DIVISION
1. Write a program for addition, subtraction, multiplication and division of two numbers
ALGORITHM:
STEP 1: Display choice of operation in screen, “Choice 1: Add, 2: Sub, 3: Div, 4: Mul, 5: Quit “.
STEP 2: Receive input choice from the user.
STEP 3: Convert the input to integer (n = int (n1)).
STEP 4: If choice of option is 1 then receive input for A and B, Initiate operation c = A + B.
STEP 5: If choice of option is 2 then receive input for A and B, Initiate operation c = A - B.
STEP 6: If choice of option is 3 then receive input for A and B, Initiate operation c = A / B.
STEP 7: If choice of option is 4 then receive input for A and B, Initiate operation c = A * B.
PROGRAM:
print ("Choice 1: Add, 2: Sub, 3: Div, 4: Mul, 5: Quit") elif (n == 3):
n1 = input("Enter the choice of operation :") print (" You have chosen division Option :")
n = int(n1) a1 = input(" Enter the value for A :")
if (n == 1): b1 = input(" Enter the value for B :")
print (" You have chosen addition Option :") a = int(a1)
a1 = input(" Enter the value for A :") b = int(b1)
b1 = input(" Enter the value for B :") c=a/b
a = int(a1) print ("The Result",a,"/",b,"=",c)
b = int(b1) elif (n == 4):
c=a+b print (" You have chosen multiplication Option :")
print ("The Result",a,"+",b,"=",c) a1 = input (" Enter the value for A :")
elif (n == 2): b1 = input (" Enter the value for B :")
print (" You have chosen subtraction Option :") a = int (a1)
a1 = input(" Enter the value for A :") b = int (b1)
b1 = input(" Enter the value for B :") c=a*b
a = int(a1) print ("The Result”, a,"*", b,"=",c)
b = int(b1) elif (n==5):
c=a-b print (“You have given a wrong option”, n)
print ("The Result",a,"-",b,"=",c) exit ()
SAMPLE OUTPUT:
If option 1 -> Then Addition
C = A + B --> C = 5 + 5 --> C = 10.
If option 2 -> Then Subtraction
C = A - B --> C = 5 - 2 --> C = 03.
If option 3 -> Then Division
C = A / B --> C = 6 / 2 --> C = 03.
If option 4 -> Then Multiplications
C = A * B --> C = 5 * 3 --> C = 15.
If option 5 -> You have given a wrong option
Exit.
Python Operators
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:
•Arithmetic operators
•Assignment operators
•Comparison operators
•Logical operators
•Identity operators
•Membership operators
•Bitwise operators
FIZZ BUZZ PROGRAM
3. Write a program to incorporate FIZZ for any number divisible by 3 and Buzz for any
number divisible for 5 and FIZZBUZZ for any number divisible by 3 and 5 as well.
ALGORITHM:
STEP 1: Print “FizzBuzz Program”
STEP 2: prompt for user input for value N1
STEP 3: Convert the received value N1 to integer value N
STEP 4: Create a loop which will execute from 0 to N+1 times.
If I modules 3 and I modules 5 is zero then
Print I value + “= FIZZBUZZ”
If I modules 3 is zero then
Print I value + “= FIZZ”
If I modules 5 is zero then
Print I value + “= Buzz”
else
Print I Value
PROGRAM: OUTPUT:
print ("Fizz Buzz Program :") FizzBuzz Program
n1 = input("Enter the number : ") Enter the number: 15
0
n = int(n1) 1
i=0 2
3 = FIZZ
for i in range (n+1): 4
if (i % 3 == 0 and i % 5 == 0): 5 = BUZZ
6
print (str(i) + "= Fizz Buzz") 7
elif (i % 3 == 0): 8
9 = FIZZ
print (str(i) + "= Fizz ") 10 = BUZZ
elif (i % 5 == 0): 11
12 = FIZZ
print (str(i) + "= Buzz ") 13
else: 14
15 = FIZZBUZZ
print(i)
LIST & ITS OPERATIONS, TUPLES & ITS OPERATIONS,
DICTIONARIES & ITS OPERATIONS
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
Python Lists
Python List- Word Doc -- Click Here
List Programs - Click Here
Python Tuples
Tuple
A tuple is a collection which is
ordered and unchangeable. In Python
tuples are written with round
brackets.
Access Tuple Items
You can access tuple items by referring to
the index number, inside square brackets:
Python Tuples Python List VS Array VS Tuple
Array: An array is a collection of items stored at contiguous memory locations. The idea is to store multiple
items of the same type together. This makes it easier to calculate the position of each element by simply
adding an offset to a base value, i.e., the memory location of the first element of the array (generally
denoted by the name of the array). The following are the main characteristics of an Array:
An array is an ordered collection of the similar data types.
An array is mutable.
An array can be accessed by using its index number.
List: A list is of an ordered collection data type that is mutable which means it can be easily modified and we
can change its data values and a list can be indexed, sliced, and changed and each element can be accessed
using its index value in the list. The following are the main characteristics of a List:
The list is an ordered collection of data types.
The list is mutable.
List are dynamic and can contain objects of different data types.
List elements can be accessed by index number.
Tuple: A tuple is an ordered and an immutable data type which means we cannot change its values and
tuples are written in round brackets. We can access tuple by referring to the index number inside the square
brackets. The following are the main characteristics of a Tuple:
Tuples are immutable and can store any type of data type.
it is defined using ().
it cannot be changed or replaced as it is an immutable data type.
Python Tuples
Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to
the second last item etc.
Python Tuples
Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the
range.
When specifying a range, the return value will be a new tuple with the specified
items.
Note: The search will start at index 2 (included) and end at index 5 (not included).
Python Tuples
Range of Negative Indexes
Specify negative indexes if you want to start the search from the end of the tuple:
Change Tuple Values
Once a tuple is created, you cannot change its values.
Tuples are unchangeable, or immutable as it also is
called.
But there is a workaround. You can convert the tuple
into a list, change the list, and convert the list back
into a tuple.
Python Tuples
Loop Through a Tuple
You can loop through the tuple items by
using a for loop.
Check if Item Exists
To determine if a specified item is present in a
tuple use the in keyword:
Tuple Length
To determine how many items a tuple has, use
the len() method:
Python Tuples
Python Tuples
Python Tuples
Dictionary
Dictionary
Dictionary
Dictionary
Dictionary
Dictionary
Dictionary
Dictionary
Dictionary
Dictionary
Dictionary
Dictionary
Dictionary
Dictionary
Dictionary
Dictionary
Dictionary
Dictionary
Dictionary
Dictionary
SET
Set is collection just like list or dictionary but it is unordered and
no duplicate entries are present.
Example:
animals = ( “Lion” , “Monkey” , “Snake”’ , “Fox” )
print(animals)
ARRAYS
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
INPUT-OUTPUT
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
User Input
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
User Input- Example
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
eval()
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
The eval function: eval()
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
Output : Implementation of eval() Output : Implementation of eval()
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
CONDITIONS STATEMENTS: IF, IF-ELSE, IF-ELIF-ELSE –
LOOPING STATEMENTS: WHILE, FOR
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick
Simple if statement & if/else.
• if statement allows code to be optionally
executed
Simple if statement(flowchart & Syntax)
Simple if statement
• Python requires the block to be indented. If the block contains just one
statement, some programmers will place it on the same line as the if;
for example, the following if statement that optionally assigns y
if x < 10:
y=x
could be written as
if x < 10: y = x
but may not be written as
if x < 10:
y=x
• because the lack of indentation hides the fact that the assignment
statement is optionally executed.
• Indentation is how Python determines which statements make up a
block.
Using spaces and tabs in python editor
• It is important not to mix spaces and tabs when indenting
statements in a block.
• In many editors you cannot visually distinguish between a tab
and a sequence of spaces.
• The number of spaces equivalent to the spacing of a tab differs
from one editor to another.
• Most programming editors have a setting to substitute a
specified number of spaces for each tab character.
• For Python development you should use this feature.
• It is best to eliminate all tabs within your Python source code
• How many spaces should you indent?
• Python requires at least one, some programmers consistently
use two, four is the most popular number, but some prefer a
more dramatic display and use eight.
• A four space indentation for a block is the recommended
Python style.
If with multiple statement
The if/else Statement
The if statement has an optional else clause that is
executed only if the Boolean condition is false.
if else statement(flowchart & Syntax)
if & else (compare & Contrast)
Nested Conditionals
• The statements in the block of the if or the else may be any
Python statements, including other if/else statements.
•These nested if statements can be used to develop arbitrarily
complex control flow logic.
Nested Conditionals(using and logic)
Nested Conditionals(using 2 if and2 else)
Multi-way Decision Statements
Need of elif statement
Program with elif statement
Conditional Expressions
Example program for conditional expression
A Simple with if and else condition
Above program rewritten using conditional expression
Iteration
• Iteration repeats the execution of a sequence of code.
• Iteration is useful for solving many programming problems.
• Iteration and conditional execution form the basis for algorithm
construction.
• The process of executing the same section of code over and over
is known as iteration, or looping.
• Python has two different statements, while and for, that enable
iteration.
Python Program with ‘while’ statement
.
While statement flow and syntax
Example program
Definite Loop vs Indefinite Loop
Indefinite loop
For statement
range declaration in for loop
Example Program with range
exploration
Nested Loops
Nested Loops
Abnormal Loop Termination
• Normally, a while statement executes until its condition
becomes false. This condition is checked only at the ”top” of the
loop, so the loop is not immediately exited if the condition
becomes false due to activity in the middle of the body.
• Ordinarily this behavior is not a problem because the intention
is to execute all the statements within the body as an indivisible
unit.
• Sometimes, however, it is desirable to immediately exit the
body or recheck the condition from the middle of the loop
instead. Python provides the break and continue statements to
give programmers more flexibility designing the control logic of
loops.
Abnormal Looping-Break Statement
Abnormal Looping-continue Statement
Infinite Looping
Example program for infinite loop
CAC
CAD 2216 – UNITProgramming
7121 -Python II Course Instructor : Dr.A.Abdul Azeez Khan & Dr. K.Javubar Sathick