Conditional statements order of precedence - python

Firstly, I am a beginner in python. So i won't be able to understand complex stuff.
So I tried to make an age testing thing (it was for testing before I try to make a large one). I wrote a code where if the age is equal to 4, then it shows "yes". and if the age in range of 2 to 8, it will show "what". and if it is some thing else, it shows "wot". i want the priority of the first statement more than the second one, like if the first one is true, then skip the second one.
code:
if (age<8 and age>2):
print ("what")
if (a == 4):
print ("yes")
else:
print ("wot")

Try this code :
if age == 4 :
print('yes')
elif age < 8 and age > 2 :
print('what')
else :
print('wot')
python does not require round bracket in conditions.

You are looking for elif statement
if age == 4:
print('yes')
elif age > 2 and age <8:
print('what')
else:
print('wot')
All these three statements are exclusive, i.e. only one print call will be made, the one that gets a True evaluation first from top to bottom.

The precedence goes like this:
if then elif then else. Usually you would have one if and as many elifs you want and one or no else statements. In your case, you would like to have a if statement to check for age == 4 and elif age > 2 and age < 8 while else takes care of any other possible case.

In that case you should do:
if age == 4:
print('yes')
elif age < 8 and age > 2:
print('what')
else:
print('wot')
Then if the first conditional statement is true, the rest of the lines get skipped. If the first line fails, then it moves on to the second statement, etc...
Also, you used age as well as a for your age variable, that will also cause an issue.

As what the others have replied, you would be using an nested if condition in your case. In python, your first condition will start as if, followed by elif (it stands for else if) and else (which concludes what will happen if none of the previous conditions are met)
For example:
if condition 1:
print("hi")
elif condition 2:
print("bye")
else:
print("hello")
Note that in python, once the first condition is met, it will automatically perform the action specified under that particular condition and exit from the if statement (meaning the rest of the statement will be ignored).

Related

Does if/else statements require continue?

