Python - How to save functions

function, python, save

Solution

What you want to do is to take your Python file, and use it as a module or a library.

There's no way to make those four functions automatically available, no matter what, 100% percent of the time, but you can do something very close.

For example, at the top of your file, you imported `numpy`. `numpy` is a module or library which has been set up so it's available any time you run python, as long as you import it.

You want to do the same thing -- save those 4 functions into a file, and import them whenever you want them.

For example, if you copy and paste those four functions into a file named `foobar.py`, then you can simply do `from foobar import *`. However, this will only work if you're running Python in the same folder where you saved your code.

If you want to make your module available system-wide, you have to save it somewhere on the PYTHONPATH. Usually, saving it to `C:\Python27\Lib\site-packages` will work (assuming you're running Windows).

Problem

I´m starting in python. I have four functions and are working OK. What I want to do is to save them. I want to call them whenever I want in python. Here's the code my four functions: ``` import numpy as ui def simulate_prizedoor(nsim): sim=ui.random.choice(3,nsim) return sims def simulate_guess(nsim): guesses=ui.random.choice(3,nsim) return guesses def goat_door(prizedoors, guesses): result = ui.random.randint(0, 3, prizedoors.size) while True: bad = (result == prizedoors) | (result == guesses) if not bad.any(): return result result[bad] = ui.random.randint(0, 3, bad.sum()) def switch_guesses(guesses, goatdoors): result = ui.random.randint(0, 3, guesses.size) while True: bad = (result == guesses) | (result == goatdoors) if not bad.any(): return result result[bad] = ui.random.randint(0, 3, bad.sum()) ```

Original source