This question already has answers here:
Difference between multiple if's and elif's?
(9 answers)
Closed 8 years ago.
For e.g..
According to some experts,
The conditions here are mutually exclusive:
if(n>0):
print "Number is Positive"
if(n<0):
print "Number is Negative"
if(n==0):
print "Number is ZERO"
It would be better to rewrite with elif and else:
if n > 0:
print "Number is Positive"
elif n < 0:
print "Number is Negative"
else:
print "Number is ZERO"
So I just want to ask the question that , Is there any difference between ' if ' and ' elif ' . I know the basic difference between ' if ' and ' elif '. But I just want to know , Why some novice programmers prefer ' elif ' over ' if '?
The first form if-if-if tests all conditions, whereas the second if-elif-else tests only as many as needed: if it finds one condition that is True, it stops and doesn't evaluate the rest. In other words: if-elif-else is used when the conditions are mutually exclusive.
Let's write an example. if you want to determine the greatest value between three numbers, we could test to see if one is greater or equal than the others until we find the maximum value - but once that value is found, there is no need to test the others:
greatest = None
if a >= b and a >= c:
greatest = a
elif b >= a and b >= c:
greatest = b
else:
greatest = c
print greatest
Alternatively, we could assume one initial value to be the greatest, and test each of the other values in turn to see if the assumption holds true, updating the assumed value as needed:
greatest = None
if a > greatest:
greatest = a
if b > greatest:
greatest = b
if c > greatest:
greatest = c
print greatest
As you can see, both if-if-if and if-elif-else are useful, depending on what you need to do. In particular, the second of my examples is more useful, because it'd be easy to put the conditional inside a loop - so it doesn't matter how many numbers we have, whereas in the first example we'd need to write many conditions by hand for each additional number.
You can chain if with elif and finish with an else if none of the conditions in the chain were met. When checking through the statements, it will find the first matching one and execute the instructions within that block, then break from the if/elif/else block
n = 6
if n % 2 == 0:
print('divisible by 2')
elif n % 3 == 0:
print('divisible by 3')
else:
print('not divisible by two or three')
this would print
divisible by 2
However, say you replace that elif above with an if and remove the else clause...
divisible by 2
divisible by 3
the elif chains the statements and chooses the first appropriate one.
Related
firstNumber = -50;
secondNumber = 53;
thirdNumber = 78;
# Write assignment, if, or if else statements here as appropriate
if secondNumber>firstNumber:
if secondNumber>thirdNumber:
largest=secondNumber
elif firstNumber>secondNumber:
if firstNumber>thirdNumber:
largest=firstNumber
else:
largest=thirdNumber
if secondNumber<firstNumber:
if secondNumber<thirdNumber:
smallest=secondNumber
elif firstNumber<secondNumber:
if firstNumber<thirdNumber:
smallest=firstNumber
else:
smallest=thirdNumber
# Output largest and smallest number.
print("The largest value is " + str(largest))
print("The smallest value is " + str(smallest))
Can someone help me figure out why it keeps saying that largest is undefined? Smallest runs fine
I've been sitting here for the past 30 minutes trying to see if I typed largest wrong lol
largest is undefined because there's no condition where largest is created. see the comments I added for additional insight.
firstNumber = -50
secondNumber = 53
thirdNumber = 78
# Write assignment, if, or if else statements here as appropriate
if secondNumber>firstNumber: # is True
if secondNumber>thirdNumber: # is False
largest=secondNumber
elif firstNumber>secondNumber: # Skipped because first if is True
if firstNumber>thirdNumber:
largest=firstNumber
else: # Skipped because first if is True
largest=thirdNumber
if secondNumber<firstNumber:
if secondNumber<thirdNumber:
smallest=secondNumber
elif firstNumber<secondNumber:
if firstNumber<thirdNumber:
smallest=firstNumber
else:
smallest=thirdNumber
# Output largest and smallest number.
print("The largest value is " + str(largest))
print("The smallest value is " + str(smallest))
if you remove the nesting, it will work
# Write assignment, if, or if else statements here as appropriate
if secondNumber>firstNumber and secondNumber>thirdNumber:
largest=secondNumber
elif firstNumber>secondNumber and firstNumber>thirdNumber:
largest=firstNumber
else:
largest=thirdNumber
if secondNumber<firstNumber and secondNumber<thirdNumber:
smallest=secondNumber
elif firstNumber<secondNumber and firstNumber<thirdNumber:
smallest=firstNumber
else:
smallest=thirdNumber
# Output largest and smallest number.
print("The largest value is " + str(largest))
print("The smallest value is " + str(smallest))
The problem is subtle. What is happening here is, if one of the top-level if statments if true, then the elif and else statments is automatically being not considered. So in this example, because your second number is larger than your first, BUT NOT larger than the second, the code goes down the path of your first if statment, but since the second if statment within is not true, the variable "largest" actually never gets assigned.
An alternative way is to use a "and" syntax on your if statments e.g.,
if secondNumber>firstNumber and secondNumber>thirdNumber:
largest = secondNumber
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I'm trying to solve a problem on HackerRank and I sent the code, it worked in amost all the scnarios except for scnario 7 and 3 where they insert 18 and it should return "Weird" and when they insert 20 it should return "Weird" as well according to the website.
The rules of the challenge are:
Given an integer, n, positive number from 1 to 100 , perform the following conditional actions:
If n is odd, print Weird
If n is even and in the inclusive range of 2 to 5, print Not Weird
If n is even and in the inclusive range of 6 to 20, print Weird
If n is even and greater than 20, print Not Weird Input Format
A single line containing a positive integer, .
Constraints
Output Format
Print Weird if the number is weird. Otherwise, print Not Weird.
And my code was:
n = 0
n = int(input('Type a number between 1 and 100: '))
odd = False
even = True
# ODD / EVEN
if (n%2) == 0:
n = even #True
else:
n = odd #False
# Is this odd or is this even?
if n == odd:
print ('Weird')
if n == even > 5 < 20:
print('Weird')
elif n == even > 1 < 6:
print ('Not Weird')
else:
print('Not Weird')
I can't see what I did wrong, can you help me to solve it so it can work in all scnarios?
There's a lot to unpick here. As this is an assignment, I'm not going to print the full solution out here, but I will point out the mistakes you've made so you can come to the correct solution.
First issue: reassigning 'n'.
You assign the value from the input to n, then subsequently replace it with the value of odd or even. This means you have lost the original input number. Instead you should assign the result to a new variable (such as 'isEven').
Second issue: uneccesarry 'if'
The result of 'n%2 == 0' is already True/False, depending if n is an even/odd number. So you can simply assign the result, rather than use an 'if' block.
Third issue: multiple operators
Logical operators have an order of operation, and resolution. The statement 'n == even > 5 < 20' makes no logical sense. Instead you should do independent Boolean comparisons, and join them with "and" or "or". E.g. 'if isEven and n < 5 and n> 20'.
Given an integer, , perform the following conditional actions:
If is odd, print Weird
If is even and in the inclusive range of 2 to 5, print Not Weird
If is even and in the inclusive range of 6 to 20, print Weird
If is even and greater than 20, print Not Weird
Every time I run the code, it only executes the else statement else: print("lol") , whether I type any value from 1 to 25.
What's wrong?
n = input("Enter a number here: ")
num = int(n)
if (num % 2) == 0 >= 2 and (num % 2) == 0 <= 5:
print("Not Weird")
elif num % 2 == 0 >= 6 and num % 2 == 0 <= 20:
print("Weird")
elif num % 2 == 0 > 20:
print("Not Weird")
else:
print("lol")
(num % 2) == 0 >= 2 is not the correct way to check if a number is even and in the range you want. If you want to check if num is even and in that range, you'd do something like:
(((num % 2) == 0) and (1 < num <= 5))
As others have pointed out your conditions are not written correctly. Here's the first part to get you started (if the number is odd, and if the number is even and between 2 and 5):
n = input("Enter a number here: ")
num = int(n)
isEven = (num % 2) == 0
if not isEven:
print("Weird")
elif 2 <= num <= 5:
print("Not Weird")
Just as Random Davis said , the problem is in precedence(or whatever it is called sorry XD) so what it does is :
when you check for [(num % 2) == 0 >= 2] : what it does is first checks if num is even[(num % 2)] and then it checks the relation between 0 and 2[0 >= 2] and then equates [ [(num % 2){maybe true or false} == (0 >= 2){always false}]] which results in a LOGICAL ERROR
Rather what you should do is this
(((num % 2) == 0) and (1 < num <= 5)) {just as Random Davis said.}
what it does is checks whether number is even or not[(num % 2) == 0)] and then if number is between 1 and 5[(1 < num <= 5)] and then cheks if both are true or not.
Hope you understand what I am trying to say.
There are a couple of problems with your solution. There is nothing wrong with your if-else statements. They are valid, but are not doing what you want. Looking at the first if:
if (num % 2) == 0 >= 2 and (num % 2) == 0 <= 5:
print("Not Weird")
You first use modulo and test for equality with 0, which is a reasonable test for even vs odd. However, you then compare the boolean result of the even-add test with the number 2. You want to test num with 2, not the boolean of evenness with 2. Testing a boolean result for >= 2 always comes out false. That is True >= 2 is False; and False >=2 is False. Python is smart enough to know that False and (anything else) will be false, so Python won't even evaluate the rest of the statement.
So to test if a number is even and in the range of 2 to 5 inclusive you should want to do:
if num % 2 == 0 and 2 <= num <= 5 :
print("Not Weird")
A few words about Python: Python differs from other languages in that the form "2 <= num <= 5" is a legal construct. It is darn convenient, but atypical among languages. In other languages the initial 2<=num results in a boolean and then then you would get an error comparing a boolean to 5. It is interesting that Python does not throw an error but results in a boolean. Though Python is atypical it is useful. Other languages would require something like
if (2 <= num) and (num <= 5) then # Not a Python statement!
Another oddity is that the and operator is lower precedence than the other comparison operators. In other languages and is higher or equal. The Python rules of precedence let you use "num % 2 == 0 and 2 <= num <= 5", so the evenness test and the double inequality run before the "and", so you get a natureal human result. BUT IT IS DIFFERENT FROM OTHER LANGUAGES. You will probably learn a lot of languages over the years. Appreciate how they work.
I'll let you figure out the rest of the statements in your original solution. However, there is another problem: You don't handle odd numbers in your solution correctly, since you are printing out lol. For debugging you are doing the correct thing, since the printing of "Weird" for odd numbers is an ambiguous result. If you did that on purpose for debugging, CONGRATULATIONS!, you are thinking like a programmer digging through your program.
I submit that your approach is a bit of a brute force approach. The directions do say:
If is odd, print Weird
If is even and in the inclusive range of 2 to 5, print Not Weird
If is even and in the inclusive range of 6 to 20, print Weird
If is even and greater than 20, print Not Weird
As a programmer, you do not have to follow the given directions. You need to formulate a solution that results in an algorithm that meets the specifications. Part of the art of programming is to recognize whether the specs are subject to change, anticipate needs for updates, and even correct some assumptions that the specs make that might be in error. So while this is a simple task, it is rich in teaching. (Kudo's to your instructor).
One way to look at the specs is that it implies non-negative inputs. What is one to do with -4 or 0? Not in the specs. It is fair to look at proposed input and see what it is so you can handle that case. Sometimes other logic is added to reject illegal entries. It isn't specified here, so I would handle it with a comment in the code that input is expected to be a positive non-zero integer.
In addition, there is a certain approach that is a bit more wholistic: If odd print Weird and quit, otherwise you know num is even, so further checking is not needed for evenness. So then you print Weird for num in the range [6..20], otherwise print Not Weird. The big picture is odds print Weird, any number [6..20] prints Weird, everything else prints Not Weird.
if num % 2 == 1 : # Handle odd num
print("Weird") # Any odd prints Weird
else: # Handle even num
if 6 <= num <= 20:
print("Weird")
else:
print("Not Weird")
The point is once you do a test you know womething that can be carried forward in your code. Once you test that something is odd, handle it, and after that the code knows the number if not odd is even, and you don't have to keep testing it. Logically, if odd print and be done. Otherwise (num is even) print "Weird" for num in [6..20], print "Not Weird" otherwise. Rather than 3 tests when a number is even now there is just the one test for num being in the range [6..20].
A few comments are sprinkled in. No testing for input less than 1.
The whole thing could be simplified further
if num % 2 == 1 or 6 <= num <= 20: print("Weird")
else:print("Not Weird")
That does simplify the whole thing.
It is interesting that in programming the simple question of "what is wrong with my statement" can sometimes be addressed with "should I be using this approach?" I've gone far afield with this answer. Originally, what's with my if statement was the issue, but this little gem of a problem is really teaching a lot. (Again, Kudo's to the teacher!)
So, do you transform thw whole question and use an or, or does the first approach work better. In the real world you might have a sense of how the specification may be changed and your solution will be best when it is correct, uses reasonable resources, and is maintainable.
I am trying to create a program that prints out a list of numbers starting at 0 and leading up to a number the user inputs (represented by the variable "number"). I am required to use "while" loops to solve this problem (I already have a functional "for" loop version of the assignment). The program should mark anything in that list divisible by 3 with the word "Fizz," divisible by 5 with the word "Buzz," and anything divisible by both with "FizzBuzz" while also including unlabeled numbers outside of those specifications.
Every time I run this program, it ignores the conditions and just prints the word "FizzBuzz" however many times is represented by the number inputted. (I typically use 15 because it has at least one example of each condition, so that means I get 15 "FizzBuzz"s in a row).
To find out why it was doing that, I used print(i) instead of the rest of the program under the first conditional and it gave me 15 counts of the number 0, so there is reason to believe the program is completely ignoring the range I gave it and just outputting copies of i based on the user number input.
Any help would be appreciated!
number = int(input("Enter a Number"))
i = 0
while(i < number + 1):
if number % 3 == 0 and number % 5 == 0:
print("Fizzbuzz")
elif number % 5 == 0:
print("Buzz")
elif number % 3 == 0:
print("Fizz")
else:
print(number)
i += 1
print ("Done!")
You meant to check the divisibility of i, which increments every loop, not of number which doesn't change.
You also meant to print(i) in the else clause.
its my second day of class in introductory programming and im having trouble. We are on if statements. The homework is
Write a program that prompts the user for an integer (you can assume that the
value entered will be an integer). If that integer is equal to zero, print “zero”. If not, determine if
it is positive or negative and print which one it is. Also, determine if the number is evenly divisible
by 5 or not.
Now i can prompt the user for a number and determine if its positve or negative or if its divisible by 5 but i dont know how to make the program bypass the unmet first condition and go into the second set of condition, example of my code below,
number = input("enter an integer: ")
if number > 0 and number%5 == 0:
print number, "is positive and divisible by 5"
else :
print "positive but not divisible by 5"
if number < 0 and number%5== 0:
print "neggy and divisible by 5"
else :
print "neggy but not divisible by 5"
my problem is that when i type a negative number it print "positive but not divisible by 5" because the 1st condition wasnt met. I tried elif but i get a syntax error averytime, help?
Please dont go to fancy as my teacher only wants the basic "and", "or", "if", "else", and "elif", words used. Thanks
Use elif:
number = input("enter an integer: ")
if number > 0 and number%5 == 0:
print number, "is positive and divisible by 5"
elif number > 0:
print "positive but not divisible by 5"
elif number < 0 and number%5== 0:
print "neggy and divisible by 5"
elif number < 0:
print "neggy but not divisible by 5"
else:
print "zero"
Let’s tackle each of the tests separately first. So first of all, you want to check if it is positive or negative (or zero even). That is one “category” of properties, because a number cannot be both positive and negative:
if number > 0:
# number is positive
elif number < 0:
# number is negative
else:
# number is zero
Of course, you can order those checks however you want; you could also check for zero first etc.
So, the second check if it is divisible by 5 or not. That’s a second category, so we have to handle that separately from the sign:
if number % 5 == 0:
# number is divisible by 5
else:
# number is not divisible by 5
So now we have two separate checks for two separate property categories. If we want a single output for both properties (e.g. “positive and divisible by 5” as you already used in your code). There are different ways to interlock those two checks now. One would be to simply put one into the other one, like this:
if number > 0:
if number % 5 == 0:
print('Number is positive and divisible by 5')
else:
print('Number is positive but not divisible by 5')
elif number < 0:
if number % 5 == 0:
print('Number is negative and divisible by 5')
else:
print('Number is negative but not divisible by 5')
else:
print('Number is zero')
As you can see, this is just the second check pasted into each of the (appropriate) cases of the first check. Note that this will unnecessarily increase the indentation level, so we might want to look how we can avoid that.
You already started with this in your code, we basically want to combine two checks using and. Note that we need to make sure that in the above solution, the inner else cases (from the divisibility) still expects the outer (sign check) to be true. So we need to make sure that we keep that:
if number > 0 and number % 5 == 0:
print('Number is positive and divisible by 5')
elif number > 0:
print('Number is positive but not divisible by 5')
elif number < 0 and number % 5 == 0:
print('Number is negative and divisible by 5')
elif number < 0:
print('Number is negative but not divisible by 5')
else:
print('Number is zero')
As you can see, we’re down to a single indentation level, and we have all our checks within a single if-elif-else structure. This unfortunately forces us to have some duplication in the checks as explained above. That’s because when checking for two things in a single if, we don’t know which is false when we get to the else/elif. So if we still want to make sure that e.g. the number is positive when it wasn’t positive and divisible by 5, we have to check for that again.
This is essentially what you forgot: Your else could actually only say “not positive or not divisible by 5”.
Now, to take this just a bit further, we can actually still get rid of the duplication. Because our two “property categories” are completely independent, we can check them independently (just like we did at the beginning). To get a combined output, all we need to do is to construct that output sequentially:
# because zero is a special case, we handle it separately
# while sacrificing an indentation level.
if number == 0:
print('Number if zero')
else:
# check for the sign first
if number > 0:
output = 'Number is positive'
else:
output = 'Number is negative'
# check for the divisibility next
if number % 5 == 0:
output += ' and divisibile by 5'
else:
output += ' but not divisible by 5'
# whatever the checks resulted in, we have our output
print(output)
Of course this might be a bit too far for your task yet, but it might be good to know for the future :)
It's best to use if ... elif ... else but anyway, I'm throwing another option in:
if number == 0:
print 'zero'
else:
print number, 'is', 'positive' if number > 0 else 'negative', 'and',
print 'not' if number % 5 else '', 'divisible by 5'
Explanation... This takes advantage of the way the print statement in Python 2 can take several values separated by commas, and displays the values separated by spaces; and it uses conditional expressions, which allow you to rewrite (e.g.)
if condition:
print 'yes'
else:
print 'no'
as
print 'yes' if condition else 'no'
but are not very highly recommended because they often make code less readable.
if number == 0:
print "zero"
else:
pos = (number > 0 )
div_by_5 = (number % 5 == 0)
if pos and div_by_5:
print number, "is positive and div by 5"
elif pos and not div_by_5:
print number, "is positive but not div by 5"
elif not pos and div_by_5:
print number, "is negative and div by 5"
elif not pos and not div_by_5:
print number, "is negative but not div by 5"
Python 2.7.4
number = int(raw_input())
if not number: print "zero"
elif abs(number) % 5 == 0:
print [ `number` + " is negative and divisible by 5",
`number` + " is positive and divisible by 5"][number > 0]
else: print [ `number` + " is negative but not divisible by 5",
`number` + " is positive but not divisible by 5"][number > 0]
Backtick