-3

If I execute the codes below without if name == 'main', nothing is printed on the screen. That is, if name == 'main' seems to be essential. What is the function of if name == 'main'?

# if __name__ =='__main__':
       # main()
def input_celsius_value():
    value = float(input("input celsius for converting it to fahrenheit : "))
    return value

def convert_celsius_fahrenheit(celsius_value):
    fahrenheit_value = ((9/5)*celsius_value)+32
    return fahrenheit_value

def print_fahrenheit_value(celsius_value, fahrenheit_value) :
    print("celsius temperature : %f" %celsius_value)
    print("fahrenheit temperature : %f" %fahrenheit_value)

def main():
    print("This program converts celsius to fahrenheit")
    print("============================")
    celsius_value = input_celsius_value()
    fahrenheit_value = convert_celsius_fahrenheit(celsius_value)
    print_fahrenheit_value(celsius_value, fahrenheit_value)
    print("===========================")
    print("This program ended")


if __name__ == '__main__':
       main()
Pani
  • 1,317
  • 1
  • 14
  • 20
min min
  • 13
  • 1

1 Answers1

0

Without those 2 lines of code

if __name__ == '__main__':
       main()

there is no function called, you just define 4 functions so nothing is executed. When the interpreter runs a source file it runs all the code in it. Even just having main() without if __name__ == '__main__': will still execute your function. __name__ is just a special variable that gets populated depending on what is being executed (the name of the class/function/method etc). When you run a new file, the interpreter initializes it to '__main__' and you can use that as an entry point for your program.

Pani
  • 1,317
  • 1
  • 14
  • 20
  • I can't understand this sentence. Can you elaborate more on it? __name__ is just a special variable that gets populated depending on what is being executed (the name of the class/function/method etc) – min min Jun 18 '20 at 10:44
  • Python has some special variables. When your script is runing the variable `__name__` always holds the name of the class/function/.. executed. At first this is initialized with `'__main__'`. – Pani Jun 18 '20 at 17:55