New in python: What does or does not affect "if __name__ == '__main__':" [duplicate]

0

How about, I'm working with a simple example of a python book, with sockets, and punctually after declaring 2 functions, in what would be the main the following is put:

if __name__ == '__main__':
main()

My doubt is, in what affect the program put, or not put "if name == ' main ':" ?. I ask why I tried quintandolo, and leaving only the "main ()" and the execution was completed correctly, without affecting the code or result of the program for which it was programmed.

Thanks in advance.

    
asked by cnfs 29.10.2017 в 06:08
source

1 answer

2

Allows you to reuse code as if it were a module. I explain myself better with an example:

We have the following program:

# cat cuadrado.py
def alCuadrado(var):
    return var * var

if __name__ == '__main__':
    print "Standalone mode!!"
    print "42 al cuadrado es ==", alCuadrado(42)

This simple program has a function "alCuadrado" that returns the square of a number.

Now we have another program:

# cat code01.py 
import cuadrado

print "Usando cuadrado.py como modulo!"
print ("17 al cuadrado es == %i" % cuadrado.alCuadrado(17))

In this code, we import the first program as if it were a module, which allows us to use the functions defined in it, but we do not execute its "main program":

 # python2 code01.py 
Usando cuadrado.py como modulo!
17 al cuadrado es == 289

# python2 cuadrado.py
Standalone mode!!
42 al cuadrado es == 1764
    
answered by 29.10.2017 в 08:40