Python funkció útmutató példákkal

Bevezetés a Python funkcióihoz

A funkció lehetővé teszi egy újrafelhasználható kódblokk definiálását, amely a programon belül sokszor végrehajtható.

A funkciók segítségével modulárisabb és DRY megoldásokat hozhat létre az összetett problémákra.

Míg Python már számos beépített funkciók, mint például print(), és len()akkor is meghatározhatja a saját funkciók használatához belül a projektek.

A függvények használatának egyik nagy előnye a kódban, hogy csökkenti a projekt kódsorainak teljes számát.

Szintaxis

A Pythonban a függvénydefiníció a következő tulajdonságokkal rendelkezik:

  1. A kulcsszó def
  2. egy függvény neve
  3. paranthesis '()', és a heahesis bemeneti paramétereken belül, bár a bemeneti paraméterek nem kötelezőek.
  4. kettőspont ':'
  5. valamilyen végrehajtandó kódblokk
  6. visszatérési nyilatkozat (nem kötelező)
# a function with no parameters or returned values def sayHello(): print("Hello!") sayHello() # calls the function, 'Hello!' is printed to the console # a function with a parameter def helloWithName(name): print("Hello " + name + "!") helloWithName("Ada") # calls the function, 'Hello Ada!' is printed to the console # a function with multiple parameters with a return statement def multiply(val1, val2): return val1 * val2 multiply(3, 5) # prints 15 to the console

A függvények olyan kódblokkok, amelyek egyszerűen felhasználhatók a függvény meghívásával. Ez lehetővé teszi a kód egyszerű, elegáns újrafelhasználását anélkül, hogy kifejezetten újraírnánk a kódrészeket. Ezáltal a kód olvashatóbb, megkönnyíti a hibakeresést és korlátozza a gépelési hibákat.

A Pythonban a függvények a defkulcsszó segítségével jönnek létre , majd a zárójelben lévő függvény neve és függvényparaméterei következnek.

A függvény mindig ad vissza egy értéket. A returnkulcsszót a függvény egy érték visszaadására használja, ha nem akar visszaadni semmit, akkor az alapértelmezett érték jelenik Nonemeg.

A függvény nevét a függvény meghívására használják, zárójelben adva át a szükséges paramétereket.

# this is a basic sum function def sum(a, b): return a + b result = sum(1, 2) # result = 3

Megadhat alapértelmezett értékeket a paraméterekhez, így a Python értelmezi, hogy ennek a paraméternek az értéke az alapértelmezett, ha egyiket sem adják meg.

def sum(a, b=3): return a + b result = sum(1) # result = 4

A paramétereket a kívánt sorrendben adhatja át, a paraméter nevével.

result = sum(b=2, a=2) # result = 4

Azonban nem lehet kulcsszó argumentumot átadni egy kulcsszó nélküli argumentum előtt

result = sum(3, b=2) #result = 5 result2 = sum(b=2, 3) #Will raise SyntaxError

A függvények objektumok is, így hozzárendelheti őket egy változóhoz, és ezt a változót függvényként használhatja.

s = sum result = s(1, 2) # result = 3

Megjegyzések

Ha a függvénydefiníció paramétereket tartalmaz, akkor ugyanannyi paramétert kell megadnia a függvény meghívásakor.

print(multiply(3)) # TypeError: multiply() takes exactly 2 arguments (0 given) print(multiply('a', 5)) # 'aaaaa' printed to the console print(multiply('a', 'b')) # TypeError: Python can't multiply two strings

A függvény által futtatni kívánt kódblokk tartalmazza a függvényen belül behúzott összes utasítást.

def myFunc(): print('this will print') print('so will this') x = 7 # the assignment of x is not a part of the function since it is not indented

A függvényen belül definiált változók csak a függvény hatókörén belül léteznek.

def double(num): x = num * 2 return x print(x) # error - x is not defined print(double(4)) # prints 8

A Python csak akkor értelmezi a funkcióblokkot, ha a függvény meghívásra kerül, és nem akkor, amikor a függvény definiálva van. Tehát akkor is, ha a függvénydefiníció blokk valamilyen hibát tartalmaz, a python tolmács erre csak akkor hívja fel a figyelmet, amikor a függvény meghívásra kerül.

Most nézzünk meg néhány konkrét funkciót példákkal.

max () függvény

max() egy beépített függvény a Python 3-ban. Visszaadja az iterálható legnagyobb elemet, vagy a két vagy több argumentum közül a legnagyobbat.

Érvek

