{ "cells": [ { "cell_type": "markdown", "id": "d0dacd23-3c3f-4f68-a67a-b60f00704283", "metadata": {}, "source": [ "# Python Functions\n", "\n", "A function is reusable block of code that performs a single task and can be used repeatedly in programs. In Python, a basic function can be declared as follows:\n", "\n", "``` python\n", "def addNumbers(a:int, b:int) -> int:\n", " return a+b\n", "```\n", "\n", "The above example, the following items should be noted:\n", "\n", "- The `def` keyword declares the start of a function\n", "- The name of this function is `addNumbers`\n", "- The function accepts two arguments, `a` and `b`.\n", "\n", " - Each argument can be labelled to show the expected data type (i.e. `a:int` shows that the `a` argument is expecting an `int`).\n", " - The `-> int` declares what the function will `return` (see below).\n", "\n", "- Similar to other Python constructs, the declaration line ends with a colon (`:`).\n", "- In standard circumstances, a Python function will `return` a value\n", "\n", "Functions are useful for repeated actions. A famous principle of software development is \"Don't Repeat Yourself\" (aka DRY code). As an example, writing the same message to multiple users could be performed as follows:\n", "\n", "``` python\n", "user1 = \"Carl\"\n", "user2 = \"Jim\"\n", "user3 = \"Fred\"\n", "\n", "print(\"Greetings \" + user1 + \", welcome to this program.\")\n", "print(\"Greetings \" + user2 + \", welcome to this program.\")\n", "print(\"Greetings \" + user3 + \", welcome to this program.\")\n", "```\n", "\n", "Clearly, the same lines are being repeated over and over. This could be re-written as a function:\n", "\n", "``` python\n", "def greet(user:str) -> str:\n", " return \"Greetings \" + user + \", welcome to this program.\"\n", "\n", "user1 = \"Carl\"\n", "user2 = \"Jim\"\n", "user3 = \"Fred\"\n", "\n", "print(greet(user1))\n", "print(greet(user2))\n", "print(greet(user3))\n", "```\n", "\n", "Both of these examples will have the same output, but using the function will require less effort for the programmer and be much more robust and maintainable." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.4" } }, "nbformat": 4, "nbformat_minor": 5 }