fb pixel

Introduction to Python

  • Profound Academy

    • Status
      • 1
        Input and Output
      • 2
        Variables and Integer Arithmetic
      • 3
        Conditional Operators
      • 4
        Advanced Conditions - Nesting
      • 5
        Types and Variables
      • 6
        Strings
      • 7
        Lists
      • 8
        For Loops
      • 9
        While Loops
      • 10
        continue, break, while...else
      • 11
        String and List methods
      • 12
        Nested Loops
      • 13
        List Comprehension
      • 14
        Tuples and Sets
      • 15
        dict
      • 16
        Functions
      • 17
        Functions 2
      • 18
        Lambda and higher-order functions
      • 19
        Files

  • while loops

    Python has two types of loops - for loops and while loops. If for loops iterate over a list (iterable) element by element, a while loop, on the other hand, repeats statements inside its body as long as the condition in the while statement is satisfied. In that sense, it’s very similar to an if statement. It executes the statements inside the while loop in case the condition is satisfied:
    i = 0
    while i < 5:
    	print('Current i is:', i)
    	i += 1
    print('Done')
    Current i is: 0
    Current i is: 1
    Current i is: 2
    Current i is: 3
    Current i is: 4
    Done
    The program on the left will print this output
    1. Initially, i is assigned to be 0i = 0.

    1. Then, the program checks if i < 5 and as 0 < 5, it steps inside the while body
    1. The program prints Current i is: 0
    1. The variable i increases its value by 1 turning into i = 1

    1. Then, the program jumps again to the condition and checks if i < 5. As 1 < 5 ⇒ it steps inside the while body
    1. The program prints Current i is: 1
    1. The variable i increases its value by 1 turning into i = 2

    1. The program checks if i < 5. 2 < 5 ⇒ steps inside the while body
    1. The program prints Current i is: 2
    1. The variable i increases its value by 1 turning into i = 3

    1. The program checks if i < 5. 3 < 5 ⇒ steps inside the while body
    1. The program prints Current i is: 3
    1. The variable i increases its value by 1 turning into i = 4

    1. The program checks if i < 5. 4 < 5 ⇒ steps inside the while body
    1. The program prints Current i is: 4
    1. The variable i increases its value by 1 turning into i = 5

    1. The program checks if i < 5. 5 = 5 ⇒ The program steps outside the while loop and prints Done
     

    Challenge

    Given a positive integer n. Print the value of n as long as it’s greater than 0 and divide it by 2 (take only the whole part).
    Input
    Output
    100
    100 50 25 12 6 3 1
    5
    5 2 1
     
    To check your solution you need to sign in
    Sign in to continue