{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [], "authorship_tag": "ABX9TyP2bTdGvf/PXVCkGyZ+GmE5", "include_colab_link": true }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "markdown", "metadata": { "id": "view-in-github", "colab_type": "text" }, "source": [ "\"Open" ] }, { "cell_type": "markdown", "source": [ "# **Defining a Function:**\n", "Functions are defined using the def keyword, followed by the function name, parentheses (), and a colon :. The code block belonging to the function is indented." ], "metadata": { "id": "yKXe2tAAfnTr" } }, { "cell_type": "code", "execution_count": 2, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "tRoO62UDfl1U", "outputId": "bd4a128e-54d0-4eac-aa36-0d7b350d8b17" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Hello, Alice!\n", "Hello World!\n", "Outside function\n", "Hello John\n", "Sum: 9\n", "Square: 9\n", "Square Root of 4 is 2.0\n", "2 to the power 3 is 8\n", "I'm first call to user defined function!\n", "Again second call to the same function\n", "ID before passing: 135880511263232\n", "ID inside the function: 135880511263232\n", "ID before passing: 11654664\n", "ID inside the function: 11654664\n", "new object after increment 11 11654696\n", "value after function call 10\n", "ID before passing: 135880501554112\n", "Inside function: [10, 20, 30, 40]\n", "ID inside the function: 135880501554112\n", "list after function call [10, 20, 30, 40, 100]\n", "Hello Samay\n", "Hello Pratima\n", "Hello Steven\n", "Zahid\n", "My string\n", "Name: miki\n", "Age 50\n", "Name: miki\n", "Age 50\n", "Name: miki\n", "Age 35\n", "Evaluating positional-only arguments: \n", "66\n", "Evaluating keyword-only arguments: \n", "240\n", "Output is: \n", "10\n", "Output is: \n", "70\n", "60\n", "50\n", "a = 10 b = 20 a+b = 30\n", "Value of total : 30\n", "Value of total : 40\n", "Inside the function local total : 30\n", "Outside the function global total : 0\n", "8\n" ] } ], "source": [ "def greet(name):\n", " \"\"\"This function greets the person passed in as a parameter.\"\"\"\n", " print(f\"Hello, {name}!\")\n", "\n", "greet(\"Alice\") # Output: Hello, Alice!\n", "\n", "def greet():\n", " print('Hello World!')\n", "\n", "# call the function\n", "greet()\n", "\n", "print('Outside function')\n", "\n", "def greet(name):\n", " print(\"Hello\", name)\n", "\n", "# pass argument\n", "greet(\"John\")\n", "\n", "# function with two arguments\n", "def add_numbers(num1, num2):\n", " sum = num1 + num2\n", " print(\"Sum: \", sum)\n", "\n", "# function call with two values\n", "add_numbers(5, 4)\n", "\n", "# function definition\n", "def find_square(num):\n", " result = num * num\n", " return result\n", "\n", "# function call\n", "square = find_square(3)\n", "\n", "print('Square:', square)\n", "\n", "def future_function():\n", " pass\n", "\n", "# this will execute without any action or error\n", "future_function()\n", "\n", "import math\n", "\n", "# sqrt computes the square root\n", "square_root = math.sqrt(4)\n", "\n", "print(\"Square Root of 4 is\",square_root)\n", "\n", "# pow() comptes the power\n", "power = pow(2, 3)\n", "\n", "print(\"2 to the power 3 is\",power)\n", "\n", "def greetings():\n", " \"This is docstring of greetings function\"\n", " print (\"Hello World\")\n", " return\n", "\n", "# Function definition is here\n", "def printme( str ):\n", " \"This prints a passed string into this function\"\n", " print (str)\n", " return;\n", "\n", "# Now you can call the function\n", "printme(\"I'm first call to user defined function!\")\n", "printme(\"Again second call to the same function\")\n", "\n", "def testfunction(arg):\n", " print (\"ID inside the function:\", id(arg))\n", "\n", "var = \"Hello\"\n", "print (\"ID before passing:\", id(var))\n", "testfunction(var)\n", "\n", "def testfunction(arg):\n", " print (\"ID inside the function:\", id(arg))\n", " arg = arg + 1\n", " print (\"new object after increment\", arg, id(arg))\n", "\n", "var=10\n", "print (\"ID before passing:\", id(var))\n", "testfunction(var)\n", "print (\"value after function call\", var)\n", "\n", "def testfunction(arg):\n", " print (\"Inside function:\",arg)\n", " print (\"ID inside the function:\", id(arg))\n", " arg=arg.append(100)\n", "\n", "var=[10, 20, 30, 40]\n", "print (\"ID before passing:\", id(var))\n", "testfunction(var)\n", "print (\"list after function call\", var)\n", "\n", "def greetings(name):\n", " \"This is docstring of greetings function\"\n", " print (\"Hello {}\".format(name))\n", " return\n", "\n", "greetings(\"Samay\")\n", "greetings(\"Pratima\")\n", "greetings(\"Steven\")\n", "\n", "# Function definition is here\n", "def printme( str ):\n", " \"This prints a passed string into this function\"\n", " print (str)\n", " return;\n", "\n", "# Now you can call printme function\n", "printme(\"Zahid\")\n", "\n", "# Function definition is here\n", "def printme( str ):\n", " \"This prints a passed string into this function\"\n", " print (str)\n", " return;\n", "\n", "# Now you can call printme function\n", "printme( str = \"My string\")\n", "\n", "# Function definition is here\n", "def printinfo( name, age ):\n", " \"This prints a passed info into this function\"\n", " print (\"Name: \", name)\n", " print (\"Age \", age)\n", " return;\n", "\n", "# Now you can call printinfo function\n", "printinfo( age=50, name=\"miki\" )\n", "\n", "# Function definition is here\n", "def printinfo( name, age = 35 ):\n", " \"This prints a passed info into this function\"\n", " print (\"Name: \", name)\n", " print (\"Age \", age)\n", " return;\n", "\n", "# Now you can call printinfo function\n", "printinfo( age=50, name=\"miki\" )\n", "printinfo( name=\"miki\" )\n", "\n", "def posFun(x, y, /, z):\n", " print(x + y + z)\n", "\n", "print(\"Evaluating positional-only arguments: \")\n", "posFun(33, 22, z=11)\n", "\n", "def posFun(*, num1, num2, num3):\n", " print(num1 * num2 * num3)\n", "\n", "print(\"Evaluating keyword-only arguments: \")\n", "posFun(num1=6, num2=8, num3=5)\n", "\n", "# Function definition is here\n", "def printinfo( arg1, *vartuple ):\n", " \"This prints a variable passed arguments\"\n", " print (\"Output is: \")\n", " print (arg1)\n", " for var in vartuple:\n", " print (var)\n", " return;\n", "\n", "# Now you can call printinfo function\n", "printinfo( 10 )\n", "printinfo( 70, 60, 50 )\n", "\n", "def add(x,y):\n", " z=x+y\n", " return z\n", "a=10\n", "b=20\n", "result = add(a,b)\n", "print (\"a = {} b = {} a+b = {}\".format(a, b, result))\n", "\n", "# Function definition is here\n", "sum = lambda arg1, arg2: arg1 + arg2;\n", "\n", "# Now you can call sum as a function\n", "print (\"Value of total : \", sum( 10, 20 ))\n", "print (\"Value of total : \", sum( 20, 20 ))\n", "\n", "total = 0; # This is global variable.\n", "# Function definition is here\n", "def sum( arg1, arg2 ):\n", " # Add both the parameters and return them.\"\n", " total = arg1 + arg2; # Here total is local variable.\n", " print (\"Inside the function local total : \", total)\n", " return total;\n", "\n", "# Now you can call sum function\n", "sum( 10, 20 );\n", "print (\"Outside the function global total : \", total)\n", "\n", "def add_numbers(a, b):\n", "\n", " return a + b\n", "\n", "result = add_numbers(3, 5)\n", "\n", "print(result) # Output: 8" ] }, { "cell_type": "markdown", "source": [ "# **Types of Functions:**\n", "Built-in Functions: Functions pre-defined in Python, always available (e.g., print(), len(), int()).\n", "\n", "Module Functions: Functions available after importing a specific module (e.g., math.sqrt() after import math).\n", "\n", "User-Defined Functions: Functions created by the programmer for specific tasks.\n", "\n", "Key Benefits of Using Functions:\n", "Code Reusability: Avoids writing the same code multiple times.\n", "\n", "Modularity: Breaks down complex problems into smaller, manageable parts.\n", "\n", "Readability: Makes code easier to understand and maintain.\n", "\n", "Easier Debugging: Isolates issues to specific function blocks." ], "metadata": { "id": "R3cSjzTCfoAa" } }, { "cell_type": "code", "source": [ "def greet(name):\n", "\n", " return f\"Hello, {name}!\"\n", "\n", "message = greet(\"Alice\")\n", "\n", "print(message) # Output: Hello, Alice!\n", "\n", "def add_numbers(a, b):\n", "\n", " return a + b\n", "\n", "result = add_numbers(3, 5)\n", "\n", "print(result) # Output: 8\n", "\n", "def factorial(n):\n", "\n", " if n == 1:\n", "\n", " return 1\n", "\n", " else:\n", "\n", " return n * factorial(n - 1)\n", "\n", "print(factorial(5)) # Output: 120\n", "\n", "def square(x):\n", "\n", " return x * x\n", "\n", "numbers = [1, 2, 3, 4, 5]\n", "\n", "squared_numbers = list(map(square, numbers))\n", "\n", "print(squared_numbers) # Output: [1, 4, 9, 16, 25]\n", "\n", "def generate_numbers():\n", "\n", " for i in range(1, 6):\n", "\n", " yield i\n", "\n", "for number in generate_numbers():\n", "\n", " print(number) # Output: 1 2 3 4 5\n", "\n", "def greet():\n", "\n", " print(\"Hello, world!\")\n", "\n", "greet() # Output: Hello, world!\n", "\n", "def add_numbers(a, b):\n", "\n", " return a + b\n", "\n", "result = add_numbers(3, 5)\n", "\n", "print(result) # Output: 8\n", "\n", "def greet(name=\"Guest\"):\n", "\n", " print(f\"Hello, {name}!\")\n", "\n", "greet() # Output: Hello, Guest!\n", "\n", "greet(\"Alice\") # Output: Hello, Alice!\n", "\n", "'''\n", "def sum_all(*args):\n", "\n", " return sum(args)\n", "\n", "result = sum_all(1, 2, 3, 4, 5)\n", "\n", "print(result) # Output: 15\n", "'''\n", "def print_info(name, age):\n", "\n", " print(f\"Name: {name}, Age: {age}\")\n", "\n", "print_info(age=30, name=\"John\") # Output: Name: John, Age: 30\n", "\n", "add = lambda x, y: x + y\n", "\n", "print(add(3, 5)) # Output: 8\n", "\n", "def factorial(n):\n", "\n", " if n == 1:\n", "\n", " return 1\n", "\n", " else:\n", "\n", " return n * factorial(n - 1)\n", "\n", "print(factorial(5)) # Output: 120\n", "\n", "def add_numbers(a, b):\n", "\n", " return a + b\n", "\n", "result = add_numbers(3, 5)\n", "\n", "print(result) # Output: 8\n", "\n", "def greet(name=\"Guest\"):\n", "\n", " print(f\"Hello, {name}!\")\n", "\n", "greet() # Output: Hello, Guest!\n", "\n", "greet(\"Alice\") # Output: Hello, Alice!\n", "'''\n", "def sum_all(*args):\n", "\n", " return sum(args)\n", "\n", "result = sum_all(1, 2, 3, 4, 5)\n", "\n", "print(result) # Output: 15\n", "'''\n", "def print_info(name, age):\n", "\n", " print(f\"Name: {name}, Age: {age}\")\n", "\n", "print_info(age=30, name=\"John\") # Output: Name: John, Age: 30\n", "\n", "add = lambda x, y: x + y\n", "\n", "print(add(3, 5)) # Output: 8\n", "\n", "def factorial(n):\n", "\n", " if n == 1:\n", "\n", " return 1\n", "\n", " else:\n", "\n", " return n * factorial(n - 1)\n", "\n", "print(factorial(5)) # Output: 120\n", "\n", "def add_numbers(a, b):\n", "\n", " return a + b\n", "\n", "result = add_numbers(3, 5)\n", "\n", "print(result) # Output: 8\n", "\n", "def add(a, b):\n", "\n", " return a + b\n", "\n", "result = add(3, 5)\n", "\n", "print(result) # Output: 8\n", "\n", "def print_info(name, age):\n", "\n", " print(f\"Name: {name}, Age: {age}\")\n", "\n", "print_info(age=30, name=\"John\") # Output: Name: John, Age: 30\n", "\n", "def greet(name=\"Guest\"):\n", "\n", " print(f\"Hello, {name}!\")\n", "\n", "greet() # Output: Hello, Guest!\n", "\n", "greet(\"Alice\") # Output: Hello, Alice!\n", "\n", "def greet(name=\"Guest\"):\n", "\n", " print(f\"Hello, {name}!\")\n", "\n", "greet() # Output: Hello, Guest!\n", "\n", "greet(\"Alice\") # Output: Hello, Alice\n", "\n", "\n", "\n", "\n", "def print_details(**kwargs):\n", "\n", " for key, value in kwargs.items():\n", "\n", " print(f\"{key}: {value}\")\n", "\n", "print_details(name=\"Alice\", age=30, city=\"New York\")\n", "\n" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "SPuIrtchfoHD", "outputId": "82f6828e-bf9a-4fbb-e646-912125436fcd" }, "execution_count": 7, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Hello, Alice!\n", "8\n", "120\n", "[1, 4, 9, 16, 25]\n", "1\n", "2\n", "3\n", "4\n", "5\n", "Hello, world!\n", "8\n", "Hello, Guest!\n", "Hello, Alice!\n", "Name: John, Age: 30\n", "8\n", "120\n", "8\n", "Hello, Guest!\n", "Hello, Alice!\n", "Name: John, Age: 30\n", "8\n", "120\n", "8\n", "8\n", "Name: John, Age: 30\n", "Hello, Guest!\n", "Hello, Alice!\n", "Hello, Guest!\n", "Hello, Alice!\n", "name: Alice\n", "age: 30\n", "city: New York\n" ] } ] }, { "cell_type": "markdown", "source": [ "# **Python Library Functions**\n", "Python provides some built-in functions that can be directly used in our program.\n", "\n", "We don't need to create the function, we just need to call them.\n", "\n", "Some Python library functions are:\n", "\n", "print() - prints the string inside the quotation marks\n", "sqrt() - returns the square root of a number\n", "pow() - returns the power of a number\n", "These library functions are defined inside the module. And to use them, we must include the module inside our program.\n", "\n", "For example, sqrt() is defined inside the math module.\n", "\n", "Note: To learn more about library functions, please visit Python Library Functions." ], "metadata": { "id": "uToMen9IfoSa" } }, { "cell_type": "code", "source": [ "def greet(name=\"Guest\"):\n", "\n", " print(f\"Hello, {name}!\")\n", "\n", "greet() # Output: Hello, Guest!\n", "\n", "greet(\"Alice\") # Output: Hello, Alice\n", "\n", "def print_info(name, age):\n", "\n", " print(f\"Name: {name}, Age: {age}\")\n", "\n", "print_info(age=30, name=\"John\") # Output: Name: John, Age: 30\n", "\n", "def add(a, b):\n", "\n", " return a + b\n", "\n", "result = add(3, 5)\n", "\n", "print(result) # Output: 8\n", "\n", "def get_name_and_age():\n", "\n", " name = \"Alice\"\n", "\n", " age = 30\n", "\n", " return name, age\n", "\n", "name, age = get_name_and_age()\n", "\n", "print(f\"Name: {name}, Age: {age}\") # Output: Name: Alice, Age: 30\n", "\n", "def get_even_numbers(limit):\n", "\n", " evens = []\n", "\n", " for num in range(limit):\n", "\n", " if num % 2 == 0:\n", "\n", " evens.append(num)\n", "\n", " return evens\n", "\n", "even_numbers = get_even_numbers(10)\n", "\n", "print(even_numbers) # Output: [0, 2, 4, 6, 8]\n", "\n", "def check_positive(number):\n", "\n", " if number <= 0:\n", "\n", " return \"Not a positive number\"\n", "\n", " return \"Positive number\"\n", "\n", "result = check_positive(-5)\n", "\n", "print(result) # Output: Not a positive number\n", "\n", "result = check_positive(10)\n", "\n", "print(result) # Output: Positive number\n", "\n", "def outer_function():\n", "\n", " def inner_function():\n", "\n", " print(\"Hello from the inner function!\")\n", "\n", "\n", "\n", " print(\"Hello from the outer function!\")\n", "\n", " inner_function()\n", "\n", "outer_function()\n", "\n", "def outer_function(message):\n", "\n", " def inner_function():\n", "\n", " print(f\"Message from outer function: {message}\")\n", "\n", "\n", "\n", " inner_function()\n", "\n", "outer_function(\"Hello, World!\")\n", "\n", "def make_multiplier(x):\n", "\n", " def multiplier(n):\n", "\n", " return x * n\n", "\n", " return multiplier\n", "\n", "times_two = make_multiplier(2)\n", "\n", "times_three = make_multiplier(3)\n", "\n", "print(times_two(5)) # Output: 10\n", "\n", "print(times_three(5)) # Output: 15\n", "\n", "def calculate_area_and_perimeter(length, width):\n", "\n", " def area():\n", "\n", " return length * width\n", "\n", "\n", "\n", " def perimeter():\n", "\n", " return 2 * (length + width)\n", "\n", "\n", "\n", " return area(), perimeter()\n", "\n", "area, perimeter = calculate_area_and_perimeter(5, 3)\n", "\n", "print(f\"Area: {area}, Perimeter: {perimeter}\")\n", "\n", "my_list = [1, 2, 3, 4, 5]\n", "\n", "print(len(my_list)) # Output: 5\n", "\n", "my_string = \"Hello, World!\"\n", "\n", "print(len(my_string)) # Output: 13\n", "\n", "numbers = [10, 20, 30, 40, 50]\n", "\n", "print(max(numbers)) # Output: 50\n", "\n", "print(min(numbers)) # Output: 10\n", "'''\n", "numbers = [1, 2, 3, 4, 5]\n", "\n", "print(sum(numbers)) # Output: 15\n", "'''\n", "numbers = [3, 1, 4, 1, 5, 9]\n", "\n", "sorted_numbers = sorted(numbers)\n", "\n", "print(sorted_numbers) # Output: [1, 1, 3, 4, 5, 9]\n", "\n", "number = -10\n", "\n", "print(abs(number)) # Output: 10\n", "\n", "number = 3.14159\n", "\n", "print(round(number, 2)) # Output: 3.14\n", "\n", "items = ['apple', 'banana', 'cherry']\n", "\n", "for index, item in enumerate(items):\n", "\n", " print(index, item)\n", "\n", "names = ['Alice', 'Bob', 'Charlie']\n", "\n", "scores = [85, 90, 95]\n", "\n", "combined = zip(names, scores)\n", "\n", "for name, score in combined:\n", "\n", " print(name, score)\n", "\n", "def square(x):\n", "\n", " return x * x\n", "\n", "numbers = [1, 2, 3, 4, 5]\n", "\n", "squared_numbers = map(square, numbers)\n", "\n", "print(list(squared_numbers)) # Output: [1, 4, 9, 16, 25]\n", "\n", "def is_even(x):\n", "\n", " return x % 2 == 0\n", "\n", "numbers = [1, 2, 3, 4, 5, 6]\n", "\n", "even_numbers = filter(is_even, numbers)\n", "\n", "print(list(even_numbers)) # Output: [2, 4, 6]\n", "\n", "def hello():\n", " name = str(input(\"Enter your name: \"))\n", " if name:\n", " print (\"Hello \" + str(name))\n", " else:\n", " print(\"Hello World\")\n", " return\n", "\n", "hello()" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "LF9KfLQMfoab", "outputId": "6238116d-262f-45e9-a0ed-0934058681fc" }, "execution_count": 9, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Hello, Guest!\n", "Hello, Alice!\n", "Name: John, Age: 30\n", "8\n", "Name: Alice, Age: 30\n", "[0, 2, 4, 6, 8]\n", "Not a positive number\n", "Positive number\n", "Hello from the outer function!\n", "Hello from the inner function!\n", "Message from outer function: Hello, World!\n", "10\n", "15\n", "Area: 15, Perimeter: 16\n", "5\n", "13\n", "50\n", "10\n", "[1, 1, 3, 4, 5, 9]\n", "10\n", "3.14\n", "0 apple\n", "1 banana\n", "2 cherry\n", "Alice 85\n", "Bob 90\n", "Charlie 95\n", "[1, 4, 9, 16, 25]\n", "[2, 4, 6]\n", "Enter your name: Zahidf\n", "Hello Zahidf\n" ] } ] }, { "cell_type": "markdown", "source": [ "# **Types of Python Functions**\n", "Python provides the following types of functions −\n", "\n", "Sr.No\tType & Description\n", "1\n", "Built-in functions\n", "\n", "Python's standard library includes number of built-in functions. Some of Python's built-in functions are print(), int(), len(), sum(), etc. These functions are always available, as they are loaded into computer's memory as soon as you start Python interpreter.\n", "\n", "2\n", "Functions defined in built-in modules\n", "\n", "The standard library also bundles a number of modules. Each module defines a group of functions. These functions are not readily available. You need to import them into the memory from their respective modules.\n", "\n", "3\n", "User-defined functions\n", "\n", "In addition to the built-in functions and functions in the built-in modules, you can also create your own functions. These functions are called user-defined functions." ], "metadata": { "id": "DbFWICpvfojb" } } ] }