Site icon TestingDocs.com

Writing a Function in Python Interactively

Introduction

Python lets you put a sequence of statements together to create a function. Here is this example we will create a function to add two numbers and print the result interactively at the Python prompt window.

Defining a Function Interactively

Launch the Python prompt window and add the below code to add two numbers a and b. Make sure you properly indent the line inside the function definition.

The first line tells Python that we are defining a new function called add. The function takes two input parameters a and b. The following line is indented to show that it is part of the add function. The blank line lets Python know that the definition is finished, and the interpreter responds with another prompt.

We can invoke the function by typing its name and specifying the input parameters in interactive mode. The function takes the input and prints the sum of the two numbers.

Code Listing

Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.

>>> def add(a,b):

...    print("Sum of a and b is=",a+b)

...

>>> add(10,30)

Sum of a and b is= 40

 

Screenshot

Common mistake

Make sure you properly indent the code inside the function definition. Otherwise, you would get an error like this “IndentationError: expected an indented block”.

Disadvantage

One problem with entering functions interactively at the prompt is that the definitions of the functions go away when we exit the prompt. If you want to use the function again the next time, we have to create or code again at the prompt. To define a reusable function you can create them in a separate file called a module/script.

 

 

Exit mobile version