Python Full Tutorial — Part 7

If you write the same code again and again, you are not programming — you are copying.

Functions solve this problem. They allow you to write logic once and reuse it everywhere.

1. What is a Function?

A function is a block of code that runs only when called.

Basic Function

def greet():
    print("Hello, welcome to Python")

greet()
  

2. Function with Parameters

Parameters allow functions to accept data.

Function with Input

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

greet_user("Amit")
greet_user("Neha")
  

3. Return Values

Functions can return results instead of printing.

Return Example

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

result = add(10, 20)
print(result)
  

Why Return is Important

Printing shows output. Returning gives control to the program.

4. Default Parameters

Default Value

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

greet()
greet("Rahul")
  

5. Multiple Return Values

Returning Multiple Values

def calculate(a, b):
    return a + b, a - b, a * b

sum_, diff, mul = calculate(10, 5)
print(sum_, diff, mul)
  

6. Function Inside Function

Nested Function

def outer():
    def inner():
        print("Inner function")
    inner()

outer()
  

7. Real-World Example

Login Validation

def login(username, password):
    if username == "admin" and password == "1234":
        return True
    return False

if login("admin", "1234"):
    print("Access Granted")
else:
    print("Access Denied")
  

8. Why Functions Matter

Bad vs Good Code

❌ Bad

print(10 + 20)
print(10 + 20)
print(10 + 20)
  
✅ Good

def add():
    print(10 + 20)

add()
add()
add()
  

Key Takeaway

Functions are not syntax. They represent thinking in blocks. This is where beginners start becoming developers.

Next part: File Handling — reading & writing files.

Disclaimer:
This tutorial is for educational purposes only. Practice writing your own functions daily.