The code below is from hackermeter.com and I'm not sure what to think of it. Is the variable i being passed implicitly to run() or does it expect more modification than just where it specifies?
import sys
def run():
# Code here!
for i in range(int(sys.stdin.readline())):
run()
I'd argue that this is a poor coding practice. The only reason run() has access to i is that i is global.
The following is arguably better as it will force the programmer to pass i into run() explicitly (if required):
import sys
def run():
# Code here!
def main():
for i in range(int(sys.stdin.readline())):
run()
if __name__ == '__main__':
main()
This is the code in the question:
import sys
def run():
# Code here!
for i in range(int(sys.stdin.readline())):
run()
i is defined in global scope (that is at the top level of the module), and so is accessible inside run. This is because essentially only functions and classes introduce a new local scope, so an iteration variable is a normal variable of its enclosing scope.
If run does access i, this creates the potential for an error if i has not already been defined (e.g. if a conditional statement prevented the loop from being executed at all).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With