Ez a függvény két vagy több számot vagy bármilyen iterálható argumentumot vesz fel. Miközben érvként iterable-t adunk, meg kell győződnünk arról, hogy az iterable összes eleme azonos típusú. Ez azt jelenti, hogy nem adhatunk át olyan listát, amelyben karakterlánc és egész érték is van tárolva. Szintaxis: max (iterálható, * iterálható [, kulcs, alapértelmezett]) max (arg1, arg2, * args [, kulcs])

Érvényes érvek:

max(2, 3) max([1, 2, 3]) max('a', 'b', 'c')

Érvénytelen érvek:

max(2, 'a') max([1, 2, 3, 'a']) max([])

Visszatérési érték

Az iterálható elem legnagyobb értéke visszaküldésre kerül. Két vagy több helyzeti argumentum megadása esetén a pozícióbeli argumentumok közül a legnagyobb értéket adjuk vissza. Ha az iteráció üres, és az alapértelmezett nincs megadva, akkor ValueErrora

Kódminta

print(max(2, 3)) # Returns 3 as 3 is the largest of the two values print(max(2, 3, 23)) # Returns 23 as 23 is the largest of all the values list1 = [1, 2, 4, 5, 54] print(max(list1)) # Returns 54 as 54 is the largest value in the list list2 = ['a', 'b', 'c' ] print(max(list2)) # Returns 'c' as 'c' is the largest in the list because c has ascii value larger then 'a' ,'b'. list3 = [1, 2, 'abc', 'xyz'] print(max(list3)) # Gives TypeError as values in the list are of different type #Fix the TypeError mentioned above first before moving on to next step list4 = [] print(max(list4)) # Gives ValueError as the argument is empty

Futtassa a kódot

Hivatalos dokumentumok

min () függvény

min() egy beépített függvény a Python 3-ban. Visszaadja az iterálható legkisebb elemet, vagy a legkisebbet két vagy több argumentumból.

Érvek

Ez a függvény két vagy több számot vagy bármilyen iterálható argumentumot vesz fel. Miközben érvként iterable-t adunk, meg kell győződnünk arról, hogy az iterable összes eleme azonos típusú. Ez azt jelenti, hogy nem adhatunk át olyan listát, amelyben karakterlánc és egész érték is van tárolva.

Érvényes érvek:

min(2, 3) min([1, 2, 3]) min('a', 'b', 'c')

Érvénytelen érvek:

min(2, 'a') min([1, 2, 3, 'a']) min([])

Visszatérési érték

Az iterálható legkisebb elem visszaküldésre kerül. Ha két vagy több helyzeti argumentum van megadva, akkor a legkisebb a helyzeti érvek közül

visszatér. Ha az iterable üres és az alapértelmezett nincs megadva, akkor egy ValueError jelenik meg.

Kódminta

print(min(2, 3)) # Returns 2 as 2 is the smallest of the two values print(min(2, 3, -1)) # Returns -1 as -1 is the smallest of the two values list1 = [1, 2, 4, 5, -54] print(min(list1)) # Returns -54 as -54 is the smallest value in the list list2 = ['a', 'b', 'c' ] print(min(list2)) # Returns 'a' as 'a' is the smallest in the list in alphabetical order list3 = [1, 2, 'abc', 'xyz'] print(min(list3)) # Gives TypeError as values in the list are of different type #Fix the TypeError mentioned above first before moving on to next step list4 = [] print(min(list4)) # Gives ValueError as the argument is empty

Futtassa a kódot

Hivatalos dokumentumok

divmod () függvény

divmod() is a built-in function in Python 3, which returns the quotient and remainder when dividing the number a by the number b. It takes two numbers as arguments a & b. The argument can’t be a complex number.

Argument

It takes two arguments a & b - an integer, or a decimal number.It can’t be a complex number.

Return Value

The return value will be the pair of positive numbers consisting of quotient and remainder obtained by dividing a by b. In case of mixed operand types, rules for binary arithmetic operators will be applied.

