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

Python Course

This document explains loops in Python, specifically focusing on while loops, which repeat code as long as a condition is true. It covers the syntax, important rules such as avoiding infinite loops, and the use of break and continue statements to control loop execution. Additionally, it provides practice exercises to reinforce the concepts discussed.

Uploaded by

zraibyl
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 views3 pages

Python Course

This document explains loops in Python, specifically focusing on while loops, which repeat code as long as a condition is true. It covers the syntax, important rules such as avoiding infinite loops, and the use of break and continue statements to control loop execution. Additionally, it provides practice exercises to reinforce the concepts discussed.

Uploaded by

zraibyl
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

While Loops

1. What is a Loop?

A loop is used to repeat instructions many times in Python. Instead of writing


the same code again and again, we use loops.

2. While Loop

A while loop repeats code as long as a condition is true.

Syntax:

while condition:
instructions

Example 1: Counting from 1 to 5

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

3. Important Rule

If you forget to increase the number, the loop will run forever (infinite loop).

4. Break Statement

Used to stop the loop early.

Example:
i=1
while i <= 10:
print(i)
if i == 5:
break
i += 1

5. Continue Statement

Skips the current step of the loop.


Example:
i=0
while i < 5:
i += 1
if i == 3:
continue
print(i)

6. Practice Exercises
1. 1. Create a variable i with the value 0
2. Write a while loop that runs as long as iis less than 6
3. Inside the loop: increment i by 1
4. If i equals 3, use continue to skip that iteration
5. Print i
Solution
CodeSolution
# Create the i variable
i=0

# While loop: print 1-5, skip 3 with continue


while i < 6:
i += 1
if i == 3:
continue
print(i)

You might also like