Since you have edited your question, it appears you don't actually want random numbers, but instead you want the user to enter five numbers in a row.
You seem to want the user to enter all five numbers first, and then all the output to be displayed.
In order to accomplish this, first run the input
function five times using a for
loop, and add each input to a list, then use another for
loop to output whether each one is odd or even.
Here is the code:
# Create a list to store the five numbers
nums = []
# Fill the list with five inputs from the user
for _ in range(5):
nums.append(int(input()))
# Explanation of above line:
# - The `append` function adds a new item to a list
# - So this line gets input from the user,
# turns it into an integer,
# and adds it to the list
# Finally, output whether each number is odd or even
# Iterate over the `nums` list using a for loop
for num in nums:
# The code here will run one time for each item in the `nums` list
# Each time the code runs, the variable `num` will store the current item
# So we can do a test on `num` to see if each item is odd or even
if (num % 2) == 0:
print(num, "is even")
else:
print(num, "is odd")
Above is one way to do your task, however it does not follow best practices for the following reasons:
- The code is not split up into functions so it is not as clear what each part accomplishes
- The main code should be under an
if __name__ == "__main__:"
so that the code only runs when it is supposed to
- The code will throw an error if the user enters anything which is not an integer. Instead of ignoring this, we should catch this error and tell the user to try again if they enter something invalid
Below is the code I would probably write if I were given this task myself. It is much longer and perhaps overkill for such a simple task, but you should try to get into good coding habits right from the start.
#!/usr/bin/env python3
"""This script gets five integers from the user and outputs whether each is odd or even"""
def main():
nums = [get_user_num() for _ in range(5)]
for num in nums:
if is_even(num):
print(num, "is even")
else:
print(num, "is odd")
def get_user_num():
num = input("Enter an integer: ")
while True:
# Repeat until the user enters a valid integer
try:
return int(num)
except ValueError:
num = input("That was not an integer - please try again: ")
def is_even(num):
return (num % 2) == 0
if __name__ == "__main__":
main()
Explanations of some of the things in the improved code: