+ 1

Printing the results of comparisons

take this snapshot even = (user_num % 2) == 0 if even: print("your number is even") else: print("your number is odd") I'm having a problem in understanding why this code would print a true boolean expression. I can't even describe why I can't understand this. I guess I'm having a problem understanding why this works without creating an odd variable and superficially having a comparison to the odd variable.

11th Nov 2016, 4:12 AM
Sameer Sheikh
Sameer Sheikh - avatar
3 ответов
+ 8
You don't need to check whether the number is odd or not, as if the number is not even then it is odd. In this code, at first we assign the boolean "even" variable true, if the reminder after division by 2 is 0, and if it is not 0, "even" becomes false. After that we go to the if & else statements. First of all you should know, that we enter the "if" statement, if the the condition is true. If the condition for if statement is false, we move to the else statement. So here we have a boolean variabe "even", which is either true or false. "if even:" will work and print "your number is even", if "even" is true (the condition will be true), otherwise we will move to the else statement and print "your number is odd"
11th Nov 2016, 6:14 AM
Rebeka Asryan
Rebeka Asryan - avatar
+ 1
let's split up the code how it works: even = (user_num % 2) == 0 this line evaluates the expression '(user_num % 2) == 0' and assigns the result to the variable 'even'. if 'user_num' is even then the expression will evaluate to True, otherwise it will evaluate to False. if even: print("your number is even") else: print("your number is odd") this is not hard either. the variable 'even' has a value of either True or False at this point. it's easier to explain if we imagine the expression in place of the 'even' variable. if (user_num % 2) == 0: print("your number is even") else: print("your number is odd") if the expression evaluates to True, great! Python just executes whatever comes after, until it reaches 'else:'. since the expression was True, we don't need to execute the 'else' block. if the expression evaluates to False, it passes through the block until it finds 'else:'. because the expression was False, we should execute this. now, by assigning the expression to the variable you have just moved it out of the 'if' statement, it doesn't change the logic. you can move any other expression outside, all the 'if' statement cares about is if it receives True or False. user_num = 2 even = (user_num%2) == 0 # (2%2)==0 ; 0 == 0 ; True user_num = 3 even = (user_num%2) == 0 # (3%2)==0 ; 1 == 0 ; False
20th Nov 2016, 5:15 PM
asdadasdsaczxc
0
Thank you for the wonderful explanation!
8th Feb 2017, 6:47 PM
Sameer Sheikh
Sameer Sheikh - avatar