brittAnderson / Intro2Computing4Psychology

A guided introduction to computing tools useful for research in psychology - targeted to complete beginners
47 stars 159 forks source link

"Main" trick for hangman python #27

Closed bsgunpat closed 4 years ago

bsgunpat commented 4 years ago

Hi everyone,

In the case that there may be others (like myself) who have a difficult time with this assignment, here are some tips that I obtained from this video.

Dr. Anderson encouraged me to share this tip below when putting your hangman game together. You can use the main() function in python to execute it as a script (and it will enable you to run the game in the terminal). Here is the code used from the video:

def main(): word = get_word() play(word)

if __name__ == "__main__": main()

(FYI: get_word() was the function used in the video to obtain a random word for the game (it can also be adjusted for a single word to make it easier), and play(word) was the function used for the interactive portion of the game. The conditional is used just to execute the script from the command line and not when you import it (from what I have understood))

Personally, I am still trying to understand why this works as it does, but hopefully others may find it just as helpful! ~Brittany Gunpat

brittAnderson commented 4 years ago

Python has all sorts of hidden variables that it runs and sets and many of them are marked by double underscores, such as the __main__ and __name__ above. When you run from the terminal it can check if a couple of things match and if they do it knows to run the main function without you have to explicitly call it. Can make it more convenient for someone to use your code who knows nothing about python. They can just do python yourprogram.py.

Here is one person's explanation with some code examples you can run yourself to step through things.