We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,437 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

python if/else & return

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
3
Contributors
3
Replies
17 Hours
Discussion Span
5 Months Ago
Last Updated
4
Views
Garrett85
Posting Pro in Training
426 posts since Oct 2009
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 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

woooee
Posting Maven
2,707 posts since Dec 2006
Reputation Points: 827
Solved Threads: 780
Skill Endorsements: 9
# 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)
Ene Uran
Posting Virtuoso
1,830 posts since Aug 2005
Reputation Points: 676
Solved Threads: 255
Skill Endorsements: 7

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)
woooee
Posting Maven
2,707 posts since Dec 2006
Reputation Points: 827
Solved Threads: 780
Skill Endorsements: 9

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.0782 seconds using 2.79MB