0

I am very new to python, and I am trying to make a program that allows a user to enter three numbers and the program will tell them the sum, average, product, and the odd numbers of the numbers. I just can't seem to find a way to get the odd numbers listed on one line. Here is what I have:

def main():
    x, y, z = eval(input("Enter three integers, each seperated by a comma: "))

    Sum = (x+y+z)
    Average = (x+y+z)/3
    Product = (x*y*z)

    print("Sum:", Sum)
    print("Average:", Average)
    print("Product:", Product)

    print("Odd Numbers: ")
    if (x % 2) != 0:
        print(x)
    if (y % 2) != 0:
        print(y)
    if (z % 2) != 0:
        print(z)
main()
Miket25
  • 1,895
  • 3
  • 15
  • 29
TheBigW
  • 54
  • 1

3 Answers3

2

This one liner will work.

print('Odd Numbers:', ', '.join(str(num) for num in (x,y,z) if num % 2))

"if num % 2" resolves to a boolean true if the number is odd and false if even through an implicit conversion to boolean from integer. All values that are accepted need to be converted via "str(num)" to a string for use with ', '.join, which connects the string version of the odd numbers with a ', ' between them.

Evan
  • 2,120
  • 1
  • 15
  • 20
0

This will add all the odd numbers into an array, then print the array with a space between each value in the array. Got the join line from this SO answer.

odd_numbers = []
print("Odd Numbers: ")
if (x % 2) != 0:
   odd_numbers.append(x)
if (y % 2) != 0:
   odd_numbers.append(y)
if (z % 2) != 0:
   odd_numbers.append(z)

print " ".join([str(x) for x in odd_numbers] )
Jason
  • 514
  • 5
  • 21
0

Within your print, you can set your end character using end from a newline to a space to print them on one line.

    print("Odd Numbers:",end=" ")
    if (x % 2) != 0:
        print(x,end=" ")
    if (y % 2) != 0:
        print(y,end=" ")
    if (z % 2) != 0:
        print(z,end=" ")

The output will be: x y z if they are all odd.

Another note is that the use of eval should be carefully if not never used due to the security risks

Instead you can accomplish the user input of comma-separated values using the split function to return a list of values from the users.

userInput = input("Enter three integers, each seperated by a comma: ")
userInputList = userInput.split(",") #Split on the comma
#Assign x,y,z from userInput
x = userInput[0]
y = userInput[1]
z = userInput[2]
Miket25
  • 1,895
  • 3
  • 15
  • 29