Python Fundamentals
Notes Part-1 ----- > PYTHON
Notes Part-2 ------> Input and Output Statements
Notes Part-3 ------> Conditional Statements
Notes Part-4 -------> Operators in python
Notes Part-5 ------> Datatypes in python
Notes Part -6.1 ------> Lists
Notes Part- 6.2 -----> Dictionary
Reference Notes on For Loop and While Loop to read:
1. For Loop:
- A
for
loop is typically used when the number of iterations is known in advance. - It is structured for cases where you need to iterate over a range, a sequence, or a collection (like a list or a string).
Syntax:
for i in range(start, stop, step):
# Loop body
Example with a
for
loop:n = int(input("enter number"))
s = 0
for i in range(1, n+1):
s = s + i
print("sum =", s)
This version iterates over a known range, starting from
1
to n
. When n = 5
, the output will be:
sum = 1
sum = 3
sum = 6
sum = 10
sum = 15
2. While Loop:
- A
while
loop is generally used when the number of iterations is unknown, and the loop continues based on a condition. - It keeps running until the condition becomes
False
.
Syntax:
while condition:
# Loop body
Example with a
while
loop:n = int(input("enter number"))
s = 0
i = 1
while i <= n:
s = s + i
print("sum =", s)
i += 1 # Increment the counter to avoid infinite loop
The output will be the same as the for
loop for n = 5
.
Key Differences Between for
and while
Loops:
For Loop:
- Used when the number of iterations is known beforehand (e.g., iterating through a sequence, a fixed range).
- Easier to read when working with definite ranges or collections.
While Loop:
- Used when the number of iterations is unknown, and it depends on some condition.
- Can be more flexible for dynamic conditions, where the loop may run indefinitely or stop based on a variable condition.
When to Use Each:
Use a
for
loop:- When you have a clear start and end point.
- When you are iterating over a collection, sequence, or range.
- Example: Iterating over numbers 1 to 5, iterating over elements in a list.
Use a
while
loop:- When you don't know how many iterations you need in advance, but you know the condition that will stop the loop.
- When you need more control over how and when the loop should stop.
- Example: Reading a file until the end, looping until the user inputs a specific value.
Comments
Post a Comment