A Collection of Code Snippets in as Many Programming Languages as Possible
This project is maintained by TheRenegadeCoder
Welcome to the Even Odd in Python page! Here, you'll find the source code for this program as well as a description of how the program works.
import sys
def even_odd(x):
return "Even" if x % 2 == 0 else "Odd"
def exit_with_error():
print('Usage: please input a number')
sys.exit(1)
def main(args):
try:
num = int(args[0])
print(even_odd(num))
except (IndexError, ValueError):
exit_with_error()
if __name__ == "__main__":
main(sys.argv[1:])
Even Odd in Python was written by:
This article was written by:
If you see anything you'd like to change or update, please consider contributing.
Let's look at the code in detail:
Here we have a function called even_odd
that returns "Even" if a number is even and "Odd" if it is odd. We are checking this using the modulus operator (%) which returns the remainder after division. The result after a modulo operation of an even integer will always be 0 while the result after a modulo operation of an odd integer will always be 1.
Ex.
If we want to run this program, we should probably download a copy of Hello World in Python. After that, we should make sure we have the latest Python interpreter. From there, we can simply run the following command in the terminal:
python even-odd.py <input>
With being any integer. For example
python even-odd.py 12
Alternatively, we can copy the solution into an online Python interpreter and hit run.