A while
loop in Python is used to repeat a block of code as long as a condition is true. Use it when the number of iterations is not known in advance.
Python में while
loop का उपयोग तब किया जाता है जब किसी condition के true रहने तक कोड को बार-बार चलाना हो। इसका उपयोग तब होता है जब loop कितनी बार चलेगा यह पहले से तय नहीं हो।
i = 1
while i <= 5:
print(i)
i += 1
Output:
1 2 3 4 5
i = 2
while i <= 10:
print(i)
i += 2
Output:
2 4 6 8 10
i = 5
while i >= 1:
print(i)
i -= 1
Output:
5 4 3 2 1
i = 1
sum = 0
while i <= 10:
sum += i
i += 1
print("Sum:", sum)
Output:
Sum: 55
i = 1
while i <= 5:
print(i*i)
i += 1
Output:
1 4 9 16 25
i = 1
while i <= 10:
print("3 x", i, "=", 3*i)
i += 1
Output:
3 x 1 = 3 3 x 2 = 6 ... 3 x 10 = 30
user_input = ""
while user_input != "exit":
user_input = input("Enter something (type 'exit' to stop): ")
Output:
Enter something (type 'exit' to stop): hello Enter something (type 'exit' to stop): world Enter something (type 'exit' to stop): exit
n = 1234
rev = 0
while n != 0:
digit = n % 10
rev = rev * 10 + digit
n //= 10
print("Reversed:", rev)
Output:
Reversed: 4321
n = 5
fact = 1
while n > 0:
fact *= n
n -= 1
print("Factorial:", fact)
Output:
Factorial: 120
s = "Python"
i = 0
while i < len(s):
print(s[i])
i += 1
Output:
P y t h o n