Introduction to Functions & Built-in Functions in Python
Functions are blocks of reusable code. Python provides many built-in functions so you don’t have to write common operations from scratch.
What is a Function?
A function is a block of code that performs a specific task. You can define your own functions (user-defined functions) or use Python’s built-in functions that are ready to use.
Key Points:
- Functions help re-use code.
- They make code organized and readable.
- They can accept inputs (arguments) and give outputs (return values).
Syntax
function_name(arguments)
Example:
# Using built-in function print()
print("Hello, Python!") # Output: Hello, Python!
# Using built-in function len()
names = ["Alice", "Bob", "Charlie"]
print(len(names)) # Output: 3
What are Built-in Functions?
Built-in functions are functions that come with Python and can be used directly without importing any module. You’ve already used some, like:
print()– display outputlen()– get the length of a collectiontype()– find the type of a variableinput()– read input from the userrange()– generate sequences of numbers
Example:
age = input("Enter your age: ")
print("You are", age, "years old")
print("Type of age variable:", type(age))
Common Mistakes for Beginners
- Forgetting parentheses:
lenvslen(). The first is the function object, the second calls it. - Capitalizing function names: Python is case-sensitive.
Print()→NameError - Passing wrong type:
len(42)→TypeError, because 42 is not iterable. - Shadowing built-in names: Naming a variable
listorsumcan break functions.
💡 Try These Yourself
- Use
print()to display your name and age. - Use
len()to find the number of characters in a string. - Use
type()to check the type of different variables. - Ask user input using
input()and display a message. - Try to call
Print()instead ofprint()and see what happens.
No comments:
Post a Comment