Functions are defined using the def
keyword:
def greet(name):
print("Hello", name)
greet("Jina")
# Output: Hello Jina
def add(a, b):
return a + b
result = add(5, 3)
# Output: 8
def show(name="guest")
Python provides functions like len()
, type()
, and print()
out of the box.
A function calling itself:
def factorial(n):
if n == 0:
return 1
return n * factorial(n-1)
Anonymous functions for quick computations:
square = lambda x: x ** 2
print(square(4)) # Output: 16
Use input()
to capture text input from the user.
name = input("Please enter your name: ")
print("Hello", name)
The value returned by input()
is always a string.
age = input("What is your age? ")
print(type(age)) # Output:
age = int(input("What is your age? "))
print("In 10 years, you’ll be:", age + 10)
name, city = input("Enter your name and city: ").split()
print("Hello", name, "from", city)
email = input("Enter your email address: ")
if "@" in email:
print("Valid email")
else:
print("Invalid email")
while True:
text = input("Type 'exit' to quit: ")
if text.lower() == "exit":
break
re
for complex validationThe 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)
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.