-4

I'm struggling to figure out how to properly use Python to solve a quadratic inequality.

I'm trying to learn Python a bit and I'm trying to work through a quadratic inequality. I have a range of numbers for x from -5 to 5 and I want to use the equation y(x) = x**2 to calculate y(x) for all values greater than 0.

x = (-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5)

def y(x):
    if x >= 0:
        return x**2

print(y(x))

TypeError: unsupported operand type(s) for ** or pow(): 'tuple' and 'int'

NicoT
  • 341
  • 2
  • 11
ked123
  • 19
  • 6
  • Your y(x) function is going to return None for negative values of x. I doubt that's what you want. You should filter out the negative values *before* calling y(x). – jarmod Sep 10 '19 at 21:00

2 Answers2

1

Define your function for all numbers (remove the if from the function), loop over the numbers in the tuple x and put your if in the loop (this avoids the Nones that the function will return by default when called by negative numbers, and avoids the not so good solution of double checking both in the function and in the loop):

def y(x):
    return x**2

for n in x:
    if n >= 0:
        print(y(n))
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
  • Thank! This makes a lot of sense. The problem I was trying to solve was somewhat similar to this but much more complicated (for the purposes of learning I simplified it to be able to ask my question). – ked123 Sep 10 '19 at 21:05
0

x is a tuple in your code so you are trying to apply the ** operator to the whole tuple.

Try this.

for number in x:
    print(y(number))
jarmod
  • 71,565
  • 16
  • 115
  • 122
NicoT
  • 341
  • 2
  • 11