0% found this document useful (0 votes)
2 views7 pages

? Python Loops

The document provides a comprehensive overview of Python loops, including for loops and while loops, detailing their syntax, usage, and control statements like break and continue. It also covers the properties and methods of Python lists, including how to create, access, modify, and manipulate lists. Additionally, it explains nested loops, infinite loops, and various list methods such as append, insert, and sort.

Uploaded by

hjnzmv96fv
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)
2 views7 pages

? Python Loops

The document provides a comprehensive overview of Python loops, including for loops and while loops, detailing their syntax, usage, and control statements like break and continue. It also covers the properties and methods of Python lists, including how to create, access, modify, and manipulate lists. Additionally, it explains nested loops, infinite loops, and various list methods such as append, insert, and sort.

Uploaded by

hjnzmv96fv
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

3.

Python For Loops

📘 Python Loops – Complete Reviewer  A for loop is used for iterating over a
sequence
1. What Are Loops? (list, tuple, dictionary, set, string).
 Works more like an iterator method in
 Most useful and powerful structure object-oriented languages rather than “for”
 Allows the repetition of instructions or in other language.
statements in the loop body  Executes a set of statements once for each
 Loop body → instructions/statements that item in a sequence.
are repeated  for loop does not require an indexing
 Loop-exit condition → the condition tested variable to set beforehand.
before each repetition  Even strings are iterable objects, they
contain a sequence of characters
 for x in "banana":
 print(x)
Types of Python Loops 

1. while loop There are four collection data types in the Python
2. for loop programming language: array
o in
o range List- is a collection which is ordered and
changeable. Allows duplicate members.

Tuple -is a collection which is ordered and


2. Python While Loops unchangeable. Allows duplicate members.

Syntax Set - is a collection which is unordered,


unchangeable*, and unindexed. No duplicate
while condition: (it is either true or false) members.
statement1 # executes if true
statement2 # executes if false Dictionary -is a collection which is ordered** and
changeable. No duplicate members.
 The statements inside the while loop are
executed as long as the condition remains 4. The range() Function
true.
 Else Block (optional) Execute ONLY when  Used to loop through code a specified
while loop finishes normally (no break) number of times.
 Returns a sequence of numbers:
Example o starts at 0 by default
o increments by 1 by default
i=1 o ends at a specified number
while i < 6: (exclusive)
print(i)
i += 1 Example

✔️Remember to increment i, or else the loop will for x in range(6):


continue forever. print(x)

📌 range(6) gives 0 to 5, not 0 to 6.


 Moves control back to the loop's condition
and continues next iteration.
Specifying a Start Value (by adding parameter)
Example
for x in range(2, 6):
print(x) for x in 'python':
if x == 'h':
This prints 2 to 5. continue
print(x)
Specifying an Increment Value (start, stop, step)
for x in range(2, 30, 3):
print(x) C. Pass Statement

 A null operation; nothing happens.


More For Loop Examples  Useful when code will be written later.
 For loops cannot be empty, so use pass to
Example 1 avoid errors.

for a in range(10, 20): Example


print(a)
for x in [0, 1, 2]:
Example 2 pass

fruits = ['banana', 'apple', 'mango']


for index in range(len(fruits)): 6. Else in For Loop
print('Current fruit:', fruits[index])
 The else block runs when the loop is
finished or finishes normally without break
5. Control Statements in Loops
Example 1
A. Break Statement
for x in range(6):
 Forces immediate termination of a loop. print(x)
 Bypasses remaining code in the loop body. else:
 Program control resumes at next statement print("Finally finished!")
after the loop.
 Python break is used to terminate a loop Example 2 (with break)
