{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [], "authorship_tag": "ABX9TyMbJYcWNFaCmqaP9rH1Tbyq", "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": [ "# **How to add docstrings to a Python function**\n", "Another essential aspect of writing functions in Python: docstrings. Docstrings describe what your function does, such as the computations it performs or its return values. These descriptions serve as documentation for your function so that anyone who reads your function’s docstring understands what your function does, without having to trace through all the code in the function definition.\n", "\n", "Function docstrings are placed in the immediate line after the function header and are placed in between triple quotation marks. An appropriate Docstring for your hello() function is ‘Prints “Hello World”’." ], "metadata": { "id": "xq0fQ3mNojw1" } }, { "cell_type": "code", "execution_count": 8, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "nd4XxSw-oWzZ", "outputId": "95466384-0173-4ede-94fc-50b1fa1385b9" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "barkbark\n", "Hello Jane! Are you from Paris?\n", "Please pay $165.0\n", "Please pay $230.0\n", "Please pay $179.53\n", "Volume of the cuboid is 660.0 cubic units\n", "660.0\n", "The numbers that you have add up to 186\n", "The numbers that you have add up to 141\n", "The numbers that you have add up to 251\n", "Enter your name: Zahid\n", "Hello Zahid\n", "barkbark\n", "3\n", "9\n", "This is not part of testfunction\n", "The Farmer’s Market is selling toothpaste for $1\n", "Length = 1\n", "Width = 2\n", "Depth = 3\n", "Length = 5\n", "Width = 4\n", "Depth = 2\n", "Length = 2\n", "Width = 4\n", "Depth = 3\n", "5\n", "2\n", "2018 is not a leap year.\n", "Hello\n", "7\n", "None\n" ] } ], "source": [ "def hello():\n", " \"\"\"Prints \"Hello World\".\n", " Returns:\n", " None\n", " \"\"\"\n", " print(\"Hello World\")\n", " return\n", "\n", "class Dog:\n", " \"\"\"\n", " Requires:\n", " legs - Legs so that the dog can walk.\n", " color - A color of the fur.\n", " \"\"\"\n", "\n", " def __init__(self, legs, color):\n", " self.legs = legs\n", " self.color = color\n", "\n", " def bark(self):\n", " bark = \"bark\" * 2\n", " return bark\n", "\n", "if __name__ == \"__main__\":\n", " dog = Dog(4, \"brown\")\n", " bark = dog.bark()\n", " print(bark)\n", "\n", "def my_func(name,place):\n", " print(f\"Hello {name}! Are you from {place}?\")\n", "\n", "my_func(\"Jane\",\"Paris\")\n", "\n", "def total_calc(bill_amount,tip_perc=10):\n", " total = bill_amount*(1 + 0.01*tip_perc)\n", " total = round(total,2)\n", " print(f\"Please pay ${total}\")\n", "\n", "# specify only bill_amount\n", "# default value of tip percentage is used\n", "\n", "total_calc(150)\n", "total_calc(200,15)\n", "total_calc(167,7.5)\n", "\n", "def volume_of_cuboid(length,breadth,height):\n", " return length*breadth*height\n", "\n", "volume = volume_of_cuboid(5.5,20,6)\n", "print(f\"Volume of the cuboid is {volume} cubic units\")\n", "\n", "returned_values = volume_of_cuboid(5.5,20,6)\n", "print(returned_values)\n", "\n", "def my_var_sum(*args):\n", " sum = 0\n", " for arg in args:\n", " sum += arg\n", " return sum\n", "\n", "\n", "# Example 1 with 4 numbers\n", "sum = my_var_sum(99,10,54,23)\n", "print(f\"The numbers that you have add up to {sum}\")\n", "\n", "# Example 2 with 3 numbers\n", "sum = my_var_sum(9,87,45)\n", "print(f\"The numbers that you have add up to {sum}\")\n", "\n", "# Example 3 with 6 numbers\n", "sum = my_var_sum(5,21,36,79,45,65)\n", "print(f\"The numbers that you have add up to {sum}\")\n", "\n", "\n", "def foo(x, y):\n", " x = x - y\n", " return x + 1\n", "\n", "\n", "def caller():\n", " x = 2\n", " y = 3\n", " z = foo(y, x)\n", " print(x, y, z)\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()\n", "\n", "\n", "\n", "class Dog:\n", " \"\"\"\n", " Requires:\n", " legs - Legs so that the dog can walk.\n", " color - A color of the fur.\n", " \"\"\"\n", "\n", " def __init__(self, legs, color):\n", " self.legs = legs\n", " self.color = color\n", "\n", " def bark(self):\n", " bark = \"bark\" * 2\n", " return bark\n", "\n", "if __name__ == \"__main__\":\n", " dog = Dog(4, \"brown\")\n", " bark = dog.bark()\n", " print(bark)\n", "\n", "\n", "def write_a_book(character, setting, special_skill):\n", " print(character + \" is in \" +\n", " setting + \" practicing her \" +\n", " special_skill)\n", "\n", "def ready_for_school(backpack, pencil_case):\n", " if (backpack == 'full' and pencil_case == 'full'):\n", " print (\"I'm ready for school!\")\n", "\n", "# Define a function my_function() with parameter x\n", "\n", "def my_function(x):\n", " return x + 1\n", "\n", "# Invoke the function\n", "\n", "print(my_function(2)) # Output: 3\n", "print(my_function(3 + 5)) # Output: 9\n", "\n", "\n", "# Indentation is used to identify code blocks\n", "\n", "def testfunction(number):\n", " # This code is part of testfunction\n", " print(\"Inside the testfunction\")\n", " sum = 0\n", " for x in range(number):\n", " # More indentation because 'for' has a code block\n", " # but still part of he function\n", " sum += x\n", " return sum\n", "print(\"This is not part of testfunction\")\n", "\n", "\n", "def sales(grocery_store, item_on_sale, cost):\n", " print(grocery_store + \" is selling \" + item_on_sale + \" for \" + cost)\n", "\n", "sales(\"The Farmer’s Market\", \"toothpaste\", \"$1\")\n", "\n", "\n", "def findvolume(length=1, width=1, depth=1):\n", " print(\"Length = \" + str(length))\n", " print(\"Width = \" + str(width))\n", " print(\"Depth = \" + str(depth))\n", " return length * width * depth;\n", "\n", "findvolume(1, 2, 3)\n", "findvolume(length=5, depth=2, width=4)\n", "findvolume(2, depth=3, width=4)\n", "\n", "def square_point(x, y, z):\n", " x_squared = x * x\n", " y_squared = y * y\n", " z_squared = z * z\n", " # Return all three values:\n", " return x_squared, y_squared, z_squared\n", "\n", "three_squared, four_squared, five_squared = square_point(3, 4, 5)\n", "\n", "a = 5\n", "\n", "def f1():\n", " a = 2\n", " print(a)\n", "\n", "print(a) # Will print 5\n", "f1() # Will print 2\n", "\n", "def check_leap_year(year):\n", " if year % 4 == 0:\n", " return str(year) + \" is a leap year.\"\n", " else:\n", " return str(year) + \" is not a leap year.\"\n", "\n", "year_to_check = 2018\n", "returned_value = check_leap_year(year_to_check)\n", "print(returned_value) # 2018 is not a leap year.\n", "\n", "a = \"Hello\"\n", "\n", "def prints_a():\n", " print(a)\n", "\n", "# will print \"Hello\"\n", "prints_a()\n", "\n", "\n", "def my_function(value):\n", " print(value)\n", "\n", "# Pass the value 7 into the function\n", "value = my_function(7)\n", "\n", "# Causes an error as `value` no longer exists\n", "print(value)\n", "\n" ] }, { "cell_type": "markdown", "source": [ "# **A Quick Recap**\n", "Let's quickly summarize what we've covered. In this tutorial, we've learned:\n", "\n", "how to define functions,\n", "\n", "how to pass in arguments to a function,\n", "\n", "how to create functions with default and variable number of arguments, and\n", "\n", "how to create a function with return value(s)." ], "metadata": { "id": "mtkKMdSBokdE" } }, { "cell_type": "code", "source": [ "def my_function():\n", " print(\"Hello From My Function!\")\n", "\n", "\n", "def my_function_with_args(username, greeting):\n", " print(\"Hello, %s , From My Function!, I wish you %s\"%(username, greeting))\n", "\n", "# Define our 3 functions\n", "def my_function():\n", " print(\"Hello From My Function!\")\n", "\n", "def my_function_with_args(username, greeting):\n", " print(\"Hello, %s, From My Function!, I wish you %s\"%(username, greeting))\n", "\n", "def sum_two_numbers(a, b):\n", " return a + b\n", "\n", "# print(a simple greeting)\n", "my_function()\n", "\n", "#prints - \"Hello, John Doe, From My Function!, I wish you a great year!\"\n", "my_function_with_args(\"John Doe\", \"a great year!\")\n", "\n", "# after this line x will hold the value 3!\n", "x = sum_two_numbers(1,2)\n", "\n", "print(x)\n", "\n", "# Modify this function to return a list of strings as defined above\n", "def list_benefits():\n", " return \"More organized code\", \"More readable code\", \"Easier code reuse\", \"Allowing programmers to share and connect code together\"\n", "\n", "# Modify this function to concatenate to each benefit - \" is a benefit of functions!\"\n", "def build_sentence(benefit):\n", " return \"%s is a benefit of functions!\" % benefit\n", "\n", "\n", "def name_the_benefits_of_functions():\n", " list_of_benefits = list_benefits()\n", " for benefit in list_of_benefits:\n", " print(build_sentence(benefit))\n", "\n", "name_the_benefits_of_functions()\n", "\n", "\n", "# Define a function that returns the maximum of two numbers\n", "def max_of_two(x, y):\n", " # Check if x is greater than y\n", " if x > y:\n", " # If x is greater, return x\n", " return x\n", " # If y is greater or equal to x, return y\n", " return y\n", "\n", "# Define a function that returns the maximum of three numbers\n", "def max_of_three(x, y, z):\n", " # Call max_of_two function to find the maximum of y and z,\n", " # then compare it with x to find the overall maximum\n", " return max_of_two(x, max_of_two(y, z))\n", "\n", "# Print the result of calling max_of_three function with arguments 3, 6, and -5\n", "print(max_of_three(3, 6, -5))\n", "\n", "\n", "# Define a function named 'sum' that takes a list of numbers as input\n", "def sum(numbers):\n", " # Initialize a variable 'total' to store the sum of numbers, starting at 0\n", " total = 0\n", "\n", " # Iterate through each element 'x' in the 'numbers' list\n", " for x in numbers:\n", " # Add the current element 'x' to the 'total'\n", " total += x\n", "\n", " # Return the final sum stored in the 'total' variable\n", " return total\n", "\n", "# Print the result of calling the 'sum' function with a tuple of numbers (8, 2, 3, 0, 7)\n", "print(sum((8, 2, 3, 0, 7)))\n", "\n", "\n", "# Define a function named 'multiply' that takes a list of numbers as input\n", "def multiply(numbers):\n", " # Initialize a variable 'total' to store the multiplication result, starting at 1\n", " total = 1\n", "\n", " # Iterate through each element 'x' in the 'numbers' list\n", " for x in numbers:\n", " # Multiply the current element 'x' with the 'total'\n", " total *= x\n", "\n", " # Return the final multiplication result stored in the 'total' variable\n", " return total\n", "\n", "# Print the result of calling the 'multiply' function with a tuple of numbers (8, 2, 3, -1, 7)\n", "print(multiply((8, 2, 3, -1, 7)))\n", "\n", "\n", "# Define a function named 'multiply' that takes a list of numbers as input\n", "def multiply(numbers):\n", " # Initialize a variable 'total' to store the multiplication result, starting at 1\n", " total = 1\n", "\n", " # Iterate through each element 'x' in the 'numbers' list\n", " for x in numbers:\n", " # Multiply the current element 'x' with the 'total'\n", " total *= x\n", "\n", " # Return the final multiplication result stored in the 'total' variable\n", " return total\n", "\n", "# Print the result of calling the 'multiply' function with a tuple of numbers (8, 2, 3, -1, 7)\n", "print(multiply((8, 2, 3, -1, 7)))\n", "\n", "\n", "# Define a function named 'string_reverse' that takes a string 'str1' as input\n", "def string_reverse(str1):\n", " # Initialize an empty string 'rstr1' to store the reversed string\n", " rstr1 = ''\n", "\n", " # Calculate the length of the input string 'str1'\n", " index = len(str1)\n", "\n", " # Execute a while loop until 'index' becomes 0\n", " while index > 0:\n", " # Concatenate the character at index - 1 of 'str1' to 'rstr1'\n", " rstr1 += str1[index - 1]\n", "\n", " # Decrement the 'index' by 1 for the next iteration\n", " index = index - 1\n", "\n", " # Return the reversed string stored in 'rstr1'\n", " return rstr1\n", "\n", "# Print the result of calling the 'string_reverse' function with the input string '1234abcd'\n", "print(string_reverse('1234abcd'))\n", "\n", "\n", "# Define a function named 'factorial' that calculates the factorial of a number 'n'\n", "def factorial(n):\n", " # Check if the number 'n' is 0\n", " if n == 0:\n", " # If 'n' is 0, return 1 (factorial of 0 is 1)\n", " return 1\n", " else:\n", " # If 'n' is not 0, recursively call the 'factorial' function with (n-1) and multiply it with 'n'\n", " return n * factorial(n - 1)\n", "\n", "# Ask the user to input a number to compute its factorial and store it in variable 'n'\n", "n = int(input(\"Input a number to compute the factorial: \"))\n", "\n", "# Print the factorial of the number entered by the user by calling the 'factorial' function\n", "print(factorial(n))\n", "\n", "\n", "# Define a function named 'test_range' that checks if a number 'n' is within the range 3 to 8 (inclusive)\n", "def test_range(n):\n", " # Check if 'n' is within the range from 3 to 8 (inclusive) using the 'in range()' statement\n", " if n in range(3, 9):\n", " # If 'n' is within the range, print that 'n' is within the given range\n", " print(\"%s is in the range\" % str(n))\n", " else:\n", " # If 'n' is outside the range, print that the number is outside the given range\n", " print(\"The number is outside the given range.\")\n", "\n", "# Call the 'test_range' function with the argument 5\n", "test_range(5)\n", "\n", "\n", "# Define a function named 'string_test' that counts the number of upper and lower case characters in a string 's'\n", "def string_test(s):\n", " # Create a dictionary 'd' to store the count of upper and lower case characters\n", " d = {\"UPPER_CASE\": 0, \"LOWER_CASE\": 0}\n", "\n", " # Iterate through each character 'c' in the string 's'\n", " for c in s:\n", " # Check if the character 'c' is in upper case\n", " if c.isupper():\n", " # If 'c' is upper case, increment the count of upper case characters in the dictionary\n", " d[\"UPPER_CASE\"] += 1\n", " # Check if the character 'c' is in lower case\n", " elif c.islower():\n", " # If 'c' is lower case, increment the count of lower case characters in the dictionary\n", " d[\"LOWER_CASE\"] += 1\n", " else:\n", " # If 'c' is neither upper nor lower case (e.g., punctuation, spaces), do nothing\n", " pass\n", "\n", " # Print the original string 's'\n", " print(\"Original String: \", s)\n", "\n", " # Print the count of upper case characters\n", " print(\"No. of Upper case characters: \", d[\"UPPER_CASE\"])\n", "\n", " # Print the count of lower case characters\n", " print(\"No. of Lower case Characters: \", d[\"LOWER_CASE\"])\n", "\n", "# Call the 'string_test' function with the input string 'The quick Brown Fox'\n", "string_test('The quick Brown Fox')\n", "\n", "\n", "# Define a function named 'unique_list' that takes a list 'l' as input and returns a list of unique elements\n", "def unique_list(l):\n", " # Create an empty list 'x' to store unique elements\n", " x = []\n", "\n", " # Iterate through each element 'a' in the input list 'l'\n", " for a in l:\n", " # Check if the element 'a' is not already present in the list 'x'\n", " if a not in x:\n", " # If 'a' is not in 'x', add it to the list 'x'\n", " x.append(a)\n", "\n", " # Return the list 'x' containing unique elements\n", " return x\n", "\n", "# Print the result of calling the 'unique_list' function with a list containing duplicate elements\n", "print(unique_list([1, 2, 3, 3, 3, 3, 4, 5]))\n", "\n", "\n", "# Define a function named 'test_prime' that checks if a number 'n' is a prime number\n", "def test_prime(n):\n", " # Check if 'n' is equal to 1\n", " if (n == 1):\n", " # If 'n' is 1, return False (1 is not a prime number)\n", " return False\n", " # Check if 'n' is equal to 2\n", " elif (n == 2):\n", " # If 'n' is 2, return True (2 is a prime number)\n", " return True\n", " else:\n", " # Iterate through numbers from 2 to (n-1) using 'x' as the iterator\n", " for x in range(2, n):\n", " # Check if 'n' is divisible by 'x' without any remainder\n", " if (n % x == 0):\n", " # If 'n' is divisible by 'x', return False (not a prime number)\n", " return False\n", " # If 'n' is not divisible by any number from 2 to (n-1), return True (prime number)\n", " return True\n", "\n", "# Print the result of checking if 9 is a prime number by calling the 'test_prime' function\n", "print(test_prime(9))\n", "\n", "\n", "# Define a function named 'is_even_num' that takes a list 'l' as input and returns a list of even numbers\n", "def is_even_num(l):\n", " # Create an empty list 'enum' to store even numbers\n", " enum = []\n", "\n", " # Iterate through each number 'n' in the input list 'l'\n", " for n in l:\n", " # Check if the number 'n' is even (divisible by 2 without a remainder)\n", " if n % 2 == 0:\n", " # If 'n' is even, append it to the 'enum' list\n", " enum.append(n)\n", "\n", " # Return the list 'enum' containing even numbers\n", " return enum\n", "\n", "# Print the result of calling the 'is_even_num' function with a list of numbers\n", "print(is_even_num([1, 2, 3, 4, 5, 6, 7, 8, 9]))\n", "\n", "\n", "# Define a function named 'perfect_number' that checks if a number 'n' is a perfect number\n", "def perfect_number(n):\n", " # Initialize a variable 'sum' to store the sum of factors of 'n'\n", " sum = 0\n", "\n", " # Iterate through numbers from 1 to 'n-1' using 'x' as the iterator\n", " for x in range(1, n):\n", " # Check if 'x' is a factor of 'n' (divides 'n' without remainder)\n", " if n % x == 0:\n", " # If 'x' is a factor of 'n', add it to the 'sum'\n", " sum += x\n", "\n", " # Check if the 'sum' of factors is equal to the original number 'n'\n", " return sum == n\n", "\n", "# Print the result of checking if 6 is a perfect number by calling the 'perfect_number' function\n", "print(perfect_number(6))\n", "\n", "\n", "# Define a function named 'isPalindrome' that checks if a string is a palindrome\n", "def isPalindrome(string):\n", " # Initialize left and right pointers to check characters from the start and end of the string\n", " left_pos = 0\n", " right_pos = len(string) - 1\n", "\n", " # Loop until the pointers meet or cross each other\n", " while right_pos >= left_pos:\n", " # Check if the characters at the left and right positions are not equal\n", " if not string[left_pos] == string[right_pos]:\n", " # If characters don't match, return False (not a palindrome)\n", " return False\n", "\n", " # Move the left pointer to the right and the right pointer to the left to continue checking\n", " left_pos += 1\n", " right_pos -= 1\n", "\n", " # If the loop finishes without returning False, the string is a palindrome, so return True\n", " return True\n", "\n", "# Print the result of checking if the string 'aza' is a palindrome by calling the 'isPalindrome' function\n", "print(isPalindrome('aza'))\n", "\n", "\n" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "9jCIgiSgokk1", "outputId": "ac35a328-643d-4c98-d18e-37f32f3986df" }, "execution_count": 9, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Hello From My Function!\n", "Hello, John Doe, From My Function!, I wish you a great year!\n", "3\n", "More organized code is a benefit of functions!\n", "More readable code is a benefit of functions!\n", "Easier code reuse is a benefit of functions!\n", "Allowing programmers to share and connect code together is a benefit of functions!\n", "6\n", "20\n", "-336\n", "-336\n", "dcba4321\n", "Input a number to compute the factorial: 5\n", "120\n", "5 is in the range\n", "Original String: The quick Brown Fox\n", "No. of Upper case characters: 3\n", "No. of Lower case Characters: 13\n", "[1, 2, 3, 4, 5]\n", "False\n", "[2, 4, 6, 8]\n", "True\n", "True\n" ] } ] }, { "cell_type": "markdown", "source": [ "# **Functions in Python**\n", "You use functions in programming to bundle a set of instructions that you want to use repeatedly or that, because of their complexity, are better self-contained in a sub-program and called when needed. That means that a function is a piece of code written to carry out a specified task. To carry out that specific task, the function might or might not need multiple inputs. When the task is carried out, the function can or can not return one or more values.\n", "\n", "There are three types of functions in Python:\n", "\n", "Built-in functions, such as help() to ask for help, min() to get the minimum value, print() to print an object to the terminal,… You can find an overview with more of these functions here.\n", "\n", "User-Defined Functions (UDFs), which are functions that users create to help them out; And\n", "\n", "Anonymous functions, which are also called lambda functions because they are not declared with the standard def keyword.\n", "\n", "Functions vs. methods\n", "A method refers to a function which is part of a class. You access it with an instance or object of the class. A function doesn’t have this restriction: it just refers to a standalone function. This means that all methods are functions, but not all functions are methods.\n", "\n", "Consider this example, where you first define a function plus() and then a Summation class with a sum() method:" ], "metadata": { "id": "sU6_anMvokt0" } }, { "cell_type": "code", "source": [ "# Define a function named 'pascal_triangle' that generates Pascal's Triangle up to row 'n'\n", "def pascal_triangle(n):\n", " # Initialize the first row of Pascal's Triangle with value 1 as a starting point\n", " trow = [1]\n", "\n", " # Create a list 'y' filled with zeros to be used for calculations\n", " y = [0]\n", "\n", " # Iterate through a range starting from 0 up to the maximum of 'n' or 0 (taking the maximum to handle negative 'n')\n", " for x in range(max(n, 0)):\n", " # Print the current row of Pascal's Triangle\n", " print(trow)\n", "\n", " # Update the current row based on the previous row by calculating the next row using list comprehension\n", " # The formula for generating the next row in Pascal's Triangle is based on addition of consecutive elements\n", " trow = [l + r for l, r in zip(trow + y, y + trow)]\n", "\n", " # Return True if 'n' is greater than or equal to 1, else return False\n", " return n >= 1\n", "\n", "# Generate Pascal's Triangle up to row 6 by calling the 'pascal_triangle' function\n", "pascal_triangle(6)\n", "\n", "# Import the 'string' and 'sys' modules\n", "import string\n", "import sys\n", "\n", "# Define a function named 'ispangram' that checks if a string is a pangram\n", "def ispangram(str1, alphabet=string.ascii_lowercase):\n", " # Create a set 'alphaset' containing all lowercase letters from the provided alphabet\n", " alphaset = set(alphabet)\n", "\n", " # Convert the input string to lowercase and create a set from it\n", " str_set = set(str1.lower())\n", "\n", " # Check if the set of lowercase characters in the input string covers all characters in 'alphaset'\n", " return alphaset <= str_set\n", "\n", "# Print the result of checking if the string is a pangram by calling the 'ispangram' function\n", "print(ispangram('The quick brown fox jumps over the lazy dog'))\n", "\n", "# Take user input and split it into a list based on the hyphen (\"-\") separator, creating a list named 'items'\n", "items = [n for n in input().split('-')]\n", "\n", "# Sort the elements in the 'items' list in lexicographical order (alphabetical and numerical sorting)\n", "items.sort()\n", "\n", "# Join the sorted elements in the 'items' list using the hyphen (\"-\") separator and print the resulting string\n", "print('-'.join(items))\n", "\n", "\n", "# Define a function named 'printValues' that generates a list of squares of numbers from 1 to 20\n", "def printValues():\n", " # Create an empty list 'l'\n", " l = list()\n", "\n", " # Iterate through numbers from 1 to 20 (inclusive)\n", " for i in range(1, 21):\n", " # Calculate the square of 'i' and append it to the list 'l'\n", " l.append(i**2)\n", "\n", " # Print the list containing squares of numbers from 1 to 20\n", " print(l)\n", "\n", "# Call the 'printValues' function to generate and print the list of squares\n", "printValues()\n", "\n", "\n", "# Define a decorator 'make_bold' that adds bold HTML tags to the wrapped function's return value\n", "def make_bold(fn):\n", " def wrapped():\n", " return \"\" + fn() + \"\"\n", " return wrapped\n", "\n", "# Define a decorator 'make_italic' that adds italic HTML tags to the wrapped function's return value\n", "def make_italic(fn):\n", " def wrapped():\n", " return \"\" + fn() + \"\"\n", " return wrapped\n", "\n", "# Define a decorator 'make_underline' that adds underline HTML tags to the wrapped function's return value\n", "def make_underline(fn):\n", " def wrapped():\n", " return \"\" + fn() + \"\"\n", " return wrapped\n", "\n", "# Apply multiple decorators (@make_bold, @make_italic, @make_underline) to the 'hello' function\n", "@make_bold\n", "@make_italic\n", "@make_underline\n", "def hello():\n", " return \"hello world\"\n", "\n", "# Print the result of the decorated 'hello' function, which adds HTML tags for bold, italic, and underline\n", "\n", "print(hello()) ## returns \"hello world\"\n", "\n", "\n", "# Define a string variable 'mycode' containing a Python code as a string\n", "mycode = 'print(\"hello world\")'\n", "\n", "# Define a multi-line string variable 'code' containing Python code as a string\n", "code = \"\"\"\n", "def mutiply(x,y):\n", " return x*y\n", "\n", "print('Multiply of 2 and 3 is: ',mutiply(2,3))\n", "\"\"\"\n", "\n", "# Execute the Python code represented by the string stored in the variable 'mycode'\n", "exec(mycode)\n", "\n", "# Execute the Python code represented by the multi-line string stored in the variable 'code'\n", "exec(code)\n", "\n", "\n", "# Define a function named 'test' that takes a parameter 'a'\n", "def test(a):\n", " # Define a nested function 'add' that takes a parameter 'b'\n", " def add(b):\n", " # Declare 'a' from the outer scope as nonlocal to modify its value\n", " nonlocal a\n", "\n", " # Increment the value of 'a' by 1\n", " a += 1\n", "\n", " # Return the sum of 'a' (modified by the nonlocal statement) and 'b'\n", " return a + b\n", "\n", " # Return the inner function 'add' and its scope is retained due to closure\n", " return add\n", "\n", "# Call the 'test' function with an argument '4' and assign the returned function to 'func'\n", "func = test(4)\n", "\n", "# Call the function 'func' with argument '4' and print the result\n", "print(func(4))\n", "\n", "\n", "# Define a function named 'abc'\n", "def abc():\n", " # Define and assign values to local variables 'x', 'y', and 'str1' inside the function 'abc'\n", " x = 1\n", " y = 2\n", " str1 = \"w3resource\"\n", "\n", " # Print the string \"Python Exercises\"\n", " print(\"Python Exercises\")\n", "\n", "# Access the number of local variables in the function 'abc' using the __code__.co_nlocals attribute\n", "print(abc.__code__.co_nlocals)\n", "\n", " # Import specific functions 'sleep' from the 'time' module and the 'math' module\n", "from time import sleep\n", "import math\n", "\n", "# Define a function named 'delay' that delays the execution of a function by the given milliseconds\n", "def delay(fn, ms, *args):\n", " # Sleep for the specified number of milliseconds\n", " sleep(ms / 1000)\n", "\n", " # Call the provided function 'fn' with the given arguments '*args' and return the result\n", " return fn(*args)\n", "\n", "# Print a message indicating the operation that follows\n", "print(\"Square root after specific milliseconds:\")\n", "\n", "# Call the 'delay' function with a lambda function to calculate square roots after specific delays\n", "# Print the square root of 16 after a delay of 100 milliseconds\n", "print(delay(lambda x: math.sqrt(x), 100, 16))\n", "\n", "# Print the square root of 100 after a delay of 1000 milliseconds\n", "print(delay(lambda x: math.sqrt(x), 1000, 100))\n", "\n", "# Print the square root of 25100 after a delay of 2000 milliseconds\n", "print(delay(lambda x: math.sqrt(x), 2000, 25100))\n", "\n", "def least_difference(a, b, c):\n", " diff1 = abs(a - b)\n", " diff2 = abs(b - c)\n", " diff3 = abs(a - c)\n", " return min(diff1, diff2, diff3)\n", "\n", "print(\n", " least_difference(1, 10, 100),\n", " least_difference(1, 10, 10),\n", " least_difference(5, 6, 7), # Python allows trailing commas in argument lists. How nice is that?\n", ")\n", "\n", "def greet(who=\"Colin\"):\n", " print(\"Hello,\", who)\n", "\n", "greet()\n", "greet(who=\"Kaggle\")\n", "# (In this case, we don't need to specify the name of the argument, because it's unambiguous.)\n", "greet(\"world\")\n", "\n", "def mult_by_five(x):\n", " return 5 * x\n", "\n", "def call(fn, arg):\n", " \"\"\"Call fn on arg\"\"\"\n", " return fn(arg)\n", "\n", "def squared_call(fn, arg):\n", " \"\"\"Call fn on the result of calling fn on arg\"\"\"\n", " return fn(fn(arg))\n", "\n", "print(\n", " call(mult_by_five, 1),\n", " squared_call(mult_by_five, 1),\n", " sep='\\n', # '\\n' is the newline character - it starts a new line\n", ")\n", "\n" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "2tjB7QPjok1F", "outputId": "a729463f-8853-4649-c910-cc876980300b" }, "execution_count": 10, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "[1]\n", "[1, 1]\n", "[1, 2, 1]\n", "[1, 3, 3, 1]\n", "[1, 4, 6, 4, 1]\n", "[1, 5, 10, 10, 5, 1]\n", "True\n", "2\n", "2\n", "[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]\n", "hello world\n", "hello world\n", "Multiply of 2 and 3 is: 6\n", "9\n", "3\n", "Square root after specific milliseconds:\n", "4.0\n", "10.0\n", "158.42979517754858\n", "9 0 1\n", "Hello, Colin\n", "Hello, Kaggle\n", "Hello, world\n", "5\n", "25\n" ] } ] }, { "cell_type": "markdown", "source": [ "Function arguments in Python\n", "Earlier, you learned about the difference between parameters and arguments. In short, arguments are the things which are given to any function or method call, while the function or method code refers to the arguments by their parameter names. There are four types of arguments that Python UDFs can take:\n", "\n", "Default arguments\n", "Required arguments\n", "Keyword arguments\n", "Variable number of arguments\n", "Default Arguments\n", "Default arguments are those that take a default value if no argument value is passed during the function call. You can assign this default value by with the assignment operator =, just like in the following example:" ], "metadata": { "id": "oqfgODyWok9M" } } ] }