__name__ == '__main__' in test class

I am learning testing using unittest module. At the end of a test script, there is this code

if __name__ == '__main__': 

I get that it is asking if the script is running as a main program. But I wonder what defines a main program? unittest module and a class being test are imported. Is it that the test class that implements the test to the tested class is within the script?

But most importantly, why do I need to write that code at the end?

Also I have a different question regarding dictionaries.

For ‘for’ looping dictionaries, it seems to need .value(), .keys(), .items(). These seem to convert dictionaries into lists. Does that mean ‘for’ loop only iterates lists?
I understand ‘for’ loop iterates dictionaries’ keys, but I wished to reach values directly. But it seems dictionaries have to be converted into lists first in order to reach values.

You must select a tag to post in this category. Please find the tag relating to the section of the course you are on E.g. loops, learn-compatibility

When you ask a question, don’t forget to include a link to the exercise or project you’re dealing with!

If you want to have the best chances of getting a useful answer quickly, make sure you follow our guidelines about how to ask a good question. That way you’ll be helping everyone – helping people to answer your question and helping others who are stuck to find the question and answer! :slight_smile:

From my understanding, this is to determine the code that runs only when the script is run directly/independently, not as a module inside another script.

So for example, let’s say you have a file called my_program.py. If you run it directly in the terminal like
python my_program.py all the code after if __name__ == '__main__': will run.
However, if you import my_program in another script, then that code will not run.

Dictionaries in python are a form of hash map or table. That means to be fast, it has to store items in the simplest and most efficient way possible. That’s why you are only able to access keys directly, because the dictionary in a way only directly stores the keys. The values are then connected to those keys.
You can read more about it here as a general concept and here about the python implementation.