Functions in Python: def. Python 3 for beginners

In programming languages, functions are the named part of the code. These are separate blocks in the program text. Defined using the reserved word def. In Python, functions can be accessed an unlimited number of times from any part of the script.

python def




Why functions are needed

Functions are an indispensable tool for a programmer. With their help, the developer structures the program, making it clearer and more compact. With the help of functions, it is possible to reuse a separate part of the code without writing it again.

This is the easiest way to package the logic of the execution of individual parts of the program. This reduces the amount and time that a specialist spends on creating a script.

How to write the first function

Python 3 print(). . Python .

«» Python 3. . IDLE . print(«Hello, World!») «». .





. , win+R python.exe. , cmd. Enter , .

python 3 for beginners




def

def. , print() open(), . Python def . , , , .

def . , , def. .

, «Hello, World!», def:

  • >>> def _():
  • print(«Hello, World!»)
  • >>> _() #
  • Hello, World!

return

def Python :





  • >>>def <>( 1, 2, N):

, . IDLE . Tab. . .

return:

  • def <>( 1, 2, N):
  • ...
  • return <>

Return -. . return, , .

python commands




, def. Python , . . , .

, . , def return. , :

  • x = 12 #
  • y = 34
  • >>>def example(x,y): # example
  • x = «Hello» # x, y
  • y = «Python»
  • print(x, y, sep= «, »)
  • return None
  • >>>example(x, y) # ,
  • Hello, Python
  • >>>print(x, y)
  • 12 34

. Python print() x y .

, :

  • >>>def E_2(x, y):
  • return x + y
  • >>>E_2(«Hello, » «Python!») # ,
  • Hello, Python!
  • E_2(5, 4)
  • 10

E_2, x y. E_2 , - . . , , . , , .

python def functions




LEGB

. , , . . notlocal global.

LEGB :

  1. def, .
  2. , def.
  3. , global.
  4. , Python.

:

  • >>>L = 85
  • >>>R = 23
  • >>>def _2(K):
  • R = 10
  • C = L + K+R
  • return C
  • >>>_2(5)
  • 100

L R . R, C K – , def.

R, C K, R def. L, local, .

lambda

def, Python , - lambda. - LISP.

def, lambda , , - . lambda , .

lambda expression




-

lambda- def. lambda, , :

  • >>>f = lambda x, y, z: x + y + z
  • >>>f(2, 3, 4)
  • 9

, . lambda def. , while for.

def . , , , – , .

Lambda- . . . Python 3 def.




All Articles