Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Not Outputting
#1
PYTHON 3!!

I'm working on something for school and I can't figure out why my code is not printing "NO" or "YES" when the input is "2 2 2 5". I've tried to fix is as best as I could but nothing seemed to work. Here is the problem I was given.

Given two squares of a chessboard. If they are painted in the same color, print YES, otherwise print NO.

The program receives four integers from 1 to 8, each specifying the column and row number, first two - for the first square, and then the last two - for the second square.

a = int(input())
b = int(input())
c = int(input())
d = int(input())
if (a + b) % 2 == 0:
  if (c + d) % 2 == 0:
    print("YES")
elif (a + b) % 2 != 0:
  if (c + d) % 2 != 0:
    print("YES")
else:
  print("NO")
Thanks!
Reply
#2
I tried running this code, and it only works when the two squares are the same color- that's because you need to fix your if/else structure. The outer if/else has 3 blocks, which basically come down to this:
  • if a + b is even
  • if a + b is odd
  • else
But the else only runs if neither of the previous conditions are met- in this case, if a + b is neither even or odd. Since a + b has to be even or odd, your else statement never runs.
You might want to try making a flowchart for this, if that would help.
Reply
#3
Let's look from line 5.  If the conditional in line 5 evaluates to True we enter that conditional block.  Then if the conditional on line 6 evaluates to False the program ends.

What you want (presumably) is and, not a second nested if:
if (a + b) % 2 == 0 and (c + d) % 2 == 0:
    print("YES")
elif (a + b) % 2 != 0 and (c + d) % 2 != 0:
    print("YES")
else:
    print("NO")
Also it seems it could be simplified to this:
if (a + b) % 2 == (c + d) % 2:
    print("YES")
else:
    print("NO")
As both of the first two conditionals are asking if they evaluate to the same thing.
Reply
#4
(Oct-14-2017, 12:01 AM)Mekire Wrote: Let's look from line 5.  If the conditional in line 5 evaluates to True we enter that conditional block.  Then if the conditional on line 6 evaluates to False the program ends.

What you want (presumably) is and, not a second nested if:
if (a + b) % 2 == 0 and (c + d) % 2 == 0:
    print("YES")
elif (a + b) % 2 != 0 and (c + d) % 2 != 0:
    print("YES")
else:
    print("NO")
Also it seems it could be simplified to this:
if (a + b) % 2 == (c + d) % 2:
    print("YES")
else:
    print("NO")
As both of the first two conditionals are asking if they evaluate to the same thing.
This worked, thank you!
Reply


Forum Jump:

User Panel Messages

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