0% found this document useful (0 votes)
1 views6 pages

Python Chapter (4)Looping

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views6 pages

Python Chapter (4)Looping

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Looping

A loop in Python is a type of control structure that allows a program to repeat a certain block of code a certain
number of times or while a certain condition is true.

Python supports two types of loops: the for loop and the while loop.

for loop

The for loop is used to iterate over a sequence of values and execute a block of code for each value in the
sequence.

(Syntax)

for variableName in (start,end,step):

Statement

Example (1)

for i in range(1,6,1):
print("Hello",i)

Example (2)

str="Hello"
for i in range(0,5,1):
print(str[i])

Example (3)

str="Disney"
newStr=""
for c in str:
newStr+=c+" "
print(newStr)
Example (4)

text="Scoppy"
strNum=""
for i in range(5,-1,-1):
strNum+=text[i]+"\t"
print(strNum)

While loop

The while loop is used to execute a block of code repeatedly until the condition becomes false.

(Syntax)

start
while(end/condition):
Statement
Step(inc/dec)
Example (5)

i=1
while(i<=5):
print(i)
i=i+1

Example (6)

i=10
while(i>=1):
print(i)
i-=2
Example (7) Python Collection(Arrays)

There are four collection data types in the Python programming language:

• List
• Tuple
• Set
• Dictionary

List

List is a collection which is ordered and changeable. Allows duplicate members. Access the list items by
referring to the index number. Python has a set of built-in methods that you can use on lists.

Method Description
append(value) Adds an element at the end of the list
len() To determine how many items have in list
insert(position, value) Adds an element at the specified position
count(value) Returns the number of elements with the specified value
index(value) Returns the index of the first element with the specified value
remove(value) Removes the element with the specified value
pop(position) Removes the element at the specified position
reverse() Reverse the order of the list
sort() Sorts the list

Example (1)

lst=[10,20,30,40,50,10]
print(lst)
print("Length=",len(lst))
print("Count 10=",lst.count(10))
print("Index 10=",lst.index(10))
lst.append(100)
lst.insert(2,1000)
print("After Append ",lst)
Example (2)

lst2=list(range(1,11))
print(lst2)
print("Sum=",sum(lst2))
lst2.insert(1,200)
print("Now Lst2=",lst2)
Example (3)
extend() -This function adds the elements of one list to the end of another list. It returns the extended list.
lstOne=[1,2,3]
lstTwo=[100,200]
lstOne.extend(lstTwo)
print("lstOne=",lstOne)
lstOne.remove(3)
print("After Remove lstOne=",lstOne)
print("lstOne pop",lstOne.pop())
print("lstOne pop",lstOne.pop())
print("lstOne pop",lstOne.pop(0))
print("lstOne=",lstOne)

Example (4)

lst=[10,-2,40,100,12]
lst.reverse()
print("Reverse lst=",lst)
lst.sort()
print(lst)
lst.sort(reverse=True)
print(lst)

Example (5)

The id() function in Python is used to return a unique id for an object. The id() function returns an identity of an
object. The id() function is useful to determine the type of an object and also to compare two objects.

lst2=lst[:]
lst.append(10245)
print(lst2)
print("ID=",id(lst))
print("ID=",id(lst2))

Tuple

A tuple is a collection which is ordered and unchangeable. Cannot add items after create the tuple and
remove items in a tuple. So, assign the items in a tuple while the tuple creation. In Python tuples are written
with round brackets.

Method Description
len() To determine how many items have in tuple

Example (6)

print("Tuple")
myTuple="John",
print("type=",type(myTuple))
print(myTuple)
print(myTuple[0])
student=(("John",20),("Su",15))
print(student)
print(student[0])

Example (7)

myTuple="John",20
print(myTuple)
print("Name=",myTuple[0])
print("Age=",myTuple[1])

Example (8)

students=(("Rose",16),("Susan",15))
print(students)
print(students[0])
print(students[1])

Set

A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.Once a
set is created, cannot change its items, but can add and remove items. Note: Sets are unordered, so the items
will appear in a random order.

Method Description
add(value) To add one item to a set
del() Delete the set
remove(value) To remove an item in a set (Note : If the item to remove does not exist, will raise an
error)

Example (9)

centre={"psd","mng","tgz","hld1","hld2"}
print(centre)
print(sorted(centre),len(centre))
del(centre)
print(centre)
Example (10)

numbers = {21, 34, 54, 12}


print('Initial Set:',numbers)
numbers.add(32)
print('Updated Set:', numbers)

Example (11)

programming = {'PHP', 'Java', 'Python'}


print('Initial Set:', programming)
removedValue = programming.remove('Java')
print('Set after remove():', programming)
programming.update(['VB','C','Ruby'])
print('Set after update():', programming)

Dictionary
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written
with curly brackets, and they have keys and values. Adding an item to the dictionary is done by using a new
index key and assigning a value to it. Can access the items of a dictionary by referring to its key name.

Example (12)

mark1={"Myan":40,
"Eng":60,
"Math":72}

mark2={"Myan":80,
"Eng":70,
"Math":62}
print(mark1)
print(mark2)

Exercise(1)

Write a Python program to display the first and last colors from the following list.

#left to right -> start 0

#right to left -> start -1

i=int(input("Enter Number"))
while(i != 0):
print(i*i)
i=int(input("Enter Number"))

Break & Continue


Example (8)

Example (9)

Nested Loop

for( outer loop )row / col


for( inner loop )col / row

for 1 to 5
for 1 to 5
Example (10)

for i in range(1,6):
str1=""
for j in range(1,6):
str1+="* "
print(str1)
Exercise

Write a program to use the loop to find the factorial of a given number. eg.(5! => num=5)

You might also like