A user-defined function in Python is a block of reusable code created using the def
keyword. Functions help organize code, reduce repetition, and improve readability.
Python में user-defined function एक ऐसा block होता है जिसे हम खुद def
की मदद से define करते हैं। ये कोड को दुबारा इस्तेमाल करने में मदद करता है और प्रोग्राम को organized बनाता है।
def greet():
print("Hello, welcome!")
greet()
Output:
Hello, welcome!
def show_year():
print("Year: 2025")
show_year()
Output:
Year: 2025
def welcome(name):
print("Hello", name)
welcome("Abhishek")
Output:
Hello Abhishek
def add(a, b):
print("Sum:", a + b)
add(10, 5)
Output:
Sum: 15
def give_pi():
return 3.14159
print("Pi:", give_pi())
Output:
Pi: 3.14159
def get_name():
return "Python"
print(get_name())
Output:
Python
def square(x):
return x * x
print("Square:", square(6))
Output:
Square: 36
def maximum(a, b):
return a if a > b else b
print("Max:", maximum(10, 20))
Output:
Max: 20
def check_even(n):
return "Even" if n % 2 == 0 else "Odd"
print(check_even(7))
Output:
Odd
def factorial(n):
f = 1
for i in range(1, n+1):
f *= i
return f
print("Factorial:", factorial(5))
Output:
Factorial: 120
def list_sum(lst):
return sum(lst)
print(list_sum([1,2,3]))
Output:
6
def print_stars():
for i in range(5):
print("*")
print_stars()
Output:
* * * * *
def table(n):
for i in range(1, 11):
print(n, "x", i, "=", n*i)
table(4)
Output:
4 x 1 = 4 ... 4 x 10 = 40
def is_prime(n):
if n < 2:
return False
for i in range(2, n):
if n % i == 0:
return False
return True
print(is_prime(7))
Output:
True
x = 50
def show():
x = 10
print("Local x:", x)
show()
print("Global x:", x)
Output:
Local x: 10 Global x: 50
def outer():
def inner():
print("Inside inner")
print("Inside outer")
inner()
outer()
Output:
Inside outer Inside inner