This wikiHow teaches you how to define and call a function in a Python script.

Steps

  1. 1
    Open your Python editor. You can use Idle or any programming editor you have on your computer (including Notes or Notepad).
  2. 2
    Define a function. As an example, we're going to start by defining a function called printme. Type the following code:
    def printme( str ):
         This prints a passed string into this function
         print str
         return;
    
    Advertisement
  3. 3
    Add the call to the code. Now that you've the defined print me function, you can call it with the code printme(“str”), where str is whatever it is you want printed out. On the next line after return;, add a printme call as shown (do not indent!):
    def printme( str ):
         This prints a passed string into this function
         print str
         return;
    printme(Hey! How are you doing?”)
    
  4. 4
    Save the code as a .py file. The steps to save the script varies by text editor.
    • Typically you'll click the File menu, then Save As…, select a folder, type a file name (e.g. printme.py), then click Save.
  5. 5
    Open the command prompt (Windows) or a Terminal window (macOS).
    • Windows: Type cmd into the search bar, then click Command Prompt in the search results.
    • macOS: In Finder, open the Applications folder, double-click the Utilities folder, then double-click Terminal.
  6. 6
    Navigate to the directory that contains your Python code. To switch directories, type cd full-path-to-directory at the command prompt (replace "full-path-to-directory" with the actual path to the folder), then press Enter or Return.
    • Example: cd C:\Users\wikiHow\Documents\Python\Test
  7. 7
    Run the script. To do this, type python printme.py (replace "printme.py" with the name of your file) at the prompt and press Enter or Return.
    • The output should read Hey! How are you doing?
  8. Advertisement

About This Article

Nicole Levine, MFA
Written by:
wikiHow Technology Writer
This article was co-authored by wikiHow staff writer, Nicole Levine, MFA. Nicole Levine is a Technology Writer and Editor for wikiHow. She has more than 20 years of experience creating technical documentation and leading support teams at major web hosting and software companies. Nicole also holds an MFA in Creative Writing from Portland State University and teaches composition, fiction-writing, and zine-making at various institutions. This article has been viewed 35,856 times.
How helpful is this?
Co-authors: 4
Updated: July 20, 2020
Views: 35,856
Categories: Python
Article SummaryX

1. Open your editor.
2. Define the function.
3. Use printme(“str”) to call the code.
4. Save your code.

Did this summary help you?
Advertisement