This question already has answers here:
Why does python use 'else' after for and while loops?
(24 answers)
Closed 9 years ago.
I can run the below python script without errors.
for n in range(3):
print n
else:
print "done"
But I am puzzled about the else without a matching if.
It does not make sense.
Can some one explain why this works ?
The else clause of for and while only executes if the loop exits normally, i.e. break is never run.
for i in range(20):
print i
if i == 3:
break
else:
print 'HAHA!'
And the else clause of try only executes if no exception happened.
try:
a = 1 / 2
except ZeroDivisionError:
do_something()
else:
print '/golfclap'
The body of the else is executed after the for loop is done, but only if the for loop didn't terminate early by break statements.
Related
This question already has answers here:
Why doesn't the main() function run when I start a Python script? Where does the script start running (what is its entry point)?
(5 answers)
Closed 11 months ago.
This post was edited and submitted for review 11 months ago and failed to reopen the post:
Original close reason(s) were not resolved
I am writing a function which is supposed to get the user's response, yet when I run the file nothing happens, its just an empty screen, how do I fix that? I tried searching up in stackoverflow but I couldnt find what im looking for, thanks in advance :)
def get_user_response():
while True:
try:
print ('Enter the number of clickbait headlines to generate: (0 to exit)')
user = int(input('> '))
print ('HEADLINES')
if user == 0:
for x in range (0,4):
l = "Exiting Program" + "." * x
print (l, end="\r")
sleep(1)
break
else:
print ('a')
except:
print ('Invalid - Enter an integer')
You defined a function but never called it anywhere. That's why the program is not running in the first place. Just write
get_user_response()
anywhere outside of the function.
Also consider wrapping only the user input line into the try except statement, otherwise you will literally catch every possible error that might occur in your function without ever getting an error message.
def get_user_response(trueorfalse):
while trueorfalse:
.....your codes
get_user_response(True)
your function should have arg like thaht
This question already has answers here:
Why does python use 'else' after for and while loops?
(24 answers)
Closed 3 years ago.
I already have a lot of experience in Python, but recently I've seen some people using else at the end of a while or for block. I was very curious and decided to test:
for i in range(2):
print(i)
else:
print("Something...")
Output:
0
1
Something...
Using or not else, the code will execute the same way, so what's the use of this?
else after a for or while block will execute if and only if the block terminates normally. If you leave through a break or exception, that else block gets skipped.
for i in range(2):
print(i)
break
else:
print("Something...")
Output:
0
This question already has answers here:
Why doesn't exec("break") work inside a while loop
(6 answers)
Closed 3 years ago.
A recent question made me think if it is possible to do something like:
def defA(flag) :
return "value = 'yes'" if flag else "continue"
flag = False
#n can be a reasonable number like 100
for x in range(n):
#some logic that may change the flag
exec(defA(flag))
here, you got a variable assignment if the flag is true, or continue the for loop otherwise, but it gives me an odd error:
SyntaxError: 'continue' not properly in loop
Is it possible or should I let it go?
Because exec doesn't carry the context over to the statement being executed.
pass can be used anywhere, so the context doesn't matter. continue can only be used in the context of a loop, but that context is not available to exec.
You can only use continue in an exec statement if the loop itself is also part of the executed code:
f = 'for x in range(n): if(flag) continue' exec f
In other words, you can only use exec for complete statements, where a single continue (or break) is not complete.
This question already has answers here:
How to check variable against 2 possible values?
(6 answers)
How to test multiple variables for equality against a single value?
(31 answers)
Closed 3 years ago.
i have been following tutorials on W3Schools and have decided to make a calculator with Python. I have used a input for the input and a if statement to register whether it says "quit" to stop the calculator or if it is a number to add it to an array. But every single time i run it, it will return the Quitting message which is only in the if statement even if i put a result that should be in the else code. Thanks for the help btw! Here's my code.
print("Calculator")
NumberArray = []
InputNumber = input()
if InputNumber == "Quit" or "quit":
#Calculate()
print("Quitting... ")
exit()
else:
print(InputNumber) #Just to debug it!
The two choices in your if statement are evaluated independently, and "quit" evaluates to true. What you wanted to do was:
print("Calculator")
NumberArray = []
InputNumber = input()
if InputNumber in ("Quit", "quit"):
#Calculate()
print("Quitting... ")
exit()
else:
print(InputNumber) #Just to debug it!
This question already has answers here:
Else clause on Python while statement
(13 answers)
Closed 7 years ago.
I was going through this. Coming from C environment, it hit me right in the face with utter surprise and disbelief. And, then I tried it for myself::
bCondition = True
while bCondition:
print("Inside while\n")
bCondition = False
else:
print("Inside else\n")
print("done\n")
This code renders the below output,
#Output
Inside while
Inside else
done
Ideone link
Now, my question is, Why? why do we need this? Why both the blocks are executed? Isn't if and else were made for each other, then what use case will make this design a useful design to implement?
Again if we just change the code to incorporate a break, the behavior is more mysterious. Ideone Link.
bCondition = True
while bCondition:
break
else:
print("Inside else\n")
print("done\n")
This code renders the below output,
#Output
done
Why both of the blocks are skipped? Isn't break made to break out of the loop only, then why is it breaking out of the else block?
I went through the documentation too, couldn't clear my doubts though.
The use of the else clause after a loop in python is to check whether some object satisfied some given condition or not.
If you are implementing search loops, then the else clause is executed at the end of the loop if the loop is not terminated abruptly using constructs like break because it is assumed that if break is used the search condition was met.
Hence when you use break, the else clause is not evaluated. However when you come out of the loop naturally after the while condition evaluates to false, the else clause is evaluated because in this case it is assumed that no object matched your search criteria.
for x in data:
if meets_condition(x):
print "found %s" % x
break
else:
print "not found"
# raise error or do additional processing