Python Forum
Question about an infinite loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Question about an infinite loop
#5
(Mar-04-2018, 05:44 PM)Robo_Pi Wrote:
def my_method():
    return 0 # it's not necessary but you can do it
  
if __name__ == '__main__':
    import sys
    sys.exit(my_method())
However if I were to modify this code as follows it should never run at all, right?

This will run just fine.

When the python code runs as a program "__main__" string is assigned to the __name__ special variable.
If the same code is imported as a module, __name__ will contain the name of the module. Any .py file can be imported as a module.

The if __name__ == "__main__": statement is a convention in the Python coding. It checks if the file is running as a program, not imported as a module and if that is the case the code block is executed.
This is why the most of the python programmers are defining a main() function so if someone else looks at the code he/she knows what it contains. The code to run the file as a program.

Because this became almost standard in the Python coding most of the IDE programs generate it as a template.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Messages In This Thread
Question about an infinite loop - by Robo_Pi - Mar-04-2018, 04:45 AM
RE: Question about an infinite loop - by wavic - Mar-04-2018, 05:19 AM
RE: Question about an infinite loop - by Robo_Pi - Mar-04-2018, 05:44 PM
RE: Question about an infinite loop - by wavic - Mar-04-2018, 06:45 PM
RE: Question about an infinite loop - by Robo_Pi - Mar-04-2018, 08:42 PM
RE: Question about an infinite loop - by wavic - Mar-05-2018, 05:46 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
Shocked Why this code does not go into an infinite loop? 2367409125 2 905 Dec-02-2022, 08:22 PM
Last Post: deanhystad
  Need help with infinite loop & making hotkeys/shortcuts Graxum 1 1,209 Aug-22-2022, 02:57 AM
Last Post: deanhystad
  A question about 'Event loop is closed' fc5igm 2 2,274 Oct-05-2021, 02:00 AM
Last Post: fc5igm
Exclamation question about input, while loop, then print jamie_01 5 2,734 Sep-30-2021, 12:46 PM
Last Post: Underscore
  Infinite loop problem Zirconyl 5 3,047 Nov-16-2020, 09:06 AM
Last Post: DeaD_EyE
  for loop question KEYS 1 1,755 Oct-27-2020, 11:42 PM
Last Post: jefsummers
  Netmiko Loop question sc00ter 2 3,364 Oct-24-2020, 10:54 PM
Last Post: sc00ter
  using 'while loop' output going into infinite loop... amitkb 2 2,005 Oct-05-2020, 09:18 PM
Last Post: micseydel
  while loop question KEYS 2 2,059 Sep-26-2020, 11:02 PM
Last Post: KEYS
  New to programming, loop question tomyan 1 1,679 Sep-25-2020, 04:32 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020