control-flow

Python simple loop of averages only returns first item

Python simple loop of averages only returns first item Question: I wrote a code to calculate an average, but it takes only the first item in the list. I want to input a list of key=value and it should add all the values and then divide by the total number, so it gives me the …

Total answers: 2

Python Walrus Operator in While Loops

Python Walrus Operator in While Loops Question: I’m trying to understand the walrus assignment operator. Classic while loop breaks when condition is reassigned to False within the loop. x = True while x: print(‘hello’) x = False Why doesn’t this work using the walrus operator? It ignores the reassignment of x producing an infinite loop. …

Total answers: 2

How to determine if an exception was raised once you're in the finally block?

How to determine if an exception was raised once you're in the finally block? Question: Is it possible to tell if there was an exception once you’re in the finally clause? Something like: try: funky code finally: if ???: print(‘the funky code raised’) I’m looking to make something like this more DRY: try: funky code …

Total answers: 6

Python: avoiding if condition for this code?

Python: avoiding if condition for this code? Question: for the following code a =func() if a != None: b.append(a) a can be assigned to None, is there a way to avoid the if statement and only use one line of code? original problem is the following import xml.etree.ElementTree as etree r = etree.parse(f).getroot() b = …

Total answers: 8

How to exit an if clause

How to exit an if clause Question: What sorts of methods exist for prematurely exiting an if clause? There are times when I’m writing code and want to put a break statement inside of an if clause, only to remember that those can only be used for loops. Lets take the following code as an …

Total answers: 15

How can I break out of multiple loops?

How can I break out of multiple loops? Question: Given the following code (that doesn’t work): while True: # Snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok.lower() == "y": break 2 # This doesn’t work 🙁 if ok.lower() == "n": break # Do more processing with menus and …

Total answers: 39