For Loop → mainly used for sequential traversal (going through elements one by one)
string = "hello"
# in → membership operator (checks presence / iterates)
for var in string:
print(var)output
h
e
l
l
oSyntax
# ┌────────── sequence (string, list, range)
# │
for variable in sequence:
print(variable)If you want to check whether something exists in a sequence:
string = "hello"
if 'o' in string:
print("o exists in the string")
if 'x' in string:
print("x exists in the string")output
o exists in the stringSequence = ordered collection
Examples: string, list, range
- range()
Used to generate numbers
# ┌──────── max value (not included)
# │
for i in range(5):
print(i)output
0
1
2
3
4for i in range(5):
print(i + 1)output
1
2
3
4
5Note
range(5)→ starts from 0 and ends at 4 (5 not included)
- count characters
word = "artificial Intelligence"
count = 0
for ch in word:
if ch == 'i':
count += 1
print("count of i =", count)output
count of i = 3Note
forloop works with sequencesinis used for iteration and checking- Always use
:and proper indentation Here’s your note cleaned, fixed, and expanded (keeping your style but making it clearer and more complete):
Question
Write a program in Python to count vowels in a given string
word = "artificial"
count = 0
for ch in word:
if ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u':
count += 1
print("Total vowels =", count)output
Total vowels = 5Note
- Vowels →
a, e, i, o, u- Loop checks each character one by one