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
      • 7
      • 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
      • 16
      • 17
        Functions 2
      • 18
        Lambda and higher-order functions
      • 19

  • while ... else

    if statements can have else blocks that are executed in case the condition of the if statement was not met. Similar to if statements, while loops can have else blocks as well, which will be executed in case the condition of the while statement was not met.
    name = input()
    if name != 'Alice':
    	print('I don\'t know you')
    	print('Hi, Alice!')
    name = input()
    while name != 'Alice':
    	print('I don\'t know you')
    	name = input()
    	print('Hi, Alice!')
    The program with a while will prompt the user to enter their name as long as it’s not Alice. In case the name is finally Alice, the condition name != 'Alice' does not hold, and the program enters the else block where it prints Hi, Alice!.

    Couldn’t we just do that outside the while right before print('End!')?

    In this example, Yes! But while ... else comes in really handy when we’re dealing with break statements. In case we break from within the while loop, the else would not be executed as the condition was still holding when the program entered the loop. There were some discussions to name this while ... nobreak instead of while ... else.
    Imagine if we want to check if the number has the digit 5:
    n = 123409087542108
    while n != 0:
    	if n % 10 == 5:
    		print('The number contains a digit 5!')
    	n //= 10
    	print('The number does not have a digit 5')
    So, whenever the while loop breaks, the else statement will not get executed, therefore, the program will not print the second message if it has already found a digit 5.
    In case the while loop reaches the end and the condition does not hold any longer, the else block will get executed and the program will print The number does not have a digit 5.
    You can interpret the while ... else concept as while ... nobreak but write it with else in the programs.


    Given an integer in the input, your task is to find out if it contains either 3 or 7 in its digits. If it does, you should print The number contains a digit 3 or 7. If it doesn’t, then the program should print The number neither has a digit 3 nor a digit 7.
    The number neither has a digit 3 nor a digit 7
    The number contains a digit 3 or 7
    To check your solution you need to sign in
    Sign in to continue