Python-funktionsvejledning med eksempler

Introduktion til funktioner i Python

En funktion giver dig mulighed for at definere en genanvendelig blok kode, der kan udføres mange gange i dit program.

Funktioner giver dig mulighed for at oprette mere modulære og TØRRE løsninger til komplekse problemer.

Mens Python allerede har mange indbyggede funktioner som print()og len(), kan du også definere dine egne funktioner, der skal bruges i dine projekter.

En af de store fordele ved at bruge funktioner i din kode er, at det reducerer det samlede antal kodelinjer i dit projekt.

Syntaks

I Python har en funktionsdefinition følgende funktioner:

  1. Nøgleordet def
  2. et funktionsnavn
  3. paranthesis '()' og inden for paranthesis-inputparametre, selvom inputparametrene er valgfri.
  4. et kolon ':'
  5. en eller anden blok kode, der skal udføres
  6. en returerklæring (valgfri)
# 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

Funktioner er kodeblokke, der kan genbruges ved blot at ringe til funktionen. Dette muliggør enkel, elegant genbrug af kode uden eksplicit at skrive sektioner af kode igen. Dette gør kode både mere læselig, gør det nemmere at debugge og begrænser skrivefejl.

Funktioner i Python oprettes ved hjælp af defnøgleordet efterfulgt af et funktionsnavn og funktionsparametre inden for parentes.

En funktion returnerer altid en værdi. returnNøgleordet bruges af funktionen til at returnere en værdi. Hvis du ikke vil returnere nogen værdi, Nonereturneres standardværdien .

Funktionsnavnet bruges til at kalde funktionen og videregive de nødvendige parametre inden for parenteser.

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

Du kan definere standardværdier for parametrene, på den måde fortolker Python, at værdien for denne parameter er standardværdien, hvis ingen er angivet.

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

Du kan videregive parametrene i den ønskede rækkefølge ved hjælp af navnet på parameteren.

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

Det er dog ikke muligt at overføre et søgeordsargument før et ikke-søgeordsargument

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

Funktioner er også objekter, så du kan tildele dem til en variabel og bruge den variabel som en funktion.

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

Bemærkninger

Hvis en funktionsdefinition indeholder parametre, skal du angive det samme antal parametre, når du ringer til funktionen.

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

Kodeblokken, som funktionen kører, indeholder alle udsagn, der er indrykket i funktionen.

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

Variabler, der er defineret inden for en funktion, findes kun inden for denne funktion.

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

Python fortolker kun funktionsblokken, når funktionen kaldes, og ikke når funktionen er defineret. Så selvom funktionsdefinitionsblokken indeholder en slags fejl, vil pythontolken kun påpege, at når funktionen kaldes.

Lad os nu se på nogle specifikke funktioner med eksempler.

max () funktion

max() er en indbygget funktion i Python 3. Den returnerer den største vare i en iterabel eller den største af to eller flere argumenter.

Argumenter

Denne funktion tager to eller flere tal eller en hvilken som helst iterabel som argument. Mens vi giver en iterabel som et argument, skal vi sikre os, at alle elementerne i iterablen er af samme type. Dette betyder, at vi ikke kan videregive en liste, der har både streng- og heltalværdier. Syntaks: max (iterable, * iterables [, key, default]) max (arg1, arg2, * args [, key])

Gyldige argumenter:

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

Ugyldige argumenter:

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

Returneringsværdi

Den største vare i iterablen returneres. Hvis der fremlægges to eller flere positionelle argumenter, returneres den største af positionelle argumenter. Hvis iterabelen er tom, og standard ikke er angivet, ValueErrorhæves a.

Code Sample

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

Run Code

Official Docs

min() function

min() is a built-in function in Python 3. It returns the smallest item in an iterable or the smallest of two or more arguments.

Arguments

This function takes two or more numbers or any kind of iterable as an argument. While giving an iterable as an argument we must make sure that all the elements in the iterable are of the same type. This means that we cannot pass a list which has both string and integer values stored in it.

Valid Arguments:

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

Invalid Arguments:

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

Return Value

The smallest item in the iterable is returned. If two or more positional arguments are provided, the smallest of the positional arguments

is returned. If the iterable is empty and default is not provided, a ValueError is raised.

Code Sample

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

Run Code

Official Docs

divmod() function

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

De faktiske parametre (argumenter) til et funktionsopkald introduceres i den lokale symboltabel for den kaldte funktion, når den kaldes; således overføres argumenter ved hjælp af opkald efter værdi (hvor værdien altid er en objektreference, ikke objektets værdi). Når en funktion kalder på en anden funktion, oprettes der en ny lokal symboltabel til det opkald.

>>> 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'

Argumenterne, der bruges til at kalde en funktion, kan ikke tildeles igen af ​​funktionen, men argumenter, der henviser til mutable objekter, kan få deres værdier ændret:

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