Introduction to Python

for … else

Just like while loops, for loops can have else blocks that are executed when the for loop completes without encountering a breakstatement. The syntax for for…else is very similar to the syntax of while…else.
Let’s consider this program that checks whether the given number is prime or not. A number is prime if it is greater than 1 and cannot be divided by a number other than 1 and itself.
# Program to check if a number is prime or not
num = int(input('Enter a number: '))
for i in range(2, num):
    if num % i == 0:
        print(f'{num} is not a prime number')
    print(f'{num} is a prime number')
The program will check every number within the range [2, num) to see if it is a factor of num. If it encounters such a number, it will print {num} is not a prime number and exit the loop. Since a break statement was executed, the code in the else block will not be executed. However, if no number in the range is a factor of num, the code in the else statement will be executed, and the program will print {num} is a prime number.


The first line of the input contains n, followed by n lines of integer numbers. Your task is to print The first even number in the list is {num} or There is no even number in the list if none of the input numbers are even. Try to use a for loop with an else block to solve this challenge!
5 -1 3 4 -3 6
The first even number in the list is 4
4 1 3 -7 17
There is no even number in the list


Time limit: 1 seconds

Memory limit: 512 MB

Output limit: 1 MB

To check your solution you need to sign in
Sign in to continue