In: Computer Science
Using Python. Write a program that reads a sequence (unknown number of inputs) of integer inputs and prints the number of even and odd inputs in the sequence. please explain. Thanks
We have to read unknown number of inputs, so we can read the input sequence as a string.
We can use split() function to split the string input into individual inputs, but the type of each value will still be string.
Use int() function to convert each value to integer and implement the program as follows:
Program:
Note: Please double-check the indentation using the screenshot provided as a reference.
sequence = input("Enter a sequence of integers: ") # read sequence of integers as a single string
values = sequence.split() # split sequence of integers into a list of string values using split()
num_odd = 0 # initialize odd count to 0
num_even = 0 # initialize even count to 0
for value in values: # for each value in values list
int_value = int(value) # convert each value into integer using int()
if int_value%2 == 0: # check if the integer value is even or odd using modulus operator (%)
num_even += 1 # increment even count if the integer value is even
else:
num_odd += 1 # increment odd count if the integer value is odd
print("Number of even inputs : ", num_even) # print even count
print("Number of odd inputs : ", num_odd) # print odd count
Screenshot:
Output1:
Output2:
Please don't forget to give a Thumbs Up.