Vodič za funkcije Pythona s primjerima

Uvod u funkcije u Pythonu

Funkcija vam omogućuje definiranje bloka koda za višekratnu upotrebu koji se može izvršiti više puta u vašem programu.

Funkcije vam omogućuju stvaranje modularnijih i SUHIH rješenja složenih problema.

Iako Python već nudi mnoge ugrađene funkcije poput print()i len(), također možete definirati vlastite funkcije koje ćete koristiti u svojim projektima.

Jedna od velikih prednosti upotrebe funkcija u vašem kodu je ta što smanjuje ukupan broj redaka koda u vašem projektu.

Sintaksa

U Pythonu, definicija funkcije ima sljedeće značajke:

  1. Ključna riječ def
  2. naziv funkcije
  3. paranthesis '()', a unutar parametarskih ulaznih parametara, iako su ulazni parametri neobavezni.
  4. dvotočka ':'
  5. neki blok koda za izvršenje
  6. povratna izjava (nije obavezno)
# 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

Funkcije su blokovi koda koji se mogu ponovno koristiti jednostavnim pozivom funkcije. To omogućuje jednostavnu, elegantnu ponovnu upotrebu koda bez izričitog ponovnog pisanja odjeljaka koda. To kôd čini čitljivijim, olakšava otklanjanje pogrešaka i ograničava pogreške u tipkanju.

Funkcije u Pythonu kreiraju se pomoću defključne riječi, a nakon njih slijede ime funkcije i parametri funkcije unutar zagrada.

Funkcija uvijek vraća vrijednost. returnKljučnu riječ koristi funkcija za vraćanje vrijednosti. Ako ne želite vratiti nikakvu vrijednost, Nonevratit će se zadana vrijednost .

Ime funkcije koristi se za poziv funkcije, prosljeđujući potrebne parametre unutar zagrada.

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

Možete definirati zadane vrijednosti za parametre, na taj će način Python protumačiti da je vrijednost tog parametra zadana ako nije navedena.

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

Parametre možete proslijediti u željenom redoslijedu, koristeći naziv parametra.

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

Međutim, nije moguće proslijediti argument ključne riječi prije ne-ključne riječi

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

Funkcije su također Objekti, pa ih možete dodijeliti varijabli i koristiti tu varijablu poput funkcije.

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

Bilješke

Ako definicija funkcije uključuje parametre, morate navesti jednak broj parametara kada pozivate funkciju.

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

Blok koda koji će funkcija izvoditi uključuje sve izraze uvučene unutar funkcije.

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

Varijable definirane unutar funkcije postoje samo unutar opsega te funkcije.

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

Python interpretira funkcijski blok samo kada je funkcija pozvana, a ne kada je funkcija definirana. Dakle, čak i ako blok definicije funkcije sadrži neku vrstu pogreške, tumač python će to istaknuti samo kada se funkcija pozove.

Pogledajmo sada neke specifične funkcije s primjerima.

funkcija max ()

max() je ugrađena funkcija u Pythonu 3. Vraća najveću stavku u iterabilnom ili najvećem od dva ili više argumenata.

Argumenti

Ova funkcija uzima dva ili više brojeva ili bilo koju vrstu iterabilnosti kao argument. Dajući iterable kao argument, moramo osigurati da su svi elementi u iteralu istog tipa. To znači da ne možemo proslijediti popis koji sadrži i string i cijele vrijednosti. Sintaksa: max (iterable, * iterables [, key, default]) max (arg1, arg2, * args [, key])

Važeći argumenti:

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

Nevažeći argumenti:

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

Povratna vrijednost

Vraća se najveći predmet u iteralu. Ako su navedena dva ili više pozicijskih argumenata, vraća se najveći od pozicijskih argumenata. Ako je iterable prazan, a zadana vrijednost nije navedena, ValueErrorpodiže se a.

Uzorak koda

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

Pokreni kod

Službeni dokumenti

min () funkcija

min() je ugrađena funkcija u Pythonu 3. Vraća najmanju stavku u iterabilnom ili najmanjem od dva ili više argumenata.

Argumenti

Ova funkcija uzima dva ili više brojeva ili bilo koju vrstu iterabilnosti kao argument. Dajući iterable kao argument, moramo osigurati da su svi elementi u iteralu istog tipa. To znači da ne možemo proslijediti popis koji sadrži i string i cijele vrijednosti.

Važeći argumenti:

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

Nevažeći argumenti:

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

Povratna vrijednost

Vraća se najmanji predmet u iteralu. Ako su navedena dva ili više pozicijskih argumenata, najmanji je od pozicijskih argumenata

se vraća. Ako je iterable prazan, a zadana vrijednost nije navedena, podiže se ValueError.

Uzorak koda

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

Pokreni kod

Službeni dokumenti

funkcija divmod ()

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]