0

I was typing a sample code. Where I defined temperature as the main function, but I was unable to run it. It closed automatically without any input prompt.

def temperature():
    number = input('Enter what you want\n')
    values = number.split(' ')
    temperature = values[0]
    unitin = values[1]
    unitout = values[-1]
    print(temperature, 'this', unitin, 'is', unitout, 'working')  # this is working is a test statemment i was unsure
    print('This is a test function', number)


def main():
    temperature()


if __name__ == "__main__":
    main()

this is the part of the code that ran. But as soon as I tried to change just the name of the main function it stopped working. I am not sure, does it only take the name "main"?

def readinput():
input_string = input('Enter what you want\n')
values = input_string.split(' ')
temperature = values[0]
unitin = values[1]
unitout = values[-1]
print(temperature, 'this', unitin, 'is', unitout, 'working')
print('This is a test function', input_string)


def temperature_converter():
    readinput()


if __name__ == "__temperature_converter__":
    temperature_converter()

This is the code that did not work. thank you.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241

2 Answers2

2

If you run your code on its own, the variable __name__ is automatically set to "__main__" by the interpreter. That does not have anything to do with your functions name. Have a look at What does if __name__ == "__main__": do?

This should work:

if __name__ == "__main__":
    temperature_converter()
CodeZero
  • 1,649
  • 11
  • 18
0

You're confusing the contents of the special variable __name__ that contains string '__main__' in case when the module is run by itself (as opposed to imported by another module) with the function main() -- these are totally unrelated things, and when you change the name of the function main() to whatever else you like, leave the string __main__ alone, as it is.

Or you may remove the line starting with if __name__ == completely, it should work without is as well.

lenik
  • 23,228
  • 4
  • 34
  • 43