0

So I was stuck on this test question for ever could someone explain something to me. Why did my code only work after adding ()’s

So I was working on this problem in SoloLearn: Write a program that takes a numbers input and -outputs it’s double, if the number is even -outputs it’s triple, if the number is odd -returns 0, if number is 0 So I tried and tried and eventually came up with this code num = int(input()) if num %2: print( num*3) else: if num /2: print(num*2) else: if num==0: print("0") But the test cases didn’t yield a passing result. Until I added parenthesis around num—-> print((num)*3) https://code.sololearn.com/cIgRU2asHgBu/?ref=app

16th Apr 2021, 4:44 PM
Reginald Gray
3 Answers
+ 5
Reginald Gray There should be num % 2 == 0 for even and num % 2 == 1 for odd https://code.sololearn.com/c3h6kL9RvELL/?ref=app
16th Apr 2021, 4:50 PM
A͢J
A͢J - avatar
+ 4
Hey Reginald Gray like you make condition for num==0 You have to make condition odd/even number also if(num%2==0) -for even number if(num%2==1) -for odd number
16th Apr 2021, 5:07 PM
Giriraj Yalpalwar
Giriraj Yalpalwar - avatar
+ 2
Reginald Gray To add to what has been stated. Your first 'if' statement will currently only run if num is an odd number. All even numbers and zero will return zero for the result of the expression 'num % 2'. 0 is a falsy value and will be evaluated to False so the statement will not be ran. Likewise, if num is odd it will result in 1 which is a truthy value and will be evaluated to True, and the statement will run. Similarly, your nested if statement will always be truthy for any value other than 0 as all numbers that reach this statement will be either even or 0. All even numbers will result in a value that is greater than 0, which again would be truthy. 0 will result in 0 which is falsy. This is why the comparison of == 0 and/or == 1 etc is needed. (Unless you're intending the current behavior)
16th Apr 2021, 5:44 PM
ChaoticDawg
ChaoticDawg - avatar