Jak volat funkci v Python (Příklad)

⚡ Chytré shrnutí

Funkce v Python are reusable blocks of code that run when called, defined with the def statement. They accept arguments, return values, and rely on consistent indentation to group the statements that belong to each function.

  • 🧩 def statement: A function is defined with def, a name, and parentheses, followed by a colon that opens the indented block of statements.
  • 📞 Calling functions: Writing the function name followed by parentheses runs its code, so the same logic can be reused many times.
  • ⌨️ Odsazení: Python groups a function body by consistent indentation instead of braces, so a missing space raises an IndentationError.
  • 🎯 argumenty: Values passed inside the parentheses become parameters, and defaults or keyword arguments make each call flexible.
  • ↩️ Return values: The return statement passes a result back to the caller; without it, a function returns None.
  • 🤖 Asistence AI: AI assistants such as GitHub Copilot generate function skeletons, arguments, and docstrings from a short prompt.

Jak volat funkci v Python

V čem je Funkce Python?

A Funkce v Python is a piece of code which runs when it is referenced. It is used to utilize the code in more than one place in a program. It is also called a method or a procedure. Python provides many inbuilt functions like print(), input(), compile(), and exec(), but it also gives you the freedom to create your own functions.

Jak definovat a volat funkci v Python

Funkce v Python is defined by the “def” statement followed by the function name and parentheses ( () ).

Příklad:

Let us define a function by using the command “def func1():” and call the function. The output of the function will be “I am learning Python funkce".

Definujte a volejte funkci v Python

The function call func1() invokes our def func1(): and prints the command “I am learning Python function None.”

There is a set of rules in Python programování definovat funkci.

  • Any arguments or input parameters should be placed within these parentheses.
  • The function first statement can be an optional statement — the docstring or documentation string of the function.
  • The code within every function starts with a colon (:) and should be indented (space).
  • The statement return (expression) exits a function, optionally passing back a value to the caller. A return statement with no arguments is the same as return None.

Význam odsazení (mezera) v Python

Before we get familiar with Python funkcí, je důležité, abychom rozuměli pravidlu odsazení, které se má deklarovat Python functions, and these rules are applicable to other elements of Python as well, such as declaring conditions, loops, or variables.

Python follows a particular style of indentation to define the code. Since Python functions do not have any explicit begin or end like curly braces to indicate the start and stop of the function, they have to rely on this indentation. Here we take a simple example with the “print” command. When we write the “print” function right below the def func1(): line, it will show an “indentation error: expected an indented block”.

Definujte a volejte funkci v Python

Now, when you add the indent (space) in front of the “print” function, it should print as expected.

Definujte a volejte funkci v Python

At least one indent is enough to make your code work successfully. But as a best practice, it is advisable to leave about 3–4 spaces of indent to call your function.

It is also necessary that while declaring indentation, you maintain the same indent for the rest of your code. For example, in the below screenshot, when we call another statement “still in func1” and it is not declared right below the first print statement, it will show an indentation error: “unindent does not match any other indentation level.”

Definujte a volejte funkci v Python

Now, when we apply the same indentation for both the statements and align them on the same line, it gives the expected output.

Definujte a volejte funkci v Python

Jak funkce vrátí hodnotu?

The return command in Python specifies what value to give back to the caller of the function. Let us understand this with the following example.

Krok 1) Funkce nic nevrací

Here we see when a function does not “return”. For example, we want the square of 4, and it should give the answer “16” when the code is executed. It gives that when we simply use the “print x*x” code, but when you call the function “print square” it gives “None” as an output. This is because when you call the function, recursion does not happen and it falls off the end of the function. Python returns “None” for falling off the end of the function.

Definujte a volejte funkci v Python

Step 2) Replace the print command with an assignment command

To make this clearer, we replace the print command with an assignment command. Let us check the output.

Definujte a volejte funkci v Python

When you run the command “print square (4)”, it actually returns the value of the object. Since we do not have any specific function to run over here, it returns “None”.

Step 3) Use the ‘return’ function and execute the code

Now, here we will see how to retrieve the output using the “return” command. When you use the “return” function and execute the code, it will give the output “16.”

Definujte a volejte funkci v Python

Krok 4) Spusťte příkaz 'print square'

