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
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
defto create a function. - Use a clear name, like
sum_toormake_upper. - Put
()after the function name to call it. - Use parameters to give information to a function.
- Use
returnwhen 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