Python
Python List index() with Example
A list is a container that stores items of different data types (ints, floats, Boolean, strings,...
Python main function is a starting point of any program. When the program is run, the python interpreter runs the code sequentially. Main function is executed only when it is run as a Python program. It will not run the main function if it imported as a module.
What is the def main() function in Python? To understand this, consider the following example code
def main():
print ("hello world!")
print ("gtupapers")
Here, we got two pieces of print- one is defined within the main function that is "Hello World" and the other is independent, which is "gtupapers". When you run the function def main ():
It is because we did not declare the call function "if__name__== "__main__".
It is important that after defining the main function, you call the code by if__name__== "__main__" and then run the code, only then you will get the output "hello world!" in the programming console. Consider the following code
def main():
print("hello world!")
if __name__ == "__main__":
main()
print("gtupapers")
gtupapers is printed in this case.
Here is the explanation,
To understand the importance of __name__ variable in Python main function method, consider the following code:
def main():
print("hello world!")
if __name__ == "__main__":
main()
print("gtupapers")
print("Value in built variable name is: ",__name__)
Now consider, code is imported as a module
import MainFunction
print("done")
Here, is the code explanation:
Like C, Python uses == for comparison while = for assignment. Python interpreter uses the main function in two ways
direct run:
import as a module
When the code is executed, it will check for the module name with "if." This mechanism ensures, the main function is executed only as direct run not when imported as a module.
Above examples are Python 3 codes, if you want to use Python 2, please consider following code
def main(): print "Hello World!" if __name__== "__main__": main() print "gtupapers"
In Python 3, you do not need to use if__name. Following code also works
def main():
print("Hello World!")
main()
print("gtupapers")
Note: Make sure that after defining the main function, you leave some indent and not declare the code right below the def main(): function otherwise, it will give indent error.
A list is a container that stores items of different data types (ints, floats, Boolean, strings,...
What are the modules in Python? A module is a file with python code. The code can be in the form...
SciPy in Python SciPy in Python is an open-source library used for solving mathematical,...
Python abs() Python abs() is a built-in function available with the standard library of python. It...
Calendar module in Python has the calendar class that allows the calculations for various task...
$20.20 $9.99 for today 4.5 (129 ratings) Key Highlights of Python Tutorial PDF 211+ pages eBook...