*Memo:
- My post explains a function (1).
One or more pass
statements, return
statements or values can be used to do nothing in a function, returning None
as shown below:
*Memo:
- Basically, a
pass
statement is used for the function to do nothing. - The function with no code gets error.
def func(): pass pass return return 100 200 "Hello" "World" print(func()) # None
def func(): # SyntaxError: incomplete input # No code
A class and function can be assigned to parameters as shown below:
class mycls: v = 'mycls' def myfn(): return 'myfn' def func1(cls, fn): print(cls.v, fn()) def func2(cls=mycls, fn=myfn): print(cls.v, fn()) func1(mycls, myfn) func2() # mycls myfn
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 with ;
as shown below:
*Memo:
-
;
is optional for the end of code.
def func(): v1 = 3; v2 = 5; return v1 + v2 # def func(): v1 = 3; v2 = 5; return v1 + v2; print(func()) # 8
def func(): v1 = 3 v2 = 5 return v1 + v2 def func(): v1 = 3; v2 = 5 return v1 + v2 def func(): v1 = 3 v2 = 5; return v1 + v2 def func(): v1 = 3 v2 = 5 return v1 + v2; # Error
A function can be indirectly assigned to a variable and parameter but cannot be directly assigned to a variable like JavaScript except a lambda as shown below:
def func1(): print('OK') v = func1 v() # OK def func2(f1): f1() func2(func1) # OK def func3(f1=func1): f1() func3() # OK
v = def func(): print('OK') # SyntaxError: invalid syntax v = func(): print('OK') # SyntaxError: invalid syntax
def func1(f): f() func1(def func2(): print('OK')) func1(func2(): print('OK')) # SyntaxError: invalid syntax
def func1(f=def func2(): print('OK')): f() # SyntaxError: invalid syntax
v = lambda: print('OK') v() # OK
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(param): pass def my_func(my_param): pass def my_first_func(my_first_param): pass
Top comments (0)