How do I define a function in Python?

There are two keyword to define a function in Python: "def" and "return". The structure is always the same: def function_name(input1, input2 = 2): [INDENT] "main body" return output Remember that in Python using the ":" at the end of the definition line and indenting the following lines is essential. Every output is placed after the keyword return. The inputs can be mandatory or optional. Every optional input need to be given a default value, like this: optional_input = Default_value. Finally, it is good practice to put all the mandatory inputs first, and then the optional ones.

Answered by Stefania G. Python tutor

1971 Views

See similar Python Mentoring tutors

Related Python Mentoring answers

All answers ▸

Use recursion to print all the sublists of a given list


What would output this code? print(hello world)


Write a simple Python program that asks a user to input their age and name and then return the text: "Hi my name is *NAME*, and I am *AGE* years old."


Create an algorithm that can be used as a guessing game. Make sure to import random at the start.


We're here to help

contact us iconContact usWhatsapp logoMessage us on Whatsapptelephone icon+44 (0) 203 773 6020
Facebook logoInstagram logoLinkedIn logo

© MyTutorWeb Ltd 2013–2025

Terms & Conditions|Privacy Policy
Cookie Preferences