This question already has answers here:
What does if __name__ == "__main__": do?
(45 answers)
Closed 2 years ago.
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()
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.
Related
When I try to run main() it returns "SyntaxError: invalid syntax" at print(f"Results from Sampling (n = {SAMPLES})")
in Python 3.7
SAMPLES = 1000
def main():
print(f"Results from Sampling (n = {SAMPLES})")
if __name__ == "__main__":
main()
If you copied and pasted your code as it is then there are 2 issues here.
1st is indentation second is syntax.
You can read about python indentation here: https://docs.python.org/2.0/ref/indentation.html
The __name should be changed to __name__
Code below should work
SAMPLES = 1000
def main():
print(f"Results from Sampling (n = {SAMPLES})")
if __name__ == "__main__":
main()
Following code works as expected. It takes two inputs and outputs the same
import sys
import threading
def main():
n = int(input("input n:"))
parents = list(map(int, input("input parents:").split()))
print("n is {0} and parents is {1}".format(n,str(parents)))
if __name__ == "__main__":
main()
The moment I add this additional code for enabling more depth for recursion and threading, it throws a value error. Inputs I give are '3' for the first input (without quotes) and '-1 0 1' for the second input (without quotes).
import sys
import threading
def main():
n = int(input("input n:"))
parents = list(map(int, input("input parents:").split()))
print("n is {0} and parents is {1}".format(n,str(parents)))
sys.setrecursionlimit(10**7) # max depth of recursion
threading.stack_size(2**27) # new thread will get stack of such size
threading.Thread(target=main).start()
if __name__ == "__main__":
main()
The main() function is called from two places.
First, From the thread main() function will be called
threading.Thread(target=main).start()
Second, the __main__ will be called. So here also the main() function is called.
if __name__ == "__main__":
main()
So you were asked to enter the "input n" two times. While entering the string value ('-1 0 1') the second time, you are giving value to the "input n" again. It's expecting int as input. So the issue is happening.
Code Fix:
Move the thread inside main and remove the existing main()
import sys
import threading
def main():
n = int(input("input n:"))
parents = list(map(int, input("input parents:").split()))
print("n is {0} and parents is {1}".format(n, str(parents)))
if __name__ == "__main__":
sys.setrecursionlimit(10 ** 7) # max depth of recursion
threading.stack_size(2 ** 27) # new thread will get stack of such size
threading.Thread(target=main).start()
I hope it'll help you...
I am trying to get my head around python. This is a snippet of code where I want to have the user input an option in a function and then use that input in another function(s). This tells me 'myInput' is not defined.
def main():
myInput = input("Enter a number ")
# This is the main function that will be the primary executuable function - the start of the program
return(myInput)
if __name__ == '__main__':
main()
#
print (myInput)
Function main returns the user's input, so try this:
if __name__ == '__main__':
myInput = main()
The program asked is:
"besides testing if the length of the given string is more than ten characters, it also tests if there is the character "X" (capital X) in the given string. If the string is longer than 10 characters and it has X in it, the tester subfunction returns a value True to the main function, otherwise False.
If the subfunction returns True to the main function, the program prints "X spotted!". As earlier, if the user inputs "quit", the program terminates."
This is what I tried, but the part of checking the x character does not work at all
def check(st,res="Too short"):
if len(st)>=10:
if checkX(st):
st=st+"\nX spotted!"
return st
else:
return res
def checkX(st):
for i in st:
if i=="X":
return True
return False
def main():
while True:
st=input("Write something (quit ends): ")
if st=="quit":
break
print(check(st))
It only checks if introduced string length is equal or higher than 10 characters.
The code works.
What should you change in your code:
You can use the in operator:
if "blah" not in somestring:
continue
Does Python have a string 'contains' substring method?
Do a real "main":
if __name__ == '__main__':
What you can do if you want to keep the main() function:
A module can discover whether or not it is running in the main scope by checking its own name, which allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m but not when it is imported:
if __name__ == "__main__":
# execute only if run as a script
main()
main — Top-level script environment
Result (this code works, it is simplier, more pythonic and respect pep8):
def check_input(tested_sentence: str, result: str = "Too short"):
if len(tested_sentence) >= 10:
if "X" in tested_sentence:
result = tested_sentence + "\nX spotted!"
else:
result = tested_sentence
return result
def main():
while True:
sentence = input("Write something (quit ends): ")
if sentence == "quit":
break
print(check_input(sentence))
if __name__ == '__main__':
main()
Code Style — The Hitchhiker's Guide to Python
I don't understand why I can't see an output on the terminal when I run the following code (Python 2.7):
#!/usr/bin/python
import sys
def main():
if len(sys.argv) >=2:
name = sys.argv[1]
else:
name = "Heisenberg"
print "Hello", name
if "__name__" == "__main__":
main()
__name__should be without ":
if __name__ == "__main__":
"__name__" is a string so it will never be equal to "__main__"