In python, is there a difference between say:
if text == 'sometext':
print(text)
if text == 'nottext':
print("notanytext")
and
if text == 'sometext':
print(text)
elif text == 'nottext':
print("notanytext")
Just wondering if multiple ifs could cause any unwanted problems and if it would be better practice to use elifs.
Multiple if's means your code would go and check all the if conditions, where as in case of elif, if one if condition satisfies it would not check other conditions..
An other easy way to see the difference between the use of if and elif is this example here:
def analyzeAge( age ):
if age < 21:
print "You are a child"
if age >= 21: #Greater than or equal to
print "You are an adult"
else: #Handle all cases where 'age' is negative
print "The age must be a positive integer!"
analyzeAge( 18 ) #Calling the function
>You are a child
>The age must be a positive integer!
Here you can see that when 18 is used as input the answer is (surprisingly) 2 sentences. That is wrong. It should only be the first sentence.
That is because BOTH if statements are being evaluated. The computer sees them as two separate statements:
The first one is true for 18 and so "You are a child" is printed.
The second if statement is false and therefore the else part is
executed printing "The age must be a positive integer".
The elif fixes this and makes the two if statements 'stick together' as one:
def analyzeAge( age ):
if age < 21 and age > 0:
print "You are a child"
elif age >= 21:
print "You are an adult"
else: #Handle all cases where 'age' is negative
print "The age must be a positive integer!"
analyzeAge( 18 ) #Calling the function
>You are a child
Edit: corrected spelling
def multipleif(text):
if text == 'sometext':
print(text)
if text == 'nottext':
print("notanytext")
def eliftest(text):
if text == 'sometext':
print(text)
elif text == 'nottext':
print("notanytext")
text = "sometext"
timeit multipleif(text)
100000 loops, best of 3: 5.22 us per loop
timeit eliftest(text)
100000 loops, best of 3: 5.13 us per loop
You can see that elif is slightly faster. This would be more apparent if there were more ifs and more elifs.
Here's another way of thinking about this:
Let's say you have two specific conditions that an if/else catchall structure will not suffice:
Example:
I have a 3 X 3 tic-tac-toe board and I want to print the coordinates of both diagonals and not the rest of the squares.
I decide to use and if/elif structure instead...
for row in range(3):
for col in range(3):
if row == col:
print('diagonal1', '(%s, %s)' % (i, j))
elif col == 2 - row:
print('\t' * 6 + 'diagonal2', '(%s, %s)' % (i, j))
The output is:
diagonal1 (0, 0)
diagonal2 (0, 2)
diagonal1 (1, 1)
diagonal2 (2, 0)
diagonal1 (2, 2)
But wait! I wanted to include all three coordinates of diagonal2 since (1, 1) is part of diagonal 2 as well.
The 'elif' caused a dependency with the 'if' so that if the original 'if' was satisfied the 'elif' will not initiate even if the 'elif' logic satisfied the condition as well.
Let's change the second 'elif' to an 'if' instead.
for row in range(3):
for col in range(3):
if row == col:
print('diagonal1', '(%s, %s)' % (i, j))
if col == 2 - row:
print('\t' * 6 + 'diagonal2', '(%s, %s)' % (i, j))
I now get the output that I wanted because the two 'if' statements are mutually exclusive.
diagonal1 (0, 0)
diagonal2 (0, 2)
diagonal1 (1, 1)
diagonal2 (1, 1)
diagonal2 (2, 0)
diagonal1 (2, 2)
Ultimately knowing what kind or result you want to achieve will determine what type of conditional relationship/structure you code.
elifis just a fancy way of expressing else: if,
Multiple ifs execute multiple branches after testing, while the elifs are mutually exclusivly, execute acutally one branch after testing.
Take user2333594's examples
def analyzeAge( age ):
if age < 21:
print "You are a child"
elif age > 21:
print "You are an adult"
else: #Handle all cases were 'age' is negative
print "The age must be a positive integer!"
could be rephrased as:
def analyzeAge( age ):
if age < 21:
print "You are a child"
else:
if age > 21:
print "You are an adult"
else: #Handle all cases were 'age' is negative
print "The age must be a positive integer!"
The other example could be :
def analyzeAge( age ):
if age < 21:
print "You are a child"
else: pass #the if end
if age > 21:
print "You are an adult"
else: #Handle all cases were 'age' is negative
print "The age must be a positive integer!"
In your above example there are differences, because your second code has indented the elif, it would be actually inside the if block, and is a syntactically and logically incorrect in this example.
Python uses line indentions to define code blocks (most C like languages use {} to enclose a block of code, but python uses line indentions), so when you are coding, you should consider the indentions seriously.
your sample 1:
if text == 'sometext':
print(text)
elif text == 'nottext':
print("notanytext")
both if and elif are indented the same, so they are related to the same logic.
your second example:
if text == 'sometext':
print(text)
elif text == 'nottext':
print("notanytext")
elif is indented more than if, before another block encloses it, so it is considered inside the if block. and since inside the if there is no other nested if, the elif is being considered as a syntax error by Python interpreter.
When you use multiple if, your code will go back in every if statement to check the whether the expression suits your condition.
Sometimes, there are instances of sending many results for a single expression which you will not even expect.
But using elif terminates the process when the expression suits any of your condition.
Here's how I break down control flow statements:
# if: unaffected by preceding control statements
def if_example():
if True:
print('hey')
if True:
print('hi') # will execute *even* if previous statements execute
will print hey and hi
# elif: affected by preceding control statements
def elif_example():
if False:
print('hey')
elif True:
print('hi') # will execute *only* if previous statement *do not*
will print hi only because the preceding statement evaluated to False
# else: affected by preceding control statements
def else_example():
if False:
print('hey')
elif False:
print('hi')
else:
print('hello') # will execute *only* if *all* previous statements *do not*
will print hello because all preceding statements failed to execute
In the case of:
if text == 'sometext':
print(text)
if text == 'nottext':
print("notanytext")
All the if statements at the same indentation level are executed even if only the first if statement is True.
In the case of:
if text == 'sometext':
print(text)
elif text == 'nottext':
print("notanytext")
When an if statement is True, the preceding statements are omitted/ not-executed.
Related
str=")(hi)(hello))"
lcount=0
rcount=0
for i in str:
print(i)
if i == "(":
lcount+=1
if i == ")":
rcount+=1
print(lcount, rcount)
if lcount == rcount:
print("there's an even number of ( and )s")
if i[0] == ")":
print("invalid input")
right now i can make it so that it will print "invalid input" when the first character is a closing bracket, but i can't get it to work for all that don't have a corresponding (
Here is what I suggested (plus realizing what #JohnGordon is telling you when I wrote the code):
str=")(hi)(hello))"
count = 0
for i in str:
if i == "(":
count += 1
elif i == ")":
count -= 1
if count < 0:
break
if count == 0:
print("there's an even number of ( and )s")
else:
print("invalid input")
if i[0] == ")":
print("invalid input")
The code snippet above checks the variable i[0], which in this case stores the latest & last character in the for loop above. Which in your case would store ) and the "invalid input" statement will be printed, this statement will be printed as long as you end your input string with ). Which I believe is something you do not want.
if lcount == rcount and mystr[0] != ")":
print("there's an even number of ( and )s")
else:
print("invalid input")
Assuming that you are checking for the first character if it starts with an open bracket, make the change in variable as you can see above. Also, I highly recommend avoiding the variable str when naming your variable.
Here's another possible soluton:
string = ")(hi)(hello))"
# Count left and right parentheses, then compare the result
# Raise a ValueError (with a custom message) if counts aren't equal.
if string.count("(") != string.count(")"):
raise ValueError("Unbalanced parentheses detected!")
Also, don't use str, list, bool, etc., as variable names and that can cause confusion and havoc.
Question 1:
Just tried to execute the program but i am getting syntax error
i=input('Enter the value of i')
for j in range(10):
if i==j:
print'The value of i is %d'%(i)
elif i!=j:
print'Please enter a valid value'
else:
print 'This is not a number'
The difference between the below two codes is that code one will ask for input once and then loop trying to compare, while code two will ask for input each loop (10x)...
If your code is really indented as you put it here, the reason you are getting a syntax error is that your elif and else blocks are indented too far. Another problem with your code is that i can be either equal or not equal to j. There is no third option. Another problem is that the first time it comes across a number that is not equal to the number typed, it will say that it is not a valid value. Also, just saying "Please enter a valid value" will not make it so. Here is a better version of your code:
i = None
while True:
i = input("Enter the value of i")
if i.isdigit():
if int(i) in range(10):
print "The value of i is %d" % i
else:
print "Please enter a valid value"
else:
print "This is not a number"
As for question 2, the difference between the two is that in the first, i=input('Enter the value of i') will be executed before the loop, and in the second it will be executed for each iteration of the loop. (That is, one time for each time the loop is executed. Because range(10) returns ten items, it runs ten times.) More about for loops here, here, and here
You appear to be having a syntax error because of inconsistent levels of indentation in your code. Please try the following instead and adjust the program to suit whatever your needs might be.
#! /usr/bin/env python3
import sys
def main():
loop = True
while loop:
try:
i = int(input('Enter of the value of i: '))
except EOFError:
sys.exit()
except ValueError:
print('This is not a number')
else:
if 0 <= i <= 9:
print('The value of i is', i)
loop = False
else:
print('Please enter a valid value')
if __name__ == '__main__':
main()
What does the following code print? I know the answer is TIME GREAT. But I don't understand why it isn't Right Cheer. When it sets the score as 10.
score = 10
if score < 10:
print ("NOW")
if score > 2:
print ("RIGHT")
elif score == 10:
print ("CHEER")
else:
print ("TIME")
print ("GREAT")
Your indentation is wrong and you need all elif's after the first if, your first if evaluates to False and the fact you have the others nested means they never get evaluated and you go straight to the else block:
score = 10
if score < 10:
print ("NOW")
elif score > 2:
print ("RIGHT")
elif score == 10:
print ("CHEER")
else:
print ("TIME")
print ("GREAT")
Because input score is 10, which fails the if condition, and will jump to else part. Hence will print, TIME GREAT
I just had a quick question, for the following simulation, if one event happens , lets say birth would it automatically increase the time_elapsed, or will it go to death and check the death would happen and do that?
while time_elapsed < end_time :
event=birth () +death () +infection()
choice=random.random()*event
choice -= birth()
time_elapsed += random.expovariate(event)
if choice < 0 :
do_birth()
continue
choice -= death()
if choice < 0:
do_death()
continue
choice -= total_infection_rate()
if choice < 0:
do_infection()
continue
In your code above, it will check all the conditional statments until any one evaluates to True. If it does, it will execute the code in that block and then the continue will jump back to the start of the loop, skipping all the other if statements (regardless of whether they would have been True or not). If you want to perform only one of the cases, you would do it as:
if number >= 0:
print('Number is positive')
else:
print('Number is negative')
Here, python will evaluate the if number >= 0 block and if it is True, it will print the 'Number is positive' and then skip the else statement. If if number >= 0 block had evaluated to False, python would simply execute the code in the else block and then move on.
For more detailed cases, you can also use elif. Here is a similar example:
if number > 0:
print('Number is positive')
elif number < 0:
print('Number is negative')
else:
print('Number is 0')
It follows the same logic. Python will start at the top of the block and keep evaluating each condition in the if/elif blocks until any condition evaluates to True, at which point it will execute the code under that block and then skip all the other conditional statements in that group.
behavioural_level is defined as raw_input 1, 2 or 3.
What's going on here?
def summary_behaviour(x):
if behaviour_level == 1:
x = random.randint(0,1)
if x == 0:
return " "+str(first_name)+" has a rather "+str(shy[random.randint(0,(len(shy)-1))])+" personality. This has certain advantages. One is that "+str(he_she(gender))+" doesn't easily "+str(lose_focus[random.randint(0,(len(lose_focus)-1))])+": however, "+str(he_she(gender))+" can be a litte quiet at times."
else:
if x == 1:
return " Because of "+str(first_name)+"'s "+str(shy[random.randint(0,len(shy)-1)])+" character "+str(he_she(gender))+" can be a little quiet sometimes. On the plus side, however, "+str(he_she(gender))+" doesn't "+str(lose_focus[random.randint(0,len(lose_focus)-1)])+" very easily."
elif behaviour_level == 2:
x = random.randint(2,3)
if x == 2:
return str(first_name)+" is usually quite "+str(loud[random.randint(0,(len(loud)-1))])+" in class, and this has advantages and disadvantages. "+str(first_name)+" loves to involved and enjoys speaking, but sometimes "+str(hes_shes(gender))+" too "+str(loud[random.randint(0,(len(loud)-1))])+" to fully concentrate. This is common though. "
else:
if x == 3:
return " Because of "+str(first_name)+"'s "+str(loud[random.randint(0,len(loud)-1)])+" character "+str(he_she(gender))+" is "+str(adjective(int(science_level)))+" at speaking up and volunteering. Occasionally, "+str(his_her(gender))+" "+ str(loud[random.randint(0,len(loud)-1)])+ " nature can cuase "+str(him_her(gender))+ " to "+str(lose_focus[random.randint(0,len(lose_focus)-1)])+" but, that's fairly normal at "+str(his_her(gender))+" age."
else:
if behaviour_level == 3:
x = random.randint(4,5)
if x == 4:
return " I would descirbe "+str(fisrt_name)+" as a "+(str(well_mannered[random.randint(0,len(well-mannered)-1)]))+" child who is easy to teach. Rarely is "+str(he_she(gender))+" too "+str(loud[random.randint(0,(len(loud)-1))])+" to focus or too "+str(shy[random.randint(0,(len(shy)-1))])+" too speak up."
else:
if x == 5:
return str(first_name)+" a "+ (str(well_ma
Your nests are fine.
raw_input() returns a string. It doesn't look like you have converted it into an integer, so your function goes into the first else: bit of your if/else statement, because behaviour_level != 1 (but rather it equals "1")
Next, if behaviour_level == 3:. As the input is a string, not an integer, this is not True. And as there is no else, the function defaults to return None.
To fix this, you can use the int() function, which converts a string to an integer.
You can use
int(behaviour_level) == 1,2 or 3
to compare as 1 2 and 3 are integers and raw_input would return a string.
Also, Instead of doing
else:
if condition:
"""statements"""
You can simply use:
elif condition:
"""statements"""