Previously we have looked at the conditional statements in Python, In this article we will examine a problem related to even or odd concept. In this particular case of two examples imagine a game where you and your opponent are playing, and we are given a number of points. In the first example we have 4 coins and in the next 5 coins. The game is turn-based between you and your opponent and every turn either both have to pick up a coin. You make the first turn and have to pick up a coin, the person who picks up the last coin is the winner.
In the first example of 4 coins, by logic we can determine that the opponent would be the winner since we are required to pick 1 coin per turn, whereas the opponent would be the one last to pick up the final coin and hence the winner. In the second example it would be the reverse. If we look even further at the game logic we can establish that with an even number of coins it would be a win for the opponent but with an odd number of coins it would be a win for you.
Implementation of Even-Odd problem in Python
Let us form a program which can determine who the winner of the game would be based upon the number of coins present from the start of the play.
#Python program to determine the winner in Coin Game n=int(input("Enter the number of coins: ")) print("The winner of the game is:") if n%2==0: print("Opponent would be the winner") else: print("You would be the winner!")
Output: Enter the number of coins: 7 The winner of the game is: You would be the winner! Enter the number of coins: 4 The winner of the game is: Opponent would be the winner
We see that the program is accurately able to pre-determine the winner of the game by the first determining if the number of coins is even or odd and then displaying the result. In our next article we will look at the largest of three program in Python and it’s logic.