- Syntax:
while condition: code
- Example: Print numbers from 1 to 10.
i = 1 while i <= 10: print(i) i += 1
- Example: Print numbers from 5 to 1.
i = 5 while i >= 1: print(i) i -= 1
- Example:
i = 1 while i <= 100: print(i) i += 1
- Example:
i = 100 while i >= 1: print(i) i -= 1
- Example:
n = int(input("Enter a number:")) i = 1 while i <= 10: print(n * i) i += 1
- Example:
num = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] idx = 0 while idx < len(num): print(num[idx]) idx += 1
- Example:
x = 9 num = (1, 4, 9, 16, 25, 36, 49, 64, 81, 100) i = 0 while i < len(num): if num[i] == x: print("Found") i += 1
- Break: Stops the loop.
i = 1 while i <= 5: print(i) if i == 3: break i += 1
- Continue: Skips the current iteration and continues to the next one.
i = 0 while i <= 5: if i == 3: i += 1 continue print(i) i += 1
-
Example with a list:
num = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] for val in num: print(val)
-
Example with a tuple:
tup = (1, 4, 9, 16, 25, 36, 49, 64, 81, 100) for num in tup: print(num)
-
Example with a string:
str = "noushad" for char in str: print(char)
- Generate a sequence of numbers:
seq = range(10) # range(stop) for i in seq: print(i)
- Example with start and stop:
for i in range(2, 10): # range(start, stop) print(i)
- Example with step:
for i in range(2, 10, 2): # range(start, stop, step) print(i)
- Example:
for i in range(2, 101, 2): print(i)
- Example:
for i in range(1, 101): print(i)
- Example:
for i in range(100, 0, -1): print(i)
- Example:
n = int(input("Enter a number:")) for i in range(1, 11): print(n * i)
- Used when you need to write a block of code but don't want to execute it yet.
for i in range(10): pass print("Some useful work")
- Example:
n = 5 sum = 0 for i in range(1, n + 1): sum += i print("Total sum is", sum)
- Example:
n = 5 fact = 1 for i in range(1, n + 1): fact *= i print("Factorial of", n, "is", fact)