0

can anyone explain this to me?

n = int(input()) if n % 2 == 1: print("Weird") elif n % 2 == 0 and 2 <= n <= 5: print("Not Weird") elif n % 2 == 0 and 6 <= n <= 20: print("Weird") else: print("Not Weird")

9th Jul 2017, 4:55 PM
code-junkie
code-junkie - avatar
1 Resposta
+ 3
Sure thing. so first: n = int(input()) this takes input from the user in the form of an int and saves it to the variable n. if n%2 == 1: this snippet prints out the word "Weird" if the number the user put in divided by 2 has a remainder of 1. for example lets say i type in the number 9. so n=9 now. then i divide that by 2. 2 goes into 9 only 4 times. so if we did n/2 we would get 4. But where does that last 1 go that doesn't easily fit into 9/2? well if we instead use % as in 9 % 2 we would get back 1 as the result. This is what's left that doesnt fit evenly. now if it's 8%2 we would get 0 back since 8/2=4 and there is nothing left out. This is a common method to check if a number is odd or even. So what it says is if the number is odd print "weird" NEXT: elif n % 2 == 0 and 2 <= n <= 5: let's break it down. elif- this runs if the first 'if' statement didn't run. so if we entered 4 it's not odd, so it skips the first 'if' statement. elif stands for 'else if' so if the first 'if' is false we move onto this first 'else if(elif)' and check if it's true. this one checks if there is no remainder when we divide the variable n by 2 (n % 2 == 0) if it is we know it's even. since there is an "and" attached it means the statement 2 <= n <= 5 has to be true as well otherwise it moves on. so first (2 <= n) checks if the number 2 is less than or is the same as n so let's say if you entered 0, n=0. and the number 2 is not less than 0 so it would come back false. and since we need both n % 2 and 2 <= n <= 5 to be true, it would skip this line and move onto the next statement. now the n <= 5 is similar. only it checks if n is less than 5. so if the entered number is even, the same as or greater than 2, and the same as or less than 5 this statement would print out "Not weird." NEXT: the second (elif) is much the same as the first only it prints weird. FINALLY: else: this is called if all "if" and "elif" statements before it were all false, so it would print out not weird.
9th Jul 2017, 5:43 PM
Marinus Bokslag
Marinus Bokslag - avatar