SpecialistOff.NET / Вопросы / Статьи / Фрагменты кода / Резюме / Метки / Помощь / Файлы
НазадМетки: python
To create a function in Python, you use the def keyword, followed by the function name and argument list, and a colon to begin the function body. Here is the first example turned into a function:
# PythonForProgrammers/myFunction.py def myFunction(response): val = 0 if response == "yes": print("affirmative") val = 1 print("continuing...") return val print(myFunction("no")) print(myFunction("yes"))
Notice there is no type information in the function signature - all it specifies is the name of the function and the argument identifiers, but no argument types or return types. Python is a structurally-typed language, which means it puts the minimum possible requirements on typing. For example, you could pass and return different types from the same function:
# PythonForProgrammers/differentReturns.py def differentReturns(arg): if arg == 1: return "one" if arg == "one": return True print(differentReturns(1)) print(differentReturns("one"))
The only constraints on an object that is passed into the function are that the function can apply its operations to that object, but other than that, it doesn’t care. Here, the same function applies the ‘+‘ operator to integers and strings:
# PythonForProgrammers/sum.py def sum(arg1, arg2): return arg1 + arg2 print(sum(42, 47)) print(sum('spam ', "eggs"))
When the operator ‘+‘ is used with strings, it means concatenation (yes, Python supports operator overloading, and it does a nice job of it).