Search code examples
pythonpython-3.xmedianpython-3.4

Middle value using python 3


UPDATED

a = int(input("Give a value: "))
b = int(input("Give a value: "))
c = int(input("Give a value: "))
def middle(a, b ,c) :
    m = min(a,b,c)
    M = max(a,b,c)
    return a+b+c-m-M

This is where im at. It takes my numbers into the data. How would I get it to display the middle one?! Sorry I'm so terrible at this. Way in over my head on this intro course. @CommuSoft @Zorg @paxdiablo and everyone else


Solution

  • You should put a colon (:) on the first line (def) as well.

    This works for the online python environment:

    def input(a, b, c) :
        if a <= b <= c or c <= b <= a :
          return b
        elif b <= a <= c or c <= a <= b :
          return a
        else:
          return c
    

    Furthermore it is more advisable to make use of min and max I guess. Min and max are sometimes directly supported by a CPU and there are implementations that avoid branching (if-then-else's):

    def input(a, b, c) :
        m = min(a,b,c)
        M = max(a,b,c)
        return a+b+c-m-M
    

    or:

    def input(a, b, c) :
        return min(max(a,b),max(b,c),max(a,c))
    

    The last one is also numerically stable.

    In most cases if-then-else clauses should be avoided. They reduce the amount of pipelining although in interpreted languages this might not increase performance.


    Based on the comments, I guess you want to write an interactive program. This can be done like:

    def middle(a, b, c) : #defining a method
        return min(max(a,b),max(b,c),max(a,c))
    
    a = int(input("Give a value: "))
    b = int(input("Give b value: "))
    c = int(input("Give c value: "))
    print("The requested value is ")
    print(middle(a,b,c)) #calling a method
    

    Defining a method will never result in Python using that method. The a, b and c in the def block are not the a, b and c in the rest of your program. These are "other variables that happen to have the same name". In order to call a method. You write the methods name and between brackets the parameters with which you wish to call your method.