I am a beginner in Python and from what I understand, the continue statement in Python returns the control to the beginning of the while loop.
guesses = [0]
while True:
# we can copy the code from above to take an input
guess = int(input("I'm thinking of a number between 1 and 100.\n What is your guess? "))
if guess < 1 or guess > 100:
print('OUT OF BOUNDS! Please try again: ')
continue
# here we compare the player's guess to our number
if guess == num:
print(f'CONGRATULATIONS, YOU GUESSED IT IN ONLY {len(guesses)} GUESSES!!')
break
# if guess is incorrect, add guess to the list
guesses.append(guess)
# when testing the first guess, guesses[-2]==0, which evaluates to False
# and brings us down to the second section
if guesses[-2]:
if abs(num-guess) < abs(num-guesses[-2]):
print('WARMER!')
else:
print('COLDER!')
else:
if abs(num-guess) <= 10:
print('WARM!')
else:
print('COLD!')
Above is the code for the game called 'guess the number from 1 - 100'.
The first if statement where guess < 1 or guess > 100, it will print "Out of bounds!" and then continue which loops to the top of the code and asks for the user's input again.
But for the 3rd if statement where if guesses[-2]:, it does not require continue for neither if nor else.
Sorry if you do not understand what I am asking. But essentially, I want to know why 'continue' statement is not required after print('WARMER!), print('COLDER!'), print('WARM!') and print('COLD!').
guesses = [0]
while True:
# we can copy the code from above to take an input
guess = int(input("I'm thinking of a number between 1 and 100.\n What is your guess? "))
if guess < 1 or guess > 100:
print('OUT OF BOUNDS! Please try again: ')
continue
# here we compare the player's guess to our number
if guess == num:
print(f'CONGRATULATIONS, YOU GUESSED IT IN ONLY {len(guesses)} GUESSES!!')
break
# if guess is incorrect, add guess to the list
guesses.append(guess)
# when testing the first guess, guesses[-2]==0, which evaluates to False
# and brings us down to the second section
if guesses[-2]:
if abs(num-guess) < abs(num-guesses[-2]):
print('WARMER!')
**continue**
else:
print('COLDER!')
**continue**
else:
if abs(num-guess) <= 10:
print('WARM!')
**continue**
else:
print('COLD!')
**continue**
Note that all four of these print statements are the last of their execution branch.
Meaning, if guesses[-2] evaluates as true, than the else part won't be executed at all. Then, if abs(num-guess) < abs(num-guesses[-2]) evaluates to true, again - its else won't be executed. It means that for this execution branch the print('WARMER!') is the last statement of the loop and hence continue is not needed.
Same logic applies to all other 3 print statements.
In the case "guess < 1 or guess > 100" you want to skip the rest of the loop since you dont want to append the guess to the guesses list. Therefore you use continue.
The 'continue' statement is not required after print('WARMER!) etc because you dont need to skip any code afterwards. In this case because there wont be any lines executed after the print statement anyway.
First of all, if/else doesn't require continue. It's optional.
From what I understand you want to know why you used continue in the first if/else and not in the last if/else.
In the first one, after executing if statement it will transfer the control to while True: but for the last if/else statement it is not needed as the control will automatically go to while True: as it is the end of the loop and even if you had used continue it wouldn't have made a difference.
For further references
If you want to know why the continue is not always in if or else, this is due to the fact that when the operation arrives (true), the loop is exited and the code continues to run.

Syntax error on the "N" on line 18

I've been working on this simple program in Python just so I can start experimenting with Python and become more knowledgeable of Python and other programming languages in general by designing them in a way in which others can use them in an efficient manner without getting caught on the parts which make this code work. I've been doing this by having a simple program calculate "Angles in a triangle" as it's a simple subject. Recently, I replaced def(): commands with if statements as it cuts down typing to a minimum and making it generally easier for others however, when I try to run this code I get a syntax error message with N becoming highlighted on line 17.
def triangle():
N = int(input("Please enter the number of angles you currently have between 1 and 3: "))
if N == 1:
a = int(input("What's one of the angles?"))
b = int(input("What's the other angle in the triangle?"))
c = a + b
f = 180 - c
print(f)
print("If you'd like to continue, please type in triangle()")
elif N == 2:
a = int(input("What's the value of angle 1?"))
b = 180 - a
c = b /2
print(c)
print("If you'd like to continue, please type in triangle()")
else N == 3:
a = 180
b = 180 / 3
print(b)
print("If you'd like to continue, please type in triangle()")
But I'm getting a syntax error returned on elif N == 3:
Any tips would be great.
else does not have a condition.. remove it to just say
else:
or make it says
elif N == 3:
You have else N == 3:. That is not how the if..elif..else structure works - the else is a catch-all branch that is entered if none of the preceding if or elif conditions are satisfied. If you want to check specifically for N == 3 and no other values, use elif N == 3. If you want a catch-all condition, simply use else:.
elif N == 3:
Either you meant elif (which is Python for else..if), or else
If you meant plain else, it doesn't take a condition.
If you want to annotate that an else implies a certain condition is met, then I use a comment:
else: # N == 3
But that's considered bad style: only do that if you're sure N cannot have any other value than 1,2,3. In your case the user could also input any number 4,5,..,9 (or indeed 10 or larger, or indeed 0 or any negative number), and that will wrongly get handled by the N==3 branch.
Whereas if your last branch if elif N == 3, with no else-clause, invalid numbers will silently fail every branch in your tree.
So for completeness and sanity-checking, you might prefer to do:
...
elif N ==3:
# Handle N == 3 case
else:
print "Invalid number!"

When would it be more effective to use if/else combinations rather than elif?

In Learn Python the Hard Way, one of the student questions asks:
Can you replace elif with a sequence of if-else combinations?
You can in some situations, but it depends on how each if/else is written. It also means that Python will check every if-else combination, rather than just the first false ones like it would with if-elif-else.
When he says "in some situations," I was just wondering when it would be more effective to use those sequences to replace an elif.
EDIT: Is there any difference between how these two pieces of code will be executed?
print "You enter a dark room with two doors. Do you go through door #1 or door #2?"
door = raw_input("> ")
if door == "1":
print "Hello."
# More if/else here
# ...
# ...
if door == "2":
print "Hello again."
# More if/else here
# ...
# ...
else:
print "End."
print "You enter a dark room with two doors. Do you go through door #1 or door #2?"
door = raw_input("> ")
if door == "1":
print "Hello."
# More if/else here
# ...
# ...
elif door == "2":
print "Hello again."
# More if/else here
# ...
# ...
else:
print "End."
One situation in which a series of if statements can be substituted for an if...elif...else block is when each if statement contains a return:
def check(something):
if something == 1:
return "foo"
if something == 2:
return "bar"
return "n/a"
In that case, the return means that by the time the second if is reached, you know that the first condition was false, so any else or elif is redundant. Also, in that particular case, if you need to reorder the if statements, it's marginally easier because you don't have to worry about an elif clause ending up before the if clause, and so on.
An odd use, since python doesn't technically have an explicit switch statement, is to use a combination of ifs as a pseudo-switch with fallthrough.
I wouldn't technically recommend this normally, as it's kind of hard to debug and maintain, and not very pythonic, but it's an option where normal if/elif wouldn't be appropriate.
def do_something(x):
y = ""
if x == 1:
y += "This and "
if x == 1 or x == 2:
y += "That"
if x == 3:
y += "The Other"
return y
EDIT:
As for your code supplied, the main difference is in the logic that is created. A series of ifs will each be set to be evaluable so you may run into issues where you mung variables in ways that you're not expecting.
The if/elif will only evaluate until it hits a valid statement or the final else.
So the short answer would be that you MAY want a series of ifs instead of if/elifs if you're dealing with multiple triggers affecting multiple variables, when emulating a switch with fallthrough, or if it's short return statements on a per-if basis. Most of the time though an if/elif will be more correct and more efficient.
Also, on a compilation end, the compiler will probably be able to better handle branch prediction with if/elifs than a series of ifs.

error while passing the value in python when user enter the value [duplicate]

This question already has answers here:
error while passing the value in python
(2 answers)
Closed 8 years ago.
def row_minimum(x,L):
L=L
if x=='1':
row_minimum1=min(L[0],L[1],L[2],L[3],L[4])
return row_minimum1
elif x=='2':
row_minimum2=min(L[5],L[6],L[7],L[8],L[9])
return row_minimum2
elif x=='3':
row_minimum3=min(L[10],L[11],L[12],L[13],L[14])
return row_minimum3
table(L)
def user_input(y):
if y in ['1','2','3','A','B','C','D','E']:
condition = False
elif y !=['1','2','3','A','B','C','D','E']:
condition = True
while condition == True:
z=input("Enter a row (as a number) or a column (as and uppercase letter):")
if z in ['1','2','3','A','B','C','D','E']:
condition = False
return z
def menu(a,L):
if a==1:
display_table(L)
elif a==2:
x=input("Enter a row (as a number) or a column (as and uppercase letter):")
user_input(x)
print (user_input(x))
if user_input(x) in ['1','2','3']:
mini = row_minimum(x,l)
print ("2")
print("Minimum is:",row_minimum(x,L))
i am getting the value of user_input(x) to none instead i want it to take the value from the user and compare in the if statement and do the minimum.
You have a nested definition for user_input and the first one doesn't return anything, resulting in None being returned. Take out the first or second def.
Note that this is far from the only thing wrong with this program.
Looks like you have a logic issue in user_input() function. If I understood it right, you are trying to check if y is one of the row/column names and set condition to False in this case. Otherwise (if it is not in your list of allowed characters), you want to set the condition to True and re-prompt the user for correct input until she gives you the value you want.
If it is so, you better be checking y if it is NOT in the list. Your code, though, checks if y is not the LIST itself: y !=['1','2','3','A','B','C','D','E']. Even if the user gives you a good value, say 'B' it is still not equal to the list of strings ['1','2','3','A','B','C','D','E'], it is IN this list (thats what you should be checking for). I think, itll help if you rewrite the function to make it something like:
def user_input(y):
if y in ['1','2','3','A','B','C','D','E']:
condition = False
else:
condition = True
while condition == True:
z=input("Enter a row (as a number) or a column (as and uppercase letter):")
if z in ['1','2','3','A','B','C','D','E']:
condition = False
return z
You may also want to experiment with Python style guide and make this code look nicer ;)
Your user_input() function seems like a bad idea. As far as I can tell it is meant to check for bad input, and keeps asking for input until it gets good input. The problem is, it only returns if the initial input was bad, if the initial input was good, then the function does not return.
You can just get rid of this function altogether, since you end up checking the input anyway. you can just do:
def menu(a,L):
if a==1:
display_table(L)
elif a==2:
while True:
x=input("Enter a row (as a number) or a column (as and uppercase letter):")
print x
if x in ['1','2','3']:
mini = row_minimum(x,l)
print ("2")
print("Minimum is:",row_minimum(x,L))
break
elif x in ['A','B','C','D','E']:
whatever you want to do here
break

Else clause on Python while statement

I've noticed the following code is legal in Python. My question is why? Is there a specific reason?
n = 5
while n != 0:
print n
n -= 1
else:
print "what the..."
Many beginners accidentally stumble on this syntax when they try to put an if/else block inside of a while or for loop, and don't indent the else properly. The solution is to make sure the else block lines up with the if, assuming that it was your intent to pair them. This question explains why it didn't cause a syntax error, and what the resulting code means. See also I'm getting an IndentationError. How do I fix it?, for the cases where there is a syntax error reported.
The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won't be executed.
One way to think about it is as an if/else construct with respect to the condition:
if condition:
handle_true()
else:
handle_false()
is analogous to the looping construct:
while condition:
handle_true()
else:
# condition is false now, handle and go on with the rest of the program
handle_false()
An example might be along the lines of:
while value < threshold:
if not process_acceptable_value(value):
# something went wrong, exit the loop; don't pass go, don't collect 200
break
value = update(value)
else:
# value >= threshold; pass go, collect 200
handle_threshold_reached()
The else clause is executed if you exit a block normally, by hitting the loop condition or falling off the bottom of a try block. It is not executed if you break or return out of a block, or raise an exception. It works for not only while and for loops, but also try blocks.
You typically find it in places where normally you would exit a loop early, and running off the end of the loop is an unexpected/unusual occasion. For example, if you're looping through a list looking for a value:
for value in values:
if value == 5:
print "Found it!"
break
else:
print "Nowhere to be found. :-("
Allow me to give an example on why to use this else-clause. But:
my point is now better explained in Leo’s answer
I use a for- instead of a while-loop, but else works similar (executes unless break was encountered)
there are better ways to do this (e.g. wrapping it into a function or raising an exception)
Breaking out of multiple levels of looping
Here is how it works: the outer loop has a break at the end, so it would only be executed once. However, if the inner loop completes (finds no divisor), then it reaches the else statement and the outer break is never reached. This way, a break in the inner loop will break out of both loops, rather than just one.
for k in [2, 3, 5, 7, 11, 13, 17, 25]:
for m in range(2, 10):
if k == m:
continue
print 'trying %s %% %s' % (k, m)
if k % m == 0:
print 'found a divisor: %d %% %d; breaking out of loop' % (k, m)
break
else:
continue
print 'breaking another level of loop'
break
else:
print 'no divisor could be found!'
The else-clause is executed when the while-condition evaluates to false.
From the documentation:
The while statement is used for repeated execution as long as an expression is true:
while_stmt ::= "while" expression ":" suite
["else" ":" suite]
This repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the else clause, if present, is executed and the loop terminates.
A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and goes back to testing the expression.
The else clause is only executed when the while-condition becomes false.
Here are some examples:
Example 1: Initially the condition is false, so else-clause is executed.
i = 99999999
while i < 5:
print(i)
i += 1
else:
print('this')
OUTPUT:
this
Example 2: The while-condition i < 5 never became false because i == 3 breaks the loop, so else-clause was not executed.
i = 0
while i < 5:
print(i)
if i == 3:
break
i += 1
else:
print('this')
OUTPUT:
0
1
2
3
Example 3: The while-condition i < 5 became false when i was 5, so else-clause was executed.
i = 0
while i < 5:
print(i)
i += 1
else:
print('this')
OUTPUT:
0
1
2
3
4
this
My answer will focus on WHEN we can use while/for-else.
At the first glance, it seems there is no different when using
while CONDITION:
EXPRESSIONS
print 'ELSE'
print 'The next statement'
and
while CONDITION:
EXPRESSIONS
else:
print 'ELSE'
print 'The next statement'
Because the print 'ELSE' statement seems always executed in both cases (both when the while loop finished or not run).
Then, it's only different when the statement print 'ELSE' will not be executed.
It's when there is a breakinside the code block under while
In [17]: i = 0
In [18]: while i < 5:
print i
if i == 2:
break
i = i +1
else:
print 'ELSE'
print 'The next statement'
....:
0
1
2
The next statement
If differ to:
In [19]: i = 0
In [20]: while i < 5:
print i
if i == 2:
break
i = i +1
print 'ELSE'
print 'The next statement'
....:
0
1
2
ELSE
The next statement
return is not in this category, because it does the same effect for two above cases.
exception raise also does not cause difference, because when it raises, where the next code will be executed is in exception handler (except block), the code in else clause or right after the while clause will not be executed.
I know this is old question but...
As Raymond Hettinger said, it should be called while/no_break instead of while/else.
I find it easy to understeand if you look at this snippet.
n = 5
while n > 0:
print n
n -= 1
if n == 2:
break
if n == 0:
print n
Now instead of checking condition after while loop we can swap it with else and get rid of that check.
n = 5
while n > 0:
print n
n -= 1
if n == 2:
break
else: # read it as "no_break"
print n
I always read it as while/no_break to understand the code and that syntax makes much more sense to me.
thing = 'hay'
while thing:
if thing == 'needle':
print('I found it!!') # wrap up for break
break
thing = haystack.next()
else:
print('I did not find it.') # wrap up for no-break
The possibly unfortunately named else-clause is your place to wrap up from loop-exhaustion without break.
You can get by without it if
you break with return or raise → the entire code after the call or try is your no-break place
you set a default before while (e.g. found = False)
but it might hide bugs the else-clause knows to avoid
If you use a multi-break with non-trivial wrap-up, you should use a simple assignment before break, an else-clause assignment for no-break, and an if-elif-else or match-case to avoid repeating non-trival break handling code.
Note: the same applies to for thing in haystack:
Else is executed if while loop did not break.
I kinda like to think of it with a 'runner' metaphor.
The "else" is like crossing the finish line, irrelevant of whether you started at the beginning or end of the track. "else" is only not executed if you break somewhere in between.
runner_at = 0 # or 10 makes no difference, if unlucky_sector is not 0-10
unlucky_sector = 6
while runner_at < 10:
print("Runner at: ", runner_at)
if runner_at == unlucky_sector:
print("Runner fell and broke his foot. Will not reach finish.")
break
runner_at += 1
else:
print("Runner has finished the race!") # Not executed if runner broke his foot.
Main use cases is using this breaking out of nested loops or if you want to run some statements only if loop didn't break somewhere (think of breaking being an unusual situation).
For example, the following is a mechanism on how to break out of an inner loop without using variables or try/catch:
for i in [1,2,3]:
for j in ['a', 'unlucky', 'c']:
print(i, j)
if j == 'unlucky':
break
else:
continue # Only executed if inner loop didn't break.
break # This is only reached if inner loop 'breaked' out since continue didn't run.
print("Finished")
# 1 a
# 1 b
# Finished
The else: statement is executed when and only when the while loop no longer meets its condition (in your example, when n != 0 is false).
So the output would be this:
5
4
3
2
1
what the...
Suppose you've to search an element x in a single linked list
def search(self, x):
position = 1
p =self.start
while p is not None:
if p.info == x:
print(x, " is at position ", position)
return True
position += 1
p = p.link
else:
print(x, "not found in list")
return False
So if while conditions fails else will execute, hope it helps!
The better use of 'while: else:' construction in Python should be if no loop is executed in 'while' then the 'else' statement is executed. The way it works today doesn't make sense because you can use the code below with the same results...
n = 5
while n != 0:
print n
n -= 1
print "what the..."
As far as I know the main reason for adding else to loops in any language is in cases when the iterator is not on in your control. Imagine the iterator is on a server and you just give it a signal to fetch the next 100 records of data. You want the loop to go on as long as the length of the data received is 100. If it is less, you need it to go one more times and then end it. There are many other situations where you have no control over the last iteration. Having the option to add an else in these cases makes everything much easier.

Categories