dev.rean.me
python

14. Create Function with Examples in Python (Video in Khmer)

Learn to create and use functions in Python with simple examples. Perfect for beginners.

2026-10-25 ยท 4 min read

Share:

Hello friend! ๐Ÿ‘‹ A function is a named block of code. You can call it when you need it.

In this post, I show you how to make and use Python functions. Easy and short. ๐Ÿ


๐Ÿ› ๏ธ Create and Call a Function

Use def to make a function. Call it by writing its name with ().

def say_hello():
    print("Hello!")

say_hello()

Output:

Hello!

๐ŸŽฅ Video: Create and Call Functions in Python (Khmer)


๐Ÿ“ฅ Give Information to a Function

Put a parameter inside the brackets. Give a value when you call the function.

def greet(name):
    print("Hello", name)

greet("Dara")

Output:

Hello Dara

name is a parameter. "Dara" is the value passed to it.

๐ŸŽฅ Video: Three Function Examples in Python (Khmer)


โ†ฉ๏ธ Return a Result

Use return to send a result back. You can save it in a variable.

def add(a, b):
    return a + b

answer = add(3, 4)
print(answer)           # 7

print() show a value on the screen. return give a value back to the code.


โž• Sum Numbers with a Function

Use a loop inside a function to add numbers from 1 to end.

def sum_to(end):
    total = 0
    for number in range(1, end + 1):
        total += number
    return total

print(sum_to(5))        # 15

๐ŸŽฅ Video: Function to Sum a Series of Numbers (Khmer)


๐Ÿ”ค Function with a String

def make_upper(text):
    return text.upper()

print(make_upper("hello"))   # HELLO

๐ŸŽฅ Video: Function with a String in Python (Khmer)


๐ŸŽฒ Random Number Function

Use random.randint() to get a random whole number in the range. Both ends are included.

import random

def roll_dice():
    return random.randint(1, 6)

print(roll_dice())      # A random number from 1 to 6

๐ŸŽฅ Video: Generate Random Numbers with Exercise (Khmer)


โŒ Common Errors

Forget the brackets when calling

def say_hello():
    print("Hello!")

say_hello()             # Call the function

say_hello by itself is the function. say_hello() runs it.

Forget the indentation

Code inside a function must be indented:

def say_hello():
    print("Hello!")     # Indent this line

๐Ÿ’ก Tips

  • Use def to create a function.
  • Use a clear name, like sum_to or make_upper.
  • Put () after the function name to call it.
  • Use parameters to give information to a function.
  • Use return when you need the function to give back a result.
  • Keep the function focused on one job.
  • Indent the code inside the function.

โ“ Any Question?

Tell us in comment below! ๐Ÿ‘‡

#Python #Function #Parameters #Return #LearnPython #Beginner


๐Ÿ“š Related Post

โ† Back to python
Share: