Function in Python (2)



This content originally appeared on DEV Community and was authored by Super Kai (Kazuya Ito)

Buy Me a Coffee☕

*Memo:

One or more pass statements, return statements or values can be used to do nothing in a function, returning None as shown below:

*Memo:

  • Conventionally, a pass statement is used for the function to do nothing.
  • The function with no code gets error.
def func():
    pass

def func():
    pass
    pass

def func():
    return

def func():
    return
    return

def func():
    "Hello"

def func():
    "Hello"
    "World"

def func():
    100

def func():
    100
    200

print(func())
# None

def func(): # SyntaxError: incomplete input
    # No code

A class and function can be passed to a function as shown below:

class mycls:
    v = "Hello"

def myfn():
    return "World"

def func(cls, fn):
    print(cls.v, fn())

func(mycls, myfn)
# Hello World

A class and function can be defined in a function as shown below:

def func():
    class mycls:
        v = "Hello"
    def myfn():
        return "World"
    print(mycls.v, myfn())

func()
# Hello World
# 3D function
def func(num):
    def func(num):
        def func(num):
            return num**2
        return func(num)
    return func(num)

print(func(3))
# 9

A function can be written in one line as shown below:

def func(num1, num2): return num1+num2

print(func(3, 5))
# 8
def func(): return

print(func())
# None
def func(): pass

print(func())
# None

A function can be indirectly assigned to a variable but cannot be directly assigned to a variable like JavaScript except Lambda as shown below:

def func(num1, num2):
    return num1+num2

v = func
print(v(3, 5))
# 8
v = def func(num1, num2):
        return num1+num2
# SyntaxError: invalid syntax

v = func(num1, num2):
        return num1+num2
# SyntaxError: invalid syntax
v = lambda num1, num2: num1+num2
print(v(3, 5))
# 8

The name of a function or parameter:

  • can have letters, _ and the digits except for the 1st character.
  • can be a reserved soft keyword.
  • cannot start with a digit.
  • cannot be a reserved keyword.
def True_100(True_100): pass
def tRuE_100(tRuE_100): pass
def _True100(_True100): pass
def True100_(True100_): pass
def match(match): pass
def case(case): pass
def type(type): pass
def _(_): pass
# No error

def True-100(True-100): pass
def 100_True(100_True): pass
def True(True): pass
def class(class): pass
def def(def): pass
# Error

A function name should be lower_snake_case as shown below:

var = 'abc'
my_var = 'abc'
my_first_var = 'abc'
def func(): pass
def my_func(): pass
def my_first_func(): pass


This content originally appeared on DEV Community and was authored by Super Kai (Kazuya Ito)