Python Forum
Functions with conditionals and comparison operators
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Functions with conditionals and comparison operators
#4
Based on @Ichabod’s and @buranfor’s feedback, here are the changes I have made since my last forum post:
  • I replaced the line which previously read elif (a % 2 and b % 2) != 0: to just else
  • I removed the explicit pass operation
  • I replaced the print statements with return
  • I removed the explicit boolean references. Instead of if (a % 2 and b % 2) != 0: I now just use: if a % 2 and b % 2:

With these changes, here is what my script looks like now:

def lesser_of_two_evens(a,b):
    if a % 2 and b % 2:
        if b < a:
            return a
        if a > b:
            return b
    else:
        if a < b:
            return b
        else:
            return a
As outlined initially, I’m expecting the following output:

Quote:lesser_of_two_evens(2,4) --> 2
lesser_of_two_evens(2,5) --> 5
lesser_of_two_evens(245,13) --> 245
lesser_of_two_evens(52,10) --> 10

But I am actually getting:

Quote:lesser_of_two_evens(2,4) --> 4
lesser_of_two_evens(2,5) --> 5
lesser_of_two_evens(245,13) --> 245
lesser_of_two_evens(52,10) --> 52

It partially worked. I’ve tried many combinations at lines 4, 6, 9, and 11 (swapping a and b) and then running the script and testing the output. The output is correct for two lines, but then the other two test output lines are incorrect.

What would I need to change in my script to produce the expected output?

The answer key from the instructor is much simpler and less complicated. It reads:

def lesser_of_two_evens(a,b):
    if a%2 == 0 and b%2 == 0:
        return min(a,b)
    else:
        return max(a,b)
Even with this as the most elegant solution, how would you folks modify my script to return the correct output?
Reply


Messages In This Thread
RE: Functions with conditionals and comparison operators - by Drone4four - Dec-26-2018, 01:28 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Meltdown Mitigation (operators + conditionals) beware: Exercism potential spoiler Drone4four 5 2,773 Feb-21-2022, 08:49 AM
Last Post: Gribouillis
  Need help with a homework problem on logical operators voodoo 3 4,681 Jun-28-2019, 03:45 PM
Last Post: jefsummers
  Guessing game with comparison operators Drone4four 9 13,978 Dec-02-2018, 06:12 PM
Last Post: ichabod801
  Nested Conditionals Elero 3 8,049 Apr-16-2018, 07:58 PM
Last Post: Elero
  Error with conditionals RiceGum 17 7,504 Oct-18-2017, 01:45 AM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020