Format Q - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Format Q (/thread-23776.html) |
Format Q - ebolisa - Jan-16-2020 Hi, What's the difference between these two codes? Does one run faster than the other or it's just a question of correct format? TIA # Import modules from picamera import PiCamera import time if __name__ == '__main__': # Instantiate PiCamera object camera = PiCamera() # Sleep for 5 seconds before taking the photo time.sleep(5) # Take photo and save it as 'test.jpg' camera.capture('./test.jpg') # Import modules from picamera import PiCamera import time # Instantiate PiCamera object camera = PiCamera() # Sleep for 5 seconds before taking the photo time.sleep(5) # Take photo and save it as 'test.jpg' camera.capture('./test.jpg') RE: Format Q - micseydel - Jan-16-2020 The first one will run slightly slower, because it does more logic. That's not really important though, as the time cost is going to be absurdly small, and paid infrequently. The difference between the codes is that if you import the first one, the if-block won't run. That's desirable if you're trying to write a script which you want to be both runnable and importable. I often start my code with this template: #!/usr/bin/env python3 def main(): pass if __name__ == "__main__": main()Typically I write everything in the main function, unless I'm iterating a lot on a script in which case I omit the main function so that I can use python -i myscript.py and examine the variables.
|