Return the largest of the three numbers

hello:D
so I’m trying to solve this practice question about “Control Flow” the problem states:

" Write a function called largest_number that takes three integer inputs, x , y , and z . Have this function, as its name implies, return the largest of the three numbers."

I write what i believe to be the code and when I run it I get what they are asking for, but i still get a message that " largest_number did not return the largest value."

the code i write is :

:

def largest_number (x , y , z):
  if x > y > z :
    return x
  elif x < y > z:
    return y
  else:
    return z

print (largest_number(7 , 8 , 9))

What could be done better??

What about equality?

Welcome to the forums :slight_smile:

1 Like

Not sure what you mean :thinking:

And thank you for the welcome :smiley:

What if x and y are equal (and larger than z) for example? Would the code work then?

I think you mean this, but i did not worked :frowning:

def largest_number (x , y , z):
  if x >= y >= z :
    return x
  elif x <= y >= z:
    return y
  else:
    return z

print (largest_number(7 , 45 , 9))```

So apperantly this was the correct code:

def largest_number (x,y,z):
  if (x >= y) and (x >= z):
   return  x
  elif (y >= x) and (y >= z):
   return  y
  else:
   return  z


print(largest_number(23,53,654))

Yep. I think in general it’s interesting to test what are the breaking cases first and try to get a code that will cover every scenario (rather than be efficient). Factoring/simplifying can come after. If you get used to it, the factoring can be done automatically, but that’s really from internalizing the initial logical step.

Your idea of x > y > z is really efficient but it leaves a lot of gaps .

One idea to refactor here
you have

if (x >= y)

then

elif (y >= x)

you can already cut out the = for the second one (since equality was checked for the first time around).

Always know what the situation dictates. It may be equality works in one, but not in another. Know what the bounds are, then set the inequality. It’s not guess work.

2 Likes

Correct code is: