Python Forum
Why does this alternative solution work?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why does this alternative solution work?
#1
The problem:
We have a loud talking parrot. The "hour" parameter is the current hour time in the range 0..23. We are in trouble if the parrot is talking and the hour is before 7 or after 20. Return true if we are in trouble.

My code:

def parrot_trouble(talking, hour):
  if hour<7 or hour>20:
    return talking
  else:
    return False
Their solution:

def parrot_trouble(talking, hour):
  return (talking and (hour < 7 or hour > 20))
How does the simplified version work? I don't understand how the "and" works in that final return statement.
Reply
#2
(May-31-2018, 04:18 AM)wlsa Wrote: We are in trouble if the parrot is talking and the hour is
This is not an alternate solution. In your function, there is not 'talking' in the if condition although it is in the assignment.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
in their return statement they have two parts/conditions
  • talking
  • (hour < 7 or hour > 20)
python evaluates from left to right so if talking is evaluated to True it will evaluate the second condition because and requires all conditions to be True. It will stop evaluating at the moment when it is clear. i.e. if talking is False, it will return False, without evaluating the second condition at all.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Forum Jump:

User Panel Messages

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