Python __name__() main function - python

I have tried looking for an answer online but couldn't find it. I am fairly new to python and wondering if you could have multiple main function in a program. For example:
ask_user = int(input('enter your choice (1 or 2): '))
if ask_user == 1:
def print_hello():
print('hello world')
def main():
print_hello()
if __name__ == '__main__': main()
elif ask_user == 2:
def print_hi():
print('hi')
def main():
print_hi()
if __name__ == '__main__': main()
Is this a good programing practice?

This wouldn't be considered good programming practice, no. Like index.html, the point of main() is to have a primary entry point to the program. Even if a particular language allowed that sort of thing, it would be confusing for anyone reading the code and trying to figure out where to start. For the display options, you would use separate functions with meaningful names, such as print_hello_world and print_hi, and they would both be able to be called by main().

Related

Communication between two python programs

please help me understand why this doesn't work and how to change it.
I basically want to be able to query values of a var of program one from program two. So here are the most basic programs:
P1:
import time
gscore = 0
def get_info():
return gscore
def main():
global gscore
score = 0
while score <10:
time.sleep(1)
score +=1
gscore = score
print(score)
if __name__ == '__main__':
main()
P2:
from functest import get_info
print(get_info())
The structure may seem a bit weird but basically I have an existing small python game and want to be able to query the score which is why I adapted it in this way. So P1 obviously counts to ten but P2 always gets 0 as a return value. I feel like I'm making a really stupid mistake here...
Thx for help :)
if __name__ == '__main__' is only executed when you run your code form a shell and not when you import your program from another program. To fix this you can modify your program as:
In you P1 modify get_info to this:
def get_info():
global gscore
return gscore
In your P2 do this:
from functest import main, get_info
main()
print(get_info())
Also, note that there are better way of doing what you are doing like using a class instead of creating a global variable.
class Score(object):
def __init__(self, gscore=0):
self.gscore = gscore
def get_info(self):
return self.gscore
def increment(self, score=0):
while score < 10:
score +=1
self.gscore = score
When you import a module in Python you are not executing the content of it.
if __name__ == "__main__": is there so that your Python files can act as either reusable modules, or as standalone programs.
If you want to execute the main() function you'll need to explicitly call it.:
from functest import main, get_info
main() # calling the main function in your functest file
print(get_info()) # calling the get_info function
this will return the value you are looking for.
Now, main will be called if you execute the functest.py file:
$ python functest.py
#=> 9
When you import a function of another program, you are importing the functionality of the program, not the actual instance of the program. What I mean by that is that your program only counts to 10 while it's running, but 10 isn't part of the code, it's a result.
What importing it allows you to do is run the bit of code you imported (In your case, running the get_info code with the gscore = 0 being the gscore that is returned, however, this is a distinct instance of your other program, so even if gscore is increasing in another program that you're running with the main method, your second program has it's own gscore that is 0. Importing is more for when you have a sort of library of functions in a program that you want access to.
What you want is to be able to, run time, read a value that the other program has generated. This can't be done with python variables, but it can be done in many other ways. A common way is to write the score to a file, then read the file in your other program. If you need information on how to read and write files, read this guide here.

Initialize variable in loop - use global variable?

I wrote a function that makes a screenshot and checks if it's different than the old one. The example code is below. However, I wonder about pythons best practice to set the variables oldimage and image. Especially oldimage needs to be set before main() can start the first time. Do I use global variables?
def main():
image=screenGrab()
if equal(image,oldimage):
pass
else:
dosomething()
oldimage=image
while True:
main()
Using global variables is almost never the correct solution. It usually ends up causing more problems than solutions. Continuing from #MartijnPieters, I would organize your code as follows:
def main():
oldimage = loadLastImage()
while True:
image=screenGrab()
if not equal(image,oldimage):
dosomething()
saveLastImage(image) # this is the opposite of loadLastImage()
oldimage=image
# this is the more accepted way of running main
# because it still allows your code to be loaded as module
if __name__ == "__main__":
main()

Python User-Defined Global Variables Across Modules: Issues calling them when other modules are run

I am fairly new to Python and currently learning to work with functions and multiple modules within a python program.
I have two modules "Functions_Practice_Main" (which runs a menu) and "Functions_Practice" which has the code for a simple program that works out if a user's input divides by 7 or not (I know...pretty dull practice).
What I want to do is get the user to enter their name when the menu module is runs and then get this global variable to by displayed througout the program to make the program more personal.
However, when I run the menu module it asks for a name twice. The first name entered is displayed in the 'divide by 7' program and the second name entered is displayed in the menu. I understand why this is happening (due to the import of the Functions_Practice module demanding to know what the global variables are in the Functions_Practice_Main module before the rest of the code has a chance to run) BUT I REALLY NEED TO KNOW HOW TO FIX THIS.
How can I get the user to enter their name ONCE when the menu module is runs and then get this global variable to by displayed througout the program to make it more personal for the user.
Functions_Practice_Main
import Functions_Practice, sys
name = input("What is your name? ")
def main():
while True:
print(name, "'s Menu")
print("*******************")
print("1. Can you divide by 7?")
print("2. Quit")
print("*******************")
selection = int(input("Your number selection please..."))
if selection == 1:
Functions_Practice.main()
elif selection == 2:
sys.exit()
else:
print("Your number selection was invalid, please try again...")
if __name__ == '__main__':
main()
*Functions_Practice*
import Functions_Practice_Main
def inputData(name):
print(name)
number = int(input(" Please enter your number: "))
return number
def processData(number):
answer = number % 7
if answer == 0:
remainder = True
else:
remainder = False
return remainder
def outputData(remainder):
if remainder == True:
print("The number you entered doesn't have a remainder")
elif remainder == False:
print("The number you entered does have a remainder")
def main():
number = inputData(Functions_Practice_Main.name)
remainder = processData(number)
outputData(remainder)
if __name__ == '__main__':
main()
Running a module as a script does not count as importing it as a module. When the Functions_Practice_Main.py script imports Functions_Practice, and Functions_Practice imports Functions_Practice_Main, Python doesn't care that the code in Functions_Practice_Main.py is already running as the main script. Python will run it again to produce the module.
How do you fix this? Well, there are several things you should do. First, avoid circular imports if at all possible. Instead of having Functions_Practice import Functions_Practice_Main, pass any data Functions_Practice needs from Functions_Practice_Main as function arguments.
In Functions_Practice_Main:
Functions_Practice.interactive_remainder_test(name)
In Functions_Practice:
def interactive_remainder_test(name):
number = inputData(name)
remainder = processData(number)
outputData(remainder)
Second, things like this:
name = input("What is your name? ")
belong in a file's main, since they shouldn't run when a file is imported.

Why is the main() function not defined inside the if '__main__'?

You can often see this (variation a):
def main():
do_something()
do_sth_else()
if __name__ == '__main__':
main()
And I am now wondering why not this (variation b):
if __name__ == '__main__':
do_something()
do_sth_else()
Or at least this (variation c):
if __name__ == '__main__':
def main():
do_something()
do_sth_else()
main()
Of course the function calls inside main() might not be function calls, they just represent anything you might want to do in your main() function.
So why do people prefer variation a over the others? Is it just style/feeling or are there some real reasons? If possible, please also link sources.
Why limit your main() function to command line usage only?
By defining a main() function at module scope, you can now wrap your script and alter how it is called. Perhaps you want to set default arguments in sys.argv, perhaps you want to reuse the code in another script.
This is because there are two ways of using Python scripts. One from the command line and another when importing it from another script. When you run it from command line, you want to run main() function and when you import it you may not want to run main() function until you need it ( you just want to import main() ).

Pass argument to function in eclipse?

I go into File-properties-edit-arguments type a string. When run program I get no output.
def print(n):
print n
Be sure you're calling the method from somewhere, typically a main() or test() function in the Python file. Also, avoid using print, since that masks the actual statement/function. (In Python 2.x, this won't even run - you have to name it something other than print.)
def main():
print(raw_input("Will print something "))
if __name__ == '__main__':
main()

Categories

Resources