How to Call a Function in Python (with Pictures)

Table of contents:

How to Call a Function in Python (with Pictures)
How to Call a Function in Python (with Pictures)
Anonim

This article explains how to declare and call a function using a script created in Python.

Steps

9897260 1
9897260 1

Step 1. Open the Python editor you normally use

You can use Idle or any programming editor you have installed on your computer (including Note or Notepad).

9897260 2
9897260 2

Step 2. Start with declaring the function

In this example we will create a function called print. The code to use is shown below:

def print (str): "This function prints the string that is passed as an input parameter" print str return;

9897260 3
9897260 3

Step 3. Add code to call the "print" function

Now the latter has been declared and defined in detail, you can recall it with the following printme code (“str”), where the str parameter represents the text string that will be printed on the screen. On the line following that of the return; command, add the call to the print function as shown in the example code (do not indent it):

def print (str): "This function prints the string that is passed as an input parameter" print str return; print ("Hi! How are you?")

9897260 4
9897260 4

Step 4. Save the source code as a PY file

The procedure for saving the Phyton script you have created varies depending on the editor you are using.

Normally you will need to enter the menu File, click on the option Save with name…, select the destination folder, assign a name to the file (for example print.py) and click on the button Save.

9897260 5
9897260 5

Step 5. Open a "Command Prompt" (on Windows) or "Terminal" (on Mac) window

  • Windows: type the command cmd in the search bar, then click on the icon Command Prompt which will appear in the list of results.
  • macOS:

    open a Finder window, access the folder Applications, double-click the directory icon Utility, then double-click the icon Terminal.

9897260 6
9897260 6

Step 6. Navigate to the directory where you stored the Python file you created earlier

To switch from one directory to another using the command shell, type the following code cd [full_path_directory] (replacing the parameter "[full_path_directory]" with the full path of the folder in question, then press the Enter key.

  • Example path:

    cd C: / Users / wikiHow / Documents / Python / Test

9897260 7
9897260 7

Step 7. Run the script

Type the python print.py command (replacing the "print.py" parameter with the name of the Phyton file you want to run) into the command shell window and press the Enter key.

Recommended: