Can anyone please help me understand the solution


#1

Given 2 int values, return True if one is negative and one is positive. Except if the parameter "negative" is True, then return True only if both are negative.

def pos_neg(a, b, negative):
  if negative:
    return (a < 0 and b < 0)
  else:
    return ((a < 0 and b > 0) or (a > 0 and b < 0))_

#2

is this an exercise? If so, do you have the url?

maybe you should make this:

return (a < 0 and b < 0)

into a if condition, and return the boolean value True?


#3

http://codingbat.com/prob/p162058


#4

what is the error message you get?

here:

 return ((a < 0 and b > 0) or (a > 0 and b < 0))_

the _, is that a copy mistake, or is it really there? it is invalid syntax, and might cause an error

Or does the code work? If so, what is it you don't understand? I can fill in any blanks you have, but please explain what you do understand.


#5

sir i want to your help in understanding the code. i will be very thankful


#6

yea, i understood that a bit late. Can you tell me what do you understand? It is much easier to fill in the blanks, i have currently no idea of your level of understanding

in short, first you check if negative is true:

if negative:

if so, you have to check if both a and b are smaller then zero.

if negative is false, you need to check if one number is negative and the other is positive.


#7

instead of wrting

if negative==True:

we have written

if negative:

what does this mean?

same goes for

return ((a < 0 and b > 0) or (a > 0 and b < 0))

#8

well, in the end it matters if the condition evaluates to True. For example this would be True:

if True:

and this would be false:

if False:

you don't always have to compare. You can simply (in particular if you have boolean values) just let if decide if it is true or false.

same goes for the return, python will evaluate to use the conditions to True or False. Which you can then simply return. It is a clever trick, and running it in a python IDLE will show it nicely:

print(-5 < 0 and 5 > 0)

will print True


#9

Ok, I understand it now, Thank you so much :relaxed:


#10

you could compress this solution even further:

return a < 0 and b < 0 if negative else a < 0 and b > 0 or a > 0 and b < 0

it becomes a bit unreadable. also, this is python, you don't need that many parentheses. and is evaluate before or and return doesn't require parentheses. So you can remove all the parentheses


#11

Alright great, Can you suggest me some best references?


#12

learn python the hard way (online/book/pdf)
sololearn.com
building your own projects
codecademy
official python documentation
(in no particular order)


#13

Ok, Thanks Sir, It would be of great help to me. A sincere thanks :relaxed:


#14

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.