Python Language Functions: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 20: Line 20:
   return optional_return_value
   return optional_return_value
</syntaxhighlight>
</syntaxhighlight>
The compiler will not prevent to declare other statements after the <code>return</code> statement, they be never executed, though.


==Function Name Rules==
==Function Name Rules==

Revision as of 05:46, 26 May 2021

Internal

Overview

Function Declaration

A function is defined by the reserved word def:

def function_name(parameters):
  <function body>
def function_name(par1, par2, par3):
  <function body>

A parameter is a variable name used in the function definition. The parameters are handles for arguments for a particular function invocation. Parameters are optional, a function may have no parameters.

Return Value

The return statement, which is introduced by the return reserved word, ends the function execution and sends back the result of the function.

def ...
  ...
  return optional_return_value

The compiler will not prevent to declare other statements after the return statement, they be never executed, though.

Function Name Rules

The function name rules for function names is the same as for variable names.

Function Invocation

When the function is invoked, we pass an argument for each parameter declared in the function definition. An argument is a value that is passed into the function as function's input. The argument can be another variable, defined in the block that invokes the function. Arguments are passed in parentheses and they are separated by commas. If the function has no parameters, we pass no arguments, but the parentheses still need to be provided.

function_name(arguments)
function_name(arg1, arg2, arg3)

Example

def something(a, b):
  c = a + b
  return c

Built-in Functions

type()

type() returns the type of the argument.

print()

print(). If more comma-separated arguments are used, every comma adds a space.

input()

input() instructs Python to pause and read data from stdin. input() returns a string.

s = input('this is the prompt')
print(s)

Other Functions

max('...'), type conversion functions float(), int(), str()