Funkce v Python jsou samy o sobě objektem a objekt má nějakou hodnotu. Zde uvidíme jak Python treats an object. When you run the command “print square”, it returns the value of the object. Since we have not passed any argument, we do not have any specific function to run over here, so it returns a default value (0x021B2D30) which is the location of the object. In a practical Python program, you probably will not ever need to do this.

Definujte a volejte funkci v Python

Argumenty ve funkcích

An argument is a value that is passed to the function when it is called.

In other words, on the calling side it is an argument, and on the function side it is a parameter.

Podívejme se jak Python arguments work.

Krok 1) Arguments are declared in the function definition. While calling the function, you can pass the values for those arguments as shown below.

Definujte a volejte funkci v Python

Krok 2) To declare a default value for an argument, assign it a value at the function definition.

Definujte a volejte funkci v Python

Příklad: x has no default value. The default value of y=0. When we supply only one argument while calling the multiply function, Python přiřadí zadanou hodnotu x, zatímco keeping the value of y=0. Hence the multiply of x*y=0.

Definujte a volejte funkci v Python

Krok 3) This time we will change the value to y=2 instead of the default value y=0, and it will return the output as (4×2)=8.

Definujte a volejte funkci v Python

Krok 4) You can also change the order in which the arguments are passed in Python. Here we have reversed the order of the values x and y to x=4 and y=2.

Definujte a volejte funkci v Python

Krok 5) Multiple arguments can also be passed as an array. Here in the example we call the multiple args (1,2,3,4,5) by calling the (*args) function.

Příklad: We declared multiple args as the numbers (1,2,3,4,5); when we call the (*args) function, it prints out the output as (1,2,3,4,5).

Definujte a volejte funkci v Python

Tip:

  • In Python 2.7, function overloading is not supported. Function overloading is the ability to create multiple methods of the same name with a different implementation. Function overloading is fully supported in Python 3.
  • There is quite a confusion between methods and functions. Methods in Python are associated with object instances, while functions are not. When Python volá metodu, sváže první parametr tohoto volání s odkazem na příslušný objekt. Jednoduše řečeno, samostatná funkce v Python je „funkce“, zatímco funkce, která je atributem třídy nebo instance, je „metodou“.

Zde je kompletní Python 3 kód

#define a function
def func1():
   print ("I am learning Python function")
   print ("still in func1")
   
func1()

def square(x):
  	return x*x
print(square(4))

def multiply(x,y=0):
	print("value of x=",x)
	print("value of y=",y)
    
	return x*y
  
print(multiply(y=2,x=4))

Zde je kompletní Python 2 kód

#define a function
def func1():
   print " I am learning Python function"
   print " still in func1"
   
func1()

def square(x):
  	return x*x
print square(4)

def multiply(x,y=0):
	print"value of x=",x
	print"value of y=",y
    
	return x*y
  
print multiply(y=2,x=4)

Nejčastější dotazy

Ano. A Python function can return multiple values by separating them with commas after the return keyword. Python packs them into a tuple, which the caller can unpack into separate variables, for example a, b = func().

*args collects extra positional arguments into a tuple, while **kwargs collects extra keyword arguments into a dictionary. Both let a function accept a variable number of inputs, and the names args and kwargs are only a convention, not a requirement.

A docstring is a string literal placed as the first statement inside a function to document what it does. It is written in triple quotes and can be read at runtime through the function’s __doc__ attribute or the help() function.

A lambda is a small anonymous function defined in one line with the lambda keyword instead of def. It suits short, throwaway logic passed to functions such as map(), filter(), and sorted(). See this funkce lambda průvodce.

Yes. A function that calls itself is a recursive function. Recursion solves problems that break into smaller similar subproblems, such as factorials. Every recursive function needs a base case that stops the calls, otherwise Python raises a RecursionError.

A local variable is created inside a function and exists only while that function runs. A global variable is defined outside all functions and is visible everywhere. To change a global inside a function, declare it first with the global keyword.

GitHub Copilot suggests a full function body from its name or a short comment, including parameters, return statements, and docstrings. It also proposes edge-case handling and tests, letting you focus on the logic instead of typing boilerplate def blocks.

Functions organize AI and machine learning code into reusable steps such as loading data, preprocessing, training, and evaluation. They keep experiments readable and testable, and frameworks like TensorFlow and scikit-learn expose most of their behavior through well-named functions you call.

Shrňte tento příspěvek takto: