Monday, August 25, 2025

🐍INTRODUCTION TO PYTHON FUNCTIONS

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 output
  • len() – get the length of a collection
  • type() – find the type of a variable
  • input() – read input from the user
  • range() – 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: len vs len(). 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 list or sum can break functions.

💡 Try These Yourself

  1. Use print() to display your name and age.
  2. Use len() to find the number of characters in a string.
  3. Use type() to check the type of different variables.
  4. Ask user input using input() and display a message.
  5. Try to call Print() instead of print() and see what happens.

🖥️ Practice in Browser

No comments:

Post a Comment

🐍What is scikitlearn??