B.Tech Students: Apply for Live Programming Internship C, C++, Java, Python ,Web page Designing, PHP Python While Loops with Examples | LiveCodeProgramming
Python Installation First Python Program Control Flow if...else nested if else match-case logical-operators for loops while loops break / continue Functions Defining Functions Function Arguments Function return value Lambda Function Recursion Exception Handling Exception Handling Try Except Else and Finally Raise Exception Custom Exceptions File Handling File in python Read File Write File Append File Delete File Exception Handling

Python While Loop

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 कितनी बार चलेगा यह पहले से तय नहीं हो।

  1. Print numbers from 1 to 5
    i = 1
    while i <= 5:
        print(i)
        i += 1
    Output:
    1
    2
    3
    4
    5
  2. Print even numbers up to 10
    i = 2
    while i <= 10:
        print(i)
        i += 2
    Output:
    2
    4
    6
    8
    10
  3. Print countdown from 5 to 1
    i = 5
    while i >= 1:
        print(i)
        i -= 1
    Output:
    5
    4
    3
    2
    1
  4. Sum of numbers from 1 to 10
    i = 1
    sum = 0
    while i <= 10:
        sum += i
        i += 1
    print("Sum:", sum)
    Output:
    Sum: 55
  5. Print square of numbers 1 to 5
    i = 1
    while i <= 5:
        print(i*i)
        i += 1
    Output:
    1
    4
    9
    16
    25
  6. Print table of 3
    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
  7. Take input until user types 'exit'
    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
  8. Reverse a number
    n = 1234
    rev = 0
    while n != 0:
        digit = n % 10
        rev = rev * 10 + digit
        n //= 10
    print("Reversed:", rev)
    Output:
    Reversed: 4321
  9. Factorial of a number (e.g., 5)
    n = 5
    fact = 1
    while n > 0:
        fact *= n
        n -= 1
    print("Factorial:", fact)
    Output:
    Factorial: 120
  10. Print characters of a string using while
    s = "Python"
    i = 0
    while i < len(s):
        print(s[i])
        i += 1
    Output:
    P
    y
    t
    h
    o
    n