0

I am able to get the code work good when the compound statement is changed to if a % 2 == 0 and b % 2 == 0: But as I am in learning phase could someone please guide me in explaining the error in the original code.

exm_list = [(4,8),(1,2),(4,5),(6,7),(10,20),(3,5),(3,2)]
for a,b in exm_list:
    if a and b % 2 == 0:
        print(f'{a,b} are the even numbers')
    else:
        print(f'one of {a,b} is the odd number')

enter image description here

  • 1
    Possible duplicate of [How to test multiple variables against a value?](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-value) – Chris_Rands Apr 30 '19 at 14:38
  • Please don't use images of (or links to) code. Paste the code into the question, then immediately select it and either type Ctrl+K or click the `{}` button in the editor interface to format it properly. – glibdud Apr 30 '19 at 14:39
  • what error you receive, for me is working fine – ncica Apr 30 '19 at 15:05

2 Answers2

0

The issue is that you are not asking anything for the condition for 'a'. What you should state is the following:

exm_list = [(4,8),(1,2),(4,5),(6,7),(10,20),(3,5),(3,2)]
for a,b in exm_list:
    if a % 2 == 0 and b % 2 == 0:
        print(f'{a,b} are the even numbers')
    else:
        print(f'one of {a,b} is the odd number')

Let me know.

RenauV
  • 363
  • 2
  • 11
  • Thanks, @renauV, in the original code the 'and' statement was getting applied to only 'b' and hence the 'a' is always true. – PythonLearner Apr 30 '19 at 14:50
  • I do not believe so. Look at your example (1,2) and (6, 7). By running the program I posted, you will get for both "one is the odd number". Maybe your problem should be restated. What are you trying to achieve. – RenauV Apr 30 '19 at 15:06
  • @PythonLearner in your case "if a" is equivalent to if a == 0 since a is an integer, when you write a condition ( if expr), python will try to evaluate the expr as a boolean. For an integer it will be "equals to 0", for a list it will be "list is empty" and so on... –  Apr 30 '19 at 15:06
0

In you case

if a and b % 2 == 0:

is equivalent to

if bool(a) and bool(b % 2 == 0):

a is an integer so bool(a) is True if a is not 0