instantly.
for x in range(6):
Example if x == 3:
break
for x in 'python': print(x)
if x == 'h': else:
break print("Finally finished!")
print(x)
📌 Note: The else block will NOT run if the loop is
stopped by a break.
B. Continue Statement
n = int(input("Number of times: ")
 Skips the current iteration. total = 0
for i in range(n + 1):
print(f"x = {i}") 🔹 What Is a List in Python?
total = total + i
print(f"sum is {total}")  The list is a type of data in Python used
to store multiple items in a single variable.
 It is an ordered and mutable collection of
comma-separated ( , ) items between square
7. Nested Loop brackets [ ].
 Lists are created using square brackets [ ].
 A loop inside another loop.  Negative indices are legal and very useful.
 The inner loop runs n times for each outer o Index -1 = last element in the list.
loop repetition.
 Total iterations = outer loop × inner loop.
 Useful for star/number patterns.
🔹 Properties of Python Lists
Example idea: using nested loops with range() to
print square patterns.  List items are ordered, changeable,
and allow duplicate values.
for i in range(2,8):  Note: Some list methods can change the
print("first kineme is", i) order, but in general the order
for j in range(1,11): will not change.
print(i*j, end=", ")

print("\n")
🔹 Creating a List in Python
for x in range(1,6):
for z in range(1, x+1): Example
print("*", end=" ")
#list of food
print(" ") food = ["cake", "burger", "fries"]
0,1,2,
x=1 3,-2,-1
while x <= 5: #empty list
y=1 empty_list = []
while y <= x:
print(y, end=" ") #return all the list value
y += 1 print(food)
x += 1 print(empty_list)
print(" ")

8. Infinite Loop 🔹 Accessing a List in Python

 A loop that will not terminate Syntax


 Happens when the condition is
always TRUE Name_of_list[index_number]

Example

📘 PYTHON LIST — COMPLETE REVIEWER numbers = [1, 2, 3, 4, 5]


food = ["cake", "burger", "fries"]

print(numbers[-1]) # last element


print(numbers[0]) # first element [Link](elmnt)
print(food[1]) # "burger"
elmnt = any type (string, number, object, etc.)

🔹 Changing a Value in a List Example

Syntax name = ['Joy', 'Efren']


place = ["Indang", "Trece", "Dasma"]
Name_of_list[index] = new_value
# add Eyren in list name
Example 1 [Link]("Eyren")
print(name)
food = ["cake", "burger", "fries"]
print(food) # combine list name and place
[Link](place)
#change index 0 print(name)
food[0] = "pizza"
print(food)
🔹 INSERT() METHOD
Example 2
 Inserts a value at a specified position.
name = ['Joy', 'Efren']  Can add an element at any location, not
print(name[0]) only at the end.

name[0] = "Eyren" Syntax


print(name[0])
[Link](location, value)
location- Required. Location of the element to be
🔹 Common List Methods (Description Table) inserted
value-Required. An element of any type (string,
Important List Methods number, object etc.) to be inserted

Method What It Does Example


append() Adds item to end
insert() Adds item at specific index name = ['Joy', 'Efren']
extend() Adds elements of another iterable
# insert Eyren at index 1
remove() Removes first matching element
[Link](1, "Eyren")
pop() Removes element by index (default last) print(name)
sort() Sorts list (ascending by default)
reverse() Reverses list order
count() Counts occurrences of a value 🔹 REMOVE() METHOD
index() Returns index of first occurrence
 Removes the first occurrence of a value.

🔹 APPEND() METHOD Syntax

 Appends an element to the end of the list. [Link](elmnt)


 List length increases by one.
Example
Syntax
name = ['Joy', 'Efren', 'Eyren', 'Joy'] place = ["Indang", "Trece", "Dasma"]

# remove Joy # ascending


[Link]("Joy") [Link]()
print(name) print(place)

# descending
🔹 POP() METHOD [Link](reverse=True)
print(place)
 Removes the element at a specified
position. # ascending again
 Default position = -1 (last item). [Link](reverse=False)
 Pos-number specifying the position of the print(place)
element you want to remove.
 default value is -1, which returns the last
item 🔹 REVERSE() METHOD

Syntax  Reverses the sorting order of list elements.

[Link](pos) Syntax

Example [Link]()

place = ["Indang", "Trece", "Dasma"]


name = ['Joy', 'Eyren Joy', 'Efren', 'Sugar'] 🔹 COUNT() METHOD

# delete last element  Returns number of elements matching


[Link]() a specific value.
print(place)
Syntax
# delete index 3 element
[Link](3) [Link](value)
print(name) food=['cake','burger','fries','burger']
place=['boracay','palawan','puerto']
# display deleted element [Link]('burger')
x = [Link](1) print(food1)
print(f'Deleted Element: {x}')

🔹 INDEX() METHOD
🔹 SORT() METHOD
 Returns the index of the first occurrence of
 Sorts the list in ascending order by
an element.
default=False.
 Raises ValueError if not found.
 Can sort descending using reverse=True.
Syntax
Syntax
[Link](element, start, end)
[Link](reverse=True|False)
Example
Example
vowels = ['a', 'e', 'i', 'o', 'u']
index = [Link]('e')
print("index position of e:", index)

index = [Link]('i')
print("index position of i:", index)

🔹 EXTEND() METHOD

 Adds all elements from an iterable to the


list.

Syntax

[Link](iterable)

Example

male = ['Efren', 'Jr']


female = ['Joy', 'Eyren']

[Link](female)
print(male)
print(male[3])

You might also like