+ 1
Применение функции def
Объясните применение def,я плохо понимаю что можно делать с этим,желательно разжевать ибо я уже более 5 дней пытаюсь понять
1 Resposta
+ 1
'def' is used to DEFine function...
functions are used to avoiding code repetition: they could take arguments (or not) and could return value (or not)...
if you have some logic that repeat more than twice in a code, then it would be advantageous to define a function to do that logic...
suppose you have to compute many times the square of a value if value is less than zero, else compute the double of the value (simple example), you could do:
def square_or_double(val):
if val < 0:
return val*val
else:
return 2*val
then, you have only to call the function to get the result, avoiding repeating many times the four lines of the function body:
v1 = square_or_double(-42)
v2 = square_or_double(42)