Say I have the following Python 3 code:
def foo(number_a, number_b):
if number_a >= 0:
print("a is Positive")
if number_b <= 100:
print("b is <= 100")
else:
print("a is negative and b > 100")
How can I have the else fire if and only if both conditions are false?
I could do something like this:
doElse = True
if condition1:
doElse = False
# do something
if condition2:
doElse = False
# do something
# condition3...conditionN
if doElse:
# do the else
But that would require setting the variable, then changing it for every if
Is there a better way to do this?
As long as your first and second condition are mutally exclusive, you should always solve this with a single if/elif/else construct. Using your original example:
if word == "banana":
print("word is banana")
elif word == "apple":
print("word is not banana, but it is apple")
else:
print("word is neither banana, nor apple, but something else")
If you have conditions which are not mutally exclusive, then this obviously doesn’t work as you want to continue checking the other conditions as well.
In that case, you should try to find a common condition for all of them. This can be as simple as combining the conditions with or:
if number >= 0 or number <= 100:
if number >= 0:
print("Positive")
if number <= 100:
print("<= 100")
else:
print("x < 0 or x > 100")
But you could also combine them if that’s possible:
if 0 <= number <= 100:
…
Or you could replace the else by an inverted condition:
if number >= 0:
print("Positive")
if number <= 100:
print("<= 100")
if number < 0 or number > 100:
print("x < 0 or x > 100")
For everything more complicated than that, you will have to keep track of this in another way, involving more code.
You can just reorder the if statements like so:
def foo(number_a, number_b):
if number_a < 0 and number_b > 100:
print("a is negative and b > 100")
elif number_a >= 0:
print("a is Positive")
else:
print("b is <= 100")
Related
i am doing a challenge but for some reason every time i run it says 3 outta of 7 test cases are incorrect and don't know why? everything seems in order. Here is the challenge if Task
Given an integer, , perform the following conditional actions:
If is odd, print Weird
If is even and in the inclusive 2 range of 5 to , 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
My code below:
n = int(input().strip())
if n % 2 != 0:
print("Weird")
else:
if n % 2 == 1 and n in range(2,5):
print("Not Weird")
elif n % 2 == 1 and n in range(6,20):
print("Weird")
elif n > 20:
print("Not Weird")
Try this
n = int(input().strip())
if n % 2 != 0:
print("Weird")
else:
if n in range(2,6):
print("Not Weird")
elif n in range(6,21):
print("Weird")
elif n > 20:
print("Not Weird"
To include 5 and 20 in range you need to specify it as number + 1. Range does not include the last number. Also, there is no need to check for even condition every time in the else part as the control jumps to else when if fails!.
n = int(input().strip())
if n % 2 != 0:
print("Weird")
else:
if n in range(2,6):
print("Not Weird")
elif n in range(6,21):
print("Weird")
elif n > 20:
print("Not Weird")
a = float(input("Insert a floating point number:"))
n = int(input("Insert an integer number >= 0 :"))
accum = 1
count = 1
while n >= count and n >= 0:
accum = accum * a
count += 1
elif n < 0:
print("Integer value is less than 0")
if n >=0 and n < count:
print(accum)
I need to create a code which asks the user for a floating point number 'a' then an integer to use as the power of 'a' which is 'n'. I need to use a while loop and it must be valid for n>=0 only. If I don't have the elif statement then the code runs normally.
While technically you can put n >= 0 in the condition of the while loop to skip the loop if n < 0, it doesn't make sense to do so, because you never modify the value of n in the loop. It would be clearer to put the entire loop in the body of another if statement (which, incidentally, is the one which your elif—or else, as we'll see—would naturally belong to.)
a = float(input("Insert a floating point number:"))
n = int(input("Insert an integer number >= 0 :"))
accum = 1
count = 1
if n >= 0:
while n >= count:
accum = accum * a
count += 1
# We already know n >= 0, and the only way
# for the loop to exit is for n < count to be
# true, so no additional testing needed before
# we call print here.
print(accum)
else: # If n >= 0 is not true, n < 0 *must* be true
print("Integer value is less than 0")
It's invalid because you firstly need to add an if statement and then follow it with an elif.
if n < 0:
print("Integer value is less than 0")
elif n >=0 and n < count:
print(accum)
You need to change the elif and if statement position
while n >= count and n >= 0:
accum = accum * a
count += 1
if n >=0 and n < count:
print(accum)
elif n < 0:
print("Integer value is less than 0")
Else if always comes after if
I want to check the value range of an input number, then print the correct "size" (small, medium or large). If the value is out of my acceptable range, then I want the else statement to print out that the number is not valid.
Minimal example for my problem:
n = int(input("number= "))
if 0 <= n < 5:
a = "small"
if 5 <= n < 10:
a = "medium"
if 10 <= n <= 20:
a = "large"
print("this number is",a)
else:
print("thats not a number from 0 to 20")
According to Google, this is a problem with indentation. I've tried multiple ways of indenting this; I can fix the syntax, but I can't get the logic correct.
Let's fix your immediate issue: you have an else with no corresponding if statement. Syntactically, this is because you have an intervening "out-dented" statement, the print, which terminates your series of ifs.
Logically, this is because you have two levels of decision: "Is this a number 0-20?", and "Within that range, how big is it?" The problem stems from writing only one level of ifs to make this decision. To keep close to your intended logic flow, write a general if on the outside, and encapsulate your small/medium/large decision and print within that branch; in the other branch, insert your "none of the above" statement:
n = int(input("number= "))
if 0 <= n <= 20:
if n < 5:
a = "small"
elif n < 10:
a = "medium"
else:
a = "large"
print("this number is", a)
else:
print("that's not a number from 0 to 20")
You should try something like
n = int(input("number= "))
if 0 <= n < 5:
a = "small"
elif 5 <= n < 10:
a = "medium"
elif 10 <= n <= 20:
a = "large"
else:
a = "not a number from 0 to 20"
print("this number is",a)
The print statement before the else statement needs to either be removed or indented to match:
a= "large"
You've syntax (indentation) error:
n = int(input("number= "))
if 0 <= n < 5:
a = "small"
if 5 <= n < 10:
a = "medium"
if 10 <= n <= 20:
a = "large"
#print("this number is",a) indentation error in this line
else:
print("thats not a number from 0 to 20")
You can use also use following code
n = int(input("number= "))
if 10 <= n <= 20:
a = "large"
print("this number is",a)
elif 5 <= n < 10:
a = "medium"
print("this number is",a)
elif 0 <= n < 5:
a = "small"
print("this number is",a)
else:
print("thats not a number from 0 to 20")
The problem is with the print statement.
It is indented on the same level as the if block and thus, the if block ends on line containing the print statement.
Thus, the else on the next line is incorrect.
To achieve what you are trying, you should do something like this:
n = int(input("number= "))
if 0 <= n < 5:
a = "small"
elif 5 <= n < 10:
a = "medium"
elif 10 <= n <= 20:
a = "large"
else:
print("not between 0 and 20")
print("The number is", a)
The print statement needs to be placed after the else block. Also, its best to use elif statements than if statements in a situation like this.
n = int(input("Enter a number between 0 and 20: "))
if 0 <= n <= 5:
a = "small."
elif n <= 10:
a = "medium."
elif n <= 20:
a = "large."
else:
a = "invalid / out of range."
print("This number is ", a)
I try to understand why I get unreasonable result from the following if:
def print_if_neg (a,b):
if a < 0 != b < 0:
print "Only One Neg"
else:
print "0 or 2"
print_if_neg(1,1)
print_if_neg(-1,1)
print_if_neg (1,-1)
print_if_neg(-1,-1)
I get 3 times 0 or 2 and then last one Only One Neg.
What is the order of this complicated condition?
I've tried this:
if (a < 0) != (b < 0):
and it's ok but I'm trying to understand why above doesn't work.
You need parentheses due to operator precedence
def print_if_neg (a,b):
if (a < 0) != (b < 0):
print "Only One Neg"
else:
print "0 or 2"
As CoryKramer pointed out, the operator precedence is making the difference.
Your code is equivalent to this:
def print_if_neg (a,b):
if a < (0 != b) < 0:
print "Only One Neg"
else:
print "0 or 2"
Because != has higher precedence than < by language definition.
So, use () to force the precedence that you need:
def print_if_neg (a,b):
if (a < 0) != (b < 0):
print "Only One Neg"
else:
print "0 or 2"
Also, FYI you are coding the xor operator.
Due to operator precedence you need to place the two conditions in parentheses for your expected results. Otherwise the comparison operators are solved, checking for 0 != b in your code, which is not what you expect.
def print_if_neg (a,b):
if (a < 0) != (b < 0):
print ("Only One Neg")
else:
print ("0 or 2")
print_if_neg(1,1)
print_if_neg(-1,1)
print_if_neg (1,-1)
print_if_neg(-1,-1)
Note that all comparison operators have the same precedence and comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y AND y <= z
This is because condition a < 0 != b < 0 means a < 0 AND 0 != b AND b < 0 First of all when a >= 0 first condition evaluates to False and so nothing else gets evaluated. Then, if a is <0 but b=1 last condition in the chain is False. Therefore your chained condition is False 3 out of 4 times.
This is well explained in section 6.10 of Python documentation.
From this, you could make it more readable imo:
from operator import xor
def print_if_neg (a, b):
if xor(a < 0, b < 0):
print "Only One Neg"
else:
print "0 or 2"
import numpy as np
import random
i = random.randint(1,100)
if i > 0 and i <16:
print ("Broken")
else if i > 16 and i > 100
print ("Not broken")
I am trying to make it if the number is between 1 to 15 the racquet is broken but if it is 16-100 it is not broken.
It says it is invalid syntax in python.
Why is it invalid syntax?
You appear to be trying to "fold" a nested if statement into its containing if statement, C-style:
if (i > 0 && i < 16)
printf("Broken\n");
else
if (i > 16 && i < 100)
printf("Not broken\n");
Because the whitespace isn't significant, the above is equivalent to
if (i > 0 && i < 16)
printf("Broken\n");
else if (i > 16 && i < 100)
printf("Not broken\n");
giving the illusion of an else if clause.
In Python, indentation is significant, so you can't pull the same trick as in C. Instead, Python has an explicit elif clause that you can use to check multiple conditions in a single if statement.
if i > 0 and i < 16:
print("Broken")
elif i > 16 and i < 100:
print("Not broken")
This is semantically equivalent to
if i > 0 and i < 16:
print("Broken")
else:
if i > 16 and i < 100:
print("Not broken")
but nicer looking.
You've got 2 SyntaxErrors:
There is no else if in Python, just elif
You need a : after the conditions.
And a logical mistake:
i > 100 can never be True.
Then you also don't need and here, you could just use:
import random
i = random.randint(1,100)
if i < 16:
print ("Broken")
else:
print ("Not broken")
There is also the shortened version of i > 0 and i < 16:
if 0 < i < 16:
print ("Broken")
elif 16 < i <= 100: # compare to "<= 100" instead of "> 100"
print ("Not broken")
In Python, you use elif instead of else if. You also need a colon at the end of your else if line.
It should be:
elif i > 16 and i > 100:
elif and with ":" in the end