For Integer number arguments, return value will be same as (a // b, a % b).

For Decimal number arguments, return value will be same as (q, a % b), where q is usually math.floor(a / b) but may be 1 less than that.

Code Sample

print(divmod(5,2)) # prints (2,1) print(divmod(13.5,2.5)) # prints (5.0, 1.0) q,r = divmod(13.5,2.5) # Assigns q=quotient & r= remainder print(q) # prints 5.0 because math.floor(13.5/2.5) = 5.0 print(r) # prints 1.0 because (13.5 % 2.5) = 1.0

REPL It!

Official Docs

Hex(x) function

hex(x) is a built-in function in Python 3 to convert an integer number to a lowercase hexadecimal string prefixed with “0x”.

Argument

This function takes one argument, x, that should be of integer type.

Return

This function returns a lowercase hexadecimal string prefixed with “0x”.

Example

print(hex(16)) # prints 0x10 print(hex(-298)) # prints -0x12a print(hex(543)) # prints 0x21f

Run Code

Official Documentation

len() function

len() is a built-in function in Python 3. This method returns the length (the number of items) of an object. It takes one argument x.

Arguments

It takes one argument, x. This argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

Return Value

This function returns the number of elements in the argument which is passed to the len() function.

Code Sample

list1 = [123, 'xyz', 'zara'] # list print(len(list1)) # prints 3 as there are 3 elements in the list1 str1 = 'basketball' # string print(len(str1)) # prints 10 as the str1 is made of 10 characters tuple1 = (2, 3, 4, 5) # tuple print(len(tuple1)) # prints 4 as there are 4 elements in the tuple1 dict1 = {'name': 'John', 'age': 4, 'score': 45} # dictionary print(len(dict1)) # prints 3 as there are 3 key and value pairs in the dict1

Run Code

Official Docs

Ord function

ord() is a built-in function in Python 3, to convert the string representing one Unicode character into integer representing the Unicode code of the character.

Examples:

>>> ord('d') 100 >>> ord('1') 49

chr function

chr() is a built-in function in Python 3, to convert the integer representing the Unicode code into a string representing a corresponding character.

Examples:

>>> chr(49) '1'

One thing is to be noted that, if the integer value passed to chr() is out of range then, a ValueError will be raised.

>>> chr(-10) 'Traceback (most recent call last): File "", line 1, in  chr(-1) ValueError: chr() arg not in range(0x110000)'

input() functions

Many a time, in a program we need some input from the user. Taking inputs from the user makes the program feel interactive. In Python 3, to take input from the user we have a function input(). If the input function is called, the program flow will be stopped until the user has given an input and has ended the input with the return key. Let’s see some examples:

When we just want to take the input:

This will just give a prompt without any message

inp = input()

Run Code

To give a prompt with a message:

promptwithmessage = input(’‘)

_

The ’_’ in the output is the prompt

Run Code

3. When we want to take an integer input:

number = int(input('Please enter a number: '))

Run Code

If you enter a non integer value then Python will throw an error ValueError. So whenever you use this, please make sure that you catch it too. Otherwise, your program will stop unexpectedly after the prompt.

number = int(input('Please enter a number: ')) # Please enter a number: as # Enter a string and it will throw this error # ValueError: invalid literal for int() with base 10 'as'

4. When we want a string input:

string = str(input('Please enter a string: '))

Run Code

Though, inputs are stored by default as a string. Using the str() function makes it clear to the code-reader that the input is going to be a ‘string’. It is a good practice to mention what type of input will be taken beforehand.

Official Docs

How to call a function in Python

A function definition statement does not execute the function. Executing (calling) a function is done by using the name of the function followed by parenthesis enclosing required arguments (if any).

>>> def say_hello(): ... print('Hello') ... >>> say_hello() Hello

The execution of a function introduces a new symbol table used for the local variables of the function. More precisely, all variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the local symbol tables of enclosing functions, then in the global symbol table, and finally in the table of built-in names. Thus, global variables cannot be directly assigned a value within a function (unless named in a global statement), although they may be referenced.

>>> a = 1 >>> b = 10 >>> def fn(): ... print(a) # local a is not assigned, no enclosing function, global a referenced. ... b = 20 # local b is assigned in the local symbol table for the function. ... print(b) # local b is referenced. ... >>> fn() 1 20 >>> b # global b is not changed by the function call. 10

The actual parameters (arguments) to a function call are introduced in the local symbol table of the called function when it is called; thus, arguments are passed using call by value (where the value is always an object reference, not the value of the object). When a function calls another function, a new local symbol table is created for that call.

>>> def greet(s): ... s = "Hello " + s # s in local symbol table is reassigned. ... print(s) ... >>> person = "Bob" >>> greet(person) Hello Bob >>> person # person used to call remains bound to original object, 'Bob'. 'Bob'

The arguments used to call a function cannot be reassigned by the function, but arguments that reference mutable objects can have their values changed:

>>> def fn(arg): ... arg.append(1) ... >>> a = [1, 2, 3] >>> fn(a) >>> a [1, 2, 3, 1]