An even number is that which can be exactly divided by 2 (without getting result in decimal form). For example 2,4,10,8. An odd number on the other hand is a number which cannot be exactly divided by 2. For example 1,3,5,7,11
In this example we will check whether a number entered by a user is even or odd.
To understand this example, you must have the knowledge of –
- conditional operators
- conditional statements
- int function and input function
- modulus operator
mynum = int(input("Enter a number")) if mynum % 2 == 0: print("The number is even") else: print("The number is odd")
Enter a number7
The number is odd.
- First we are asking a number from the user through the input function and converting the number to integer form by int function. The number that the user enters would be stored inside the variable named ‘mynum’.
- Next we have written if, else conditional statements. In the if statement, we are checking whether the number is divisible fully by 2 or not. If the condition is true, i.e., if it is divisible by 2, the if block would execute and a message would be displayed saying “The number is even”. We are checking the number to be even by using the modulus operator. The modulus operator returns the remainder, for example 5 % 2 would return 1. If the remainder is 1, the number would be odd, and the number would be even if the remainder is 0. This way we can check whether the number is even or not.
- If the condition of if statement is false, the else block would be executed and display a message saying “The number is odd”.
Note : Only one block out of ‘if and else’ executes at a time. We write condition only inside the if block. The else block only executes when the condition of if statement becomes false.