-1

program that requests four number (integer or floating-point) from the user. your program should compute the average the first three numbers and compare the average to the fourth. if they are equal, your program should print 'Equal' on the screen.

import math
x1 = input('Enter first number: ')
x2 = input('Enter second number: ')
x3 = input('Enter third number: ')
x4 = input('Enter fourth number: ')

if ( x4 == (x1 + x2 + x3) / 3):
    print('equal')

Error message:

if ( x4 == (x1 + x2 + x3) / 3):
TypeError: unsupported operand type(s) for /: 'str' and 'int'" 

second error message after trying to convert to int:

x1 = int(input('Enter first number: ')) ValueError: invalid literal for int() with base 10:

Mk1982
  • 1
  • 1
  • 1
    Duplicate of [How can I read inputs as integers in Python?](http://stackoverflow.com/q/20449427/2301450) – vaultah Jul 28 '16 at 07:47
  • As you can see in the documentation [`input`](https://docs.python.org/3/library/functions.html#input) returns a string. You have to [convert the string to an integer](https://docs.python.org/3/library/functions.html#int) or a [`float`](https://docs.python.org/3/library/functions.html#float) if you want to do mathematical operations. – Matthias Jul 28 '16 at 07:48

1 Answers1

0

You are using mathematical operands on strings. Here is your fix:

import math
x1 = int(input('Enter first number: '))
x2 = int(input('Enter second number: '))
x3 = int(input('Enter third number: '))
x4 = int(input('Enter fourth number: '))

if ( x4 == (x1 + x2 + x3) / 3):
    print('equal')

You simply have to cast the strings to int.

tbobm
  • 113
  • 1
  • 9
  • Those values might be floating point numbers, so you would have to use `float`. The problem of comparing floating point numbers comes up next ... – Matthias Jul 28 '16 at 07:52
  • I tired but did not work. x1 = int(input('Enter first number: ')) ValueError: invalid literal for int() with base 10: '4.5' – Mk1982 Jul 28 '16 at 10:55
  • Replace the `int` by `float` then. Using only `int` is, as @Matthias said, used for int values. It gets you an error if you try to cast a string which looks like a float, to an int. – tbobm Jul 28 '16 at 12:20