~3 min read • Updated Jul 30, 2025
1. Defining a Function
Functions are defined using the def keyword:
def greet(name):
print("Hello", name)
2. Calling a Function
greet("Jina")
# Output: Hello Jina
3. Return Values
def add(a, b):
return a + b
result = add(5, 3)
# Output: 8
4. Types of Arguments
- Positional arguments: Based on order
- Keyword arguments: Specified by name
- Default values:
def show(name="guest") - *args and **kwargs: Handle variable-length arguments
5. Built-in Functions
Python provides functions like len(), type(), and print() out of the box.
6. Recursive Functions
A function calling itself:
def factorial(n):
if n == 0:
return 1
return n * factorial(n-1)
7. Lambda Functions
Anonymous functions for quick computations:
square = lambda x: x ** 2
print(square(4)) # Output: 16
8. Variable Scope
- Global: Accessible throughout the program
- Local: Confined to the function in which it’s defined
9. Function Documentation (Docstring)
1. The input() Function
Use input() to capture text input from the user.
name = input("Please enter your name: ")
print("Hello", name)
2. Data Type of input()
The value returned by input() is always a string.
age = input("What is your age? ")
print(type(age)) # Output:
3. Converting to Numbers (Type Casting)
age = int(input("What is your age? "))
print("In 10 years, you’ll be:", age + 10)
4. Getting Multiple Values in One Line
name, city = input("Enter your name and city: ").split()
print("Hello", name, "from", city)
5. Validating User Input
email = input("Enter your email address: ")
if "@" in email:
print("Valid email")
else:
print("Invalid email")
6. Using input() in Loops
while True:
text = input("Type 'exit' to quit: ")
if text.lower() == "exit":
break
7. Safety Tips
- Always validate and sanitize user input
- Use modules like
refor complex validation - Avoid direct usage of untrusted input in critical operations
8. Conclusion
The input() function is a simple yet powerful tool for collecting text data from users. Combining it with type casting, validation logic, and control structures lets you create robust and interactive Python applications.
def greet(name):
"""Displays a welcome message"""
print("Hello", name)
10. Conclusion
Functions are central to writing clean and scalable Python code. Learning to define them, manage arguments, and apply advanced concepts like recursion or lambda expressions is key to mastering the language.
Written & researched by Dr. Shahin Siami