TestingDocs.com
Software Testing website
  • Automation
    • Selenium
    • JBehave Framework
  • Tutorials
    • MySQL Tutorials
    • Testlink
    • Maven
    • Git
  • IDEs
    • IntelliJ IDEA
    • Eclipse
  • Flowcharts
    • Flowgorithm
    • Raptor
  • About

Python

Writing a Function in Python Interactively

Python Tutorials

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.

 

 

Related Posts

Download Python Windows 11

Python /

Download & Install Python on Windows 11

PyCharm CE

Python /

Install PyCharm on Ubuntu Linux

Python Install on CentOS Linux

Python /

Install Python on CentOS

What is Python?

Python /

What is Python?

Install Python

Python /

Install Python 3.6 on Windows

‹ User Defined Functions is Python Program› Running a Python Script

Recent Posts

  • MS Access Data Types
  • Install RAPTOR Avalonia on CentOS
  • Download RAPTOR Avalonia Edition on Windows
  • npm doctor command
  • Build & Run CLion Project
  • Create New CLion C Project on Windows
  • Configure CLion Toolchains on Windows
  • Launch CLion IDE on Windows
  • Activate CLion IDE
  • CLion IDE for C/C++ Development

Back to Top

Links

  • Contact
  • Privacy Policy
  • Cookie Policy

www.TestingDocs.com

Go to mobile version