1.11M Members

python if/else & return

 
0
 

Below is a short program I'M working of from udacity.com but I can't figure out why I'M getting the value 6 from the first call to the function.

# Define a procedure, biggest, that takes three
# numbers as inputs and returns the largest of
# those three numbers.

def biggest(first, second, third):
    if (first > second and third):
        return first
    if (second > first and third):
        return second
    else:
        return third




print biggest(3, 6, 9)
#>>> 9

print biggest(6, 9, 3)
#>>> 9

print biggest(9, 3, 6)
#>>> 9

print biggest(3, 3, 9)
#>>> 9

print biggest(9, 3, 9)
#>>> 9
 
0
 

Set third to 0 (False) and see how that affects things. An "and" is 2 nested if statements:

if first > second:
    if third:

See 5.1. Truth Value Testing

 
0
 
# Define a procedure, biggest, that takes three
# numbers as inputs and returns the largest of
# those three numbers.

def biggest(first, second, third):
    if first > second and first > third:
        return first
    if second > first and second > third:
        return second
    else:
        return third


# result is 9 in each case
print biggest(3, 6, 9)
print biggest(6, 9, 3)
print biggest(9, 3, 6)
print biggest(3, 3, 9)
print biggest(9, 3, 9)

You could do:

def biggest(first, second, third):
    return max(first, second, third)
 
1
 

To be complete, a solution that iterates over the tuple instead of using if statements, and can accomodate any length of numbers input.

def biggest(*nums_in):
    ret_num = nums_in[0]
    for num in nums_in:
        if num > ret_num:
            ret_num = num
    return ret_num

print biggest(3, 6, 7)
print biggest(6, 5, 3, 8, 2)
print biggest(9, 3, 6)
print biggest(3, 3, 10)
print biggest(11, 3, 11)
You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article