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.

SG

Related Python Mentoring answers

All answers ▸

Create an rock, paper, scissors game. The user should input one option, and the computer should play randomly.


Creating string from multiple strings(or characters)


Give an example of a FOR loop


Given a list of N numbers, use a single list comprehension to produce a new list that only contains those values that are: (a) even numbers, and (b) from elements in the original list that had even indices .