{"id":5167,"date":"2022-03-19T13:23:59","date_gmt":"2022-03-19T12:23:59","guid":{"rendered":"http:\/\/miro.borodziuk.eu\/?p=5167"},"modified":"2025-05-05T17:02:35","modified_gmt":"2025-05-05T15:02:35","slug":"functions","status":"publish","type":"post","link":"http:\/\/miro.borodziuk.eu\/index.php\/2022\/03\/19\/functions\/","title":{"rendered":"Functions"},"content":{"rendered":"<p>1. A function is a block of code that performs a specific task when the function is called (invoked). You can use functions to make your code reusable, better organized, and more readable. Functions can have parameters and return values.<\/p>\n<p><!--more--><\/p>\n<p>2. There are at least four basic types of functions in Python:<\/p>\n<ul>\n<li><strong>built-in functions<\/strong> which are an integral part of Python (such as the<code> print()<\/code> function). You can see a complete list of Python built-in functions at <em>https:\/\/docs.python.org\/3\/library\/functions.html<\/em>.<\/li>\n<li>the ones that come from <strong>pre-installed modules<\/strong>.<\/li>\n<li><strong>user-defined functions<\/strong> which are written by users for users &#8211; you can write your own functions and use them freely in your code,<\/li>\n<li>the <code>lambda<\/code> functions<\/li>\n<\/ul>\n<p>3. You can define your own function using the <code>def<\/code> keyword and the following syntax:<\/p>\n<pre class=\"lang:default decode:true\">def your_function(optional parameters):\r\n   # the body of the function<\/pre>\n<p>You can define a function which doesn&#8217;t take any arguments, e.g.:<\/p>\n<pre class=\"lang:default decode:true\">def message(): # defining a function\r\n   print(\"Hello\") # body of the function\r\n\r\nmessage() # calling the function<\/pre>\n<p>You can define a function which takes arguments, too, just like the one-parameter function below:<\/p>\n<pre class=\"lang:default decode:true\">def hello(name): # defining a function\r\n   print(\"Hello,\", name) # body of the function\r\n\r\nname = input(\"Enter your name: \")\r\n\r\nhello(name) # calling the function\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p>4. You can pass information to functions by using parameters. Your functions can have as many parameters as you need.<\/p>\n<p>An example of a one-parameter function:<\/p>\n<pre class=\"lang:default decode:true\">def hi(name):\r\n   print(\"Hi,\", name)\r\n\r\nhi(\"Greg\")<\/pre>\n<p>An example of a two-parameter function:<\/p>\n<pre class=\"lang:default decode:true\">def hi_all(name_1, name_2):\r\n   print(\"Hi,\", name_2)\r\n   print(\"Hi,\", name_1)\r\n\r\nhi_all(\"Sebastian\", \"Konrad\")<\/pre>\n<p>An example of a three-parameter function:<\/p>\n<pre class=\"lang:default decode:true\">def address(street, city, postal_code):\r\n   print(\"Your address is:\", street, \"St.,\", city, postal_code)\r\n\r\ns = input(\"Street: \")\r\np_c = input(\"Postal Code: \")\r\nc = input(\"City: \")\r\n\r\naddress(s, c, p_c)<\/pre>\n<p>5. You can pass arguments to a function using the following techniques:<\/p>\n<ul>\n<li>positional argument passing in which the order of arguments passed matters (Ex. 1),<\/li>\n<li>keyword (named) argument passing in which the order of arguments passed doesn&#8217;t matter (Ex. 2),<\/li>\n<li>a mix of positional and keyword argument passing (Ex. 3).<\/li>\n<\/ul>\n<pre class=\"lang:default decode:true\">Ex. 1\r\ndef subtra(a, b):\r\nprint(a - b)\r\n\r\nsubtra(5, 2) # outputs: 3\r\nsubtra(2, 5) # outputs: -3\r\n\r\nEx. 2\r\ndef subtra(a, b):\r\nprint(a - b)\r\n\r\nsubtra(a=5, b=2) # outputs: 3\r\nsubtra(b=2, a=5) # outputs: 3\r\n\r\nEx. 3\r\ndef subtra(a, b):\r\nprint(a - b)\r\n\r\nsubtra(5, b=2) # outputs: 3\r\nsubtra(5, 2) # outputs: 3<\/pre>\n<p>It&#8217;s important to remember that you have to put <strong>positional arguments before keyword arguments<\/strong>. Positional arguments mustn&#8217;t follow keyword arguments. That&#8217;s why if you try to run the following snippet:<\/p>\n<pre class=\"lang:default decode:true\">def subtra(a, b):\r\nprint(a - b)\r\n\r\nsubtra(5, b=2) # outputs: 3\r\nsubtra(a=5, 2) # Syntax Error<\/pre>\n<p>Python will not let you do it by signalling a SyntaxError.<\/p>\n<p>6. You can use the keyword argument passing technique to pre-define a value for a given argument:<\/p>\n<pre class=\"lang:default decode:true \">def name(first_name, last_name=\"Smith\"):\r\nprint(first_name, last_name)\r\n\r\nname(\"Andy\") # outputs: Andy Smith\r\nname(\"Betty\", \"Johnson\") # outputs: Betty Johnson (the keyword argument replaced by \"Johnson\")<\/pre>\n<p>&nbsp;<\/p>\n<p>7. You can use the <code>return<\/code> keyword to tell a function to return some value. The return statement exits the function, e.g.:<\/p>\n<pre class=\"lang:default decode:true \">def multiply(a, b):\r\n   return a * b\r\nprint(multiply(3, 4)) # outputs: 12\r\n\r\ndef multiply(a, b):\r\n   return\r\nprint(multiply(3, 4)) # outputs: None<\/pre>\n<p>&nbsp;<\/p>\n<p>8. The result of a function can be easily assigned to a variable, e.g.:<\/p>\n<pre class=\"lang:default decode:true\">def wishes():\r\n   return \"Happy Birthday!\"\r\n\r\nw = wishes()\r\n\r\nprint(w) # outputs: Happy Birthday!<\/pre>\n<p>&nbsp;<\/p>\n<p>Look at the difference in output in the following two examples:<\/p>\n<pre class=\"lang:default decode:true\"># Example 1\r\ndef wishes():\r\n   print(\"My Wishes\")\r\n   return \"Happy Birthday\"\r\n\r\nwishes() # outputs: My Wishes\r\n\r\n# Example 2\r\ndef wishes():\r\n   print(\"My Wishes\")\r\n   return \"Happy Birthday\"\r\n\r\nprint(wishes())\r\n\r\n# outputs: My Wishes\r\n#          Happy Birthday<\/pre>\n<p>&nbsp;<\/p>\n<p>9. You can use a list as a function&#8217;s argument, e.g.:<\/p>\n<pre class=\"lang:default decode:true\">def hi_everybody(my_list):\r\n   for name in my_list:\r\n      print(\"Hi,\", name)\r\n\r\nhi_everybody([\"Adam\", \"John\", \"Lucy\"])<\/pre>\n<p>&nbsp;<\/p>\n<p>10. A list can be a function result, too, e.g.:<\/p>\n<pre class=\"lang:default decode:true\">def create_list(n):\r\n   my_list = []\r\n   for i in range(n):\r\n      my_list.append(i)\r\n   return my_list\r\n\r\nprint(create_list(5))<\/pre>\n<p>&nbsp;<\/p>\n<p>11. You can use the <code>return<\/code> keyword to tell a function to return some value. The <code>return<\/code> statement exits the function, e.g.:<code class=\"codep syntax-color copy\"><\/code><\/p>\n<div class=\"ace-tm\">\n<div class=\"ace_static_highlight\">\n<pre class=\"lang:default decode:true\">def multiply(a, b):\r\n  return a * b\r\n\r\nprint(multiply(3, 4)) # outputs: 12\r\n\r\ndef multiply(a, b):\r\n  return\r\n\r\nprint(multiply(3, 4)) # outputs: None<\/pre>\n<p>&nbsp;<\/p>\n<p>12. The result of a function can be easily assigned to a variable, e.g.:<\/p>\n<\/div>\n<\/div>\n<pre class=\"lang:default decode:true\">def wishes(): \r\n  return \"Happy Birthday!\" \r\n\r\nw = wishes() \r\nprint(w) # outputs: Happy Birthday!<\/pre>\n<p>Look at the difference in output in the following two examples:<code class=\"codep syntax-color copy\"><\/code><\/p>\n<div class=\"ace-tm\">\n<div class=\"ace_static_highlight\">\n<pre class=\"lang:default decode:true\"># Example 1\r\ndef wishes():\r\n  print(\"My Wishes\")\r\n  return \"Happy Birthday\"\r\n\r\nwishes() # outputs: My Wishes\r\n\r\n# Example 2\r\ndef wishes():\r\n  print(\"My Wishes\")\r\n  return \"Happy Birthday\"\r\n\r\nprint(wishes())\r\n\r\n# outputs: My Wishes\r\n# Happy Birthday<\/pre>\n<p>&nbsp;<\/p>\n<p>13. You can use a list as a function&#8217;s argument, e.g.:<\/p>\n<\/div>\n<\/div>\n<div class=\"ace-tm\">\n<div class=\"ace_static_highlight\">\n<pre class=\"lang:default decode:true\">def hi_everybody(my_list):\r\n  for name in my_list:\r\n    print(\"Hi,\", name)\r\n\r\nhi_everybody([\"Adam\", \"John\", \"Lucy\"])<\/pre>\n<p>&nbsp;<\/p>\n<p>14. A list can be a function result, too, e.g.:<\/p>\n<\/div>\n<\/div>\n<div class=\"ace-tm\">\n<div class=\"ace_static_highlight\">\n<pre class=\"lang:default decode:true\">def create_list(n):\r\n  my_list = []\r\n  for i in range(n):\r\n    my_list.append(i)\r\n  return my_list\r\n\r\nprint(create_list(5))<\/pre>\n<\/div>\n<\/div>\n<p>&nbsp;<\/p>\n<p>15. A variable that exists outside a function has a scope inside the function body (Example 1) unless the function defines a variable of the same name (Example 2, and Example 3), e.g.:<\/p>\n<p>Example 1:<\/p>\n<pre class=\"lang:default decode:true\">var = 2 \r\ndef mult_by_var(x): \r\n  return x * var \r\n\r\nprint(mult_by_var(7)) # outputs: 14<\/pre>\n<p>Example 2:<\/p>\n<pre class=\"lang:default decode:true\">def mult(x): \r\n  var = 5 \r\n  return x * var \r\n\r\nprint(mult(7)) # outputs: 35<\/pre>\n<p>&nbsp;<\/p>\n<p>Example 3:<\/p>\n<pre class=\"lang:default decode:true\">def mult(x): \r\n  var = 7 \r\n  return x * var\r\n\r\nvar = 3 \r\nprint(mult(7)) # outputs: 49<\/pre>\n<p>&nbsp;<\/p>\n<p>16. A variable that exists inside a function has a scope inside the function body (Example 4), e.g.:<\/p>\n<p>Example 4:<\/p>\n<pre class=\"lang:default decode:true\">def adding(x): \r\n  var = 7 \r\n  return x + var \r\n\r\nprint(adding(4)) # outputs: 11 \r\nprint(var) # NameError<\/pre>\n<p>&nbsp;<\/p>\n<p>17. You can use the <code>global<\/code> keyword followed by a variable name to make the variable&#8217;s scope global, e.g.:<\/p>\n<div class=\"ace-tm\">\n<div class=\"ace_static_highlight\">\n<pre class=\"lang:default decode:true \">var = 2\r\nprint(var) # outputs: 2\r\n\r\ndef return_var():\r\n  global var\r\n  var = 5\r\n  return var\r\n\r\nprint(return_var()) # outputs: 5\r\nprint(var) # outputs: 5<\/pre>\n<p>&nbsp;<\/p>\n<div class=\"ace_line\">18. Is it worth checking how it works with lists (do you recall the peculiarities of assigning list slices versus assigning lists as a whole?).<\/div>\n<\/div>\n<\/div>\n<p>The following example will shed some light on the issue:<\/p>\n<p><code class=\"codep syntax-color copy\"><\/code><\/p>\n<div class=\"ace-tm\">\n<div class=\"ace_static_highlight\">\n<pre class=\"lang:default decode:true\">def my_function(my_list_1):\r\n  print(\"Print #1:\", my_list_1)\r\n  print(\"Print #2:\", my_list_2)\r\n  my_list_1 = [0, 1]\r\n  print(\"Print #3:\", my_list_1)\r\n  print(\"Print #4:\", my_list_2)\r\n\r\nmy_list_2 = [2, 3]\r\nmy_function(my_list_2)\r\nprint(\"Print #5:\", my_list_2)<\/pre>\n<p>The code&#8217;s output is:<\/p>\n<\/div>\n<\/div>\n<pre class=\"lang:default decode:true\">Print #1: [2, 3]\r\nPrint #2: [2, 3]\r\nPrint #3: [0, 1]\r\nPrint #4: [2, 3]\r\nPrint #5: [2, 3]<\/pre>\n<p>It seems that the former rule still works.<\/p>\n<p>Finally, can you see the difference in the example below:<code class=\"codep copy syntax-color\"><\/code><\/p>\n<div class=\"ace-tm\">\n<div class=\"ace_static_highlight\">\n<pre class=\"lang:default decode:true\">def my_function(my_list_1):\r\n  print(\"Print #1:\", my_list_1)\r\n  print(\"Print #2:\", my_list_2)\r\n  del my_list_1[0] # Pay attention to this line.\r\n  print(\"Print #3:\", my_list_1)\r\n  print(\"Print #4:\", my_list_2)\r\n\r\nmy_list_2 = [2, 3]\r\nmy_function(my_list_2)\r\nprint(\"Print #5:\", my_list_2)<\/pre>\n<p>We don&#8217;t change the value of the parameter <code>my_list_1<\/code> (we already know it will not affect the argument), but instead modify the list identified by it.<\/p>\n<\/div>\n<\/div>\n<p>The output may be surprising. Run the code and check:<\/p>\n<pre class=\"lang:default decode:true\">Print #1: [2, 3] \r\nPrint #2: [2, 3] \r\nPrint #3: [3] \r\nPrint #4: [3] \r\nPrint #5: [3]<\/pre>\n<p>Let&#8217;s explain it :<\/p>\n<ul>\n<li>if the argument is a list, then changing the value of the corresponding parameter doesn&#8217;t affect the list (remember: variables containing lists are stored in a different way than scalars),<\/li>\n<li>but if you change a list identified by the parameter (note: the list, not the parameter!), the list will reflect the change.<\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<p>19. A function can call other functions or even itself. When a function calls itself, this situation is known as <strong>recursion<\/strong>, and the function which calls itself and contains a specified termination condition (i.e., the base case &#8211; a condition which doesn&#8217;t tell the function to make any further calls to that function) is called a <strong>recursive<\/strong> function.<\/p>\n<p>20. You can use recursive functions in Python to write <strong>clean, elegant code, and divide it into smaller, organized chunks<\/strong>. On the other hand, you need to be very careful as it might be <strong>easy to make a mistake and create a function which never terminates<\/strong>. You also need to remember that <strong>recursive calls consume a lot of memory<\/strong>, and therefore may sometimes be inefficient.<\/p>\n<p>When using recursion, you need to take all its advantages and disadvantages into consideration.<\/p>\n<p>The factorial function is a classic example of how the concept of recursion can be put in practice:<\/p>\n<pre class=\"lang:default decode:true\">def factorial_function(n):\r\n    if n &lt; 0:\r\n        return None\r\n    if n &lt; 2:\r\n        return 1\r\n    return n * factorial_function(n - 1)\r\n\r\nprint(factorial(4)) # 4 * 3 * 2 * 1 = 2<\/pre>\n<p>Factorial without recursion:<\/p>\n<pre class=\"lang:default decode:true \">def factorial_function(n):\r\n    if n &lt; 0:\r\n        return None\r\n    if n &lt; 2:\r\n        return 1\r\n    \r\n    product = 1\r\n    for i in range(2, n + 1):\r\n        product *= i\r\n    return product\r\n\r\n\r\nfor n in range(1, 6):  # testing\r\n    print(n, factorial_function(n))\r\n\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p><code class=\"codep copy\"><\/code><\/p>\n<div class=\"ace-tm\">\n<div class=\"ace_static_highlight\">\n<p><em>Exercise 1<\/em><\/p>\n<\/div>\n<\/div>\n<p>What is the output of the following snippet?<\/p>\n<pre class=\"lang:default decode:true\">def intro(a=\"James Bond\", b=\"Bond\"):\r\n   print(\"My name is\", b + \".\", a + \".\")\r\n\r\nintro()<\/pre>\n<p># My name is Bond. James Bond.<\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 2<\/em><\/p>\n<p>What is the output of the following snippet?<\/p>\n<pre class=\"lang:default decode:true\">def intro(a=\"James Bond\", b=\"Bond\"):\r\n   print(\"My name is\", b + \".\", a + \".\")\r\n\r\nintro(b=\"Sean Connery\")<\/pre>\n<p># My name is Sean Connery. James Bond.<\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 3<\/em><\/p>\n<p>What is the output of the following snippet?<\/p>\n<pre class=\"lang:default decode:true\">def intro(a, b=\"Bond\"):\r\n   print(\"My name is\", b + \".\", a + \".\")\r\n\r\nintro(\"Susan\")<\/pre>\n<p># My name is Bond. Susan.<\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 4<\/em><\/p>\n<p>What is the output of the following snippet?<\/p>\n<pre class=\"lang:default decode:true\">def add_numbers(a, b=2, c):\r\n   print(a + b + c)\r\n\r\nadd_numbers(a=1, c=3)\r\n\r\n<\/pre>\n<p># SyntaxError &#8211; a non-default argument (c) follows a default argument (b=2)<\/p>\n<p><strong>A non-default arguments must be before a default arguments.<\/strong><\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 5<\/em><\/p>\n<p>What is the output of the following snippet?<\/p>\n<pre class=\"lang:default decode:true\">def hi():\r\n   return\r\n   print(\"Hi!\")\r\n\r\nhi()<\/pre>\n<p># the function will return an implicit None value<\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 6<\/em><\/p>\n<p>What is the output of the following snippet?<\/p>\n<pre class=\"lang:default decode:true\">def is_int(data):\r\nif type(data) == int:\r\n   return True\r\nelif type(data) == float:\r\n   return False\r\n\r\nprint(is_int(5))\r\nprint(is_int(5.0))\r\nprint(is_int(\"5\"))\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p>True<\/p>\n<p>False<\/p>\n<p>None<\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 7<\/em><\/p>\n<p>What is the output of the following snippet?<\/p>\n<pre class=\"lang:default decode:true\">def even_num_lst(ran):\r\n   lst = []\r\n   for num in range(ran):\r\n      if num % 2 == 0:\r\n         lst.append(num)\r\n   return lst\r\n\r\nprint(even_num_lst(11))\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p>[0, 2, 4, 6, 8, 10]<\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 8<\/em><\/p>\n<p>What is the output of the following snippet?<\/p>\n<pre class=\"lang:default decode:true\">def list_updater(lst):\r\n   upd_list = []\r\n   for elem in lst:\r\n      elem **= 2\r\n      upd_list.append(elem)\r\n   return upd_list\r\n\r\nfoo = [1, 2, 3, 4, 5]\r\nprint(list_updater(foo))\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p>[1, 4, 9, 16, 25]<\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 9<\/em><strong><br \/>\n<\/strong><\/p>\n<p>What is the output of the following snippet?<code class=\"codep \"><\/code><\/p>\n<pre class=\"lang:default decode:true\">def hi(): \r\n  return print(\"Hi!\") \r\n\r\nhi()<\/pre>\n<p id=\"sol\">the function will return an implicit <code>None<\/code> value<\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 10<\/em><strong><br \/>\n<\/strong><\/p>\n<p>What is the output of the following snippet?<code class=\"codep \"><\/code><\/p>\n<pre class=\"lang:default decode:true\">def is_int(data): \r\n  if type(data) == int: \r\n    return True \r\n  elif type(data) == float: \r\n    return False \r\n\r\nprint(is_int(5)) \r\nprint(is_int(5.0)) \r\nprint(is_int(\"5\"))<code class=\"codep \"><\/code><\/pre>\n<p id=\"sol2\"><code class=\"codep \"><\/code><\/p>\n<p><code class=\"codep \">True<br \/>\nFalse<\/code><code class=\"codep \"><br \/>\nNone<\/code><\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 11<\/em><strong><br \/>\n<\/strong><\/p>\n<p>What is the output of the following snippet?<\/p>\n<pre class=\"lang:default decode:true\">def even_num_lst(ran): \r\n  lst = [] \r\n  for num in range(ran): \r\n    if num % 2 == 0: \r\n      lst.append(num) \r\n  return lst \r\n\r\nprint(even_num_lst(11))<\/pre>\n<div align=\"right\"><\/div>\n<p id=\"sol3\"><code class=\"codep \">[0, 2, 4, 6, 8, 10]<\/code><\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 12<\/em><strong><br \/>\n<\/strong><\/p>\n<p>What is the output of the following snippet?<\/p>\n<pre class=\"lang:default decode:true\">def list_updater(lst): \r\n  upd_list = [] \r\n  for elem in lst: \r\n    elem **= 2 upd_list.append(elem) \r\n  return upd_list foo = [1, 2, 3, 4, 5] \r\n\r\nprint(list_updater(foo))<\/pre>\n<div align=\"right\"><\/div>\n<p id=\"sol4\"><code class=\"codep \">[1, 4, 9, 16, 25]<\/code><\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 13<\/em><\/p>\n<p>What will happen when you try to run the following code?<\/p>\n<pre class=\"lang:default decode:true\">def message(): \r\n  alt = 1 \r\n  print(\"Hello, World!\") \r\n\r\nprint(alt)<\/pre>\n<p>&nbsp;<\/p>\n<p id=\"sol\">The <code>NameError<\/code> exception will be thrown (<code>NameError: name 'alt' is not defined<\/code>)<\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 14<br \/>\n<\/em><\/p>\n<p>What is the output of the following snippet?<\/p>\n<pre class=\"lang:default decode:true \">a = 1 \r\ndef fun(): \r\n  a = 2 \r\n  print(a) \r\n\r\nfun() \r\nprint(a)<\/pre>\n<p>2<\/p>\n<p>1<\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 15<\/em><strong><br \/>\n<\/strong><\/p>\n<p>What is the output of the following snippet?<\/p>\n<pre class=\"lang:default decode:true\">a = 1 \r\ndef fun(): \r\n  global a \r\n  a = 2 \r\n  print(a) \r\n\r\nfun() \r\na = 3 \r\nprint(a)<\/pre>\n<p>2<\/p>\n<p>3<\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 16<\/em><strong><br \/>\n<\/strong><\/p>\n<p>What is the output of the following snippet?<\/p>\n<pre class=\"lang:default decode:true \">a = 1 \r\ndef fun(): \r\n  global a \r\n  a = 2 \r\n  print(a) \r\n\r\na = 3 \r\nfun() \r\nprint(a)<\/pre>\n<p>2<\/p>\n<p>2<\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 17<\/em><\/p>\n<p>What will happen when you attempt to run the following snippet and why?<\/p>\n<pre class=\"lang:default decode:true \">def factorial(n): \r\n  return n * factorial(n - 1) \r\n\r\nprint(factorial(4))<\/pre>\n<p>&nbsp;<\/p>\n<p id=\"sol\">The factorial function has no termination condition (no base case) so Python will raise an exception (<code>RecursionError: maximum recursion depth exceeded<\/code>)<\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 18<\/em><strong><br \/>\n<\/strong><\/p>\n<p>What is the output of the following snippet?<\/p>\n<pre class=\"lang:default decode:true\">def fun(a): \r\nif a &gt; 30: \r\n  return 3 \r\nelse: \r\n  return a + fun(a + 3) \r\n\r\nprint(fun(25))<\/pre>\n<div align=\"right\"><\/div>\n<p id=\"sol2\"><code class=\"codep \">56<\/code><\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 19<\/em><strong><br \/>\n<\/strong><\/p>\n<p>What is the output of the following snippet?<\/p>\n<pre class=\"lang:default decode:true \">def fun(in=2, out=3):\r\n  return in*out\r\n\r\nprint (fun(3))<\/pre>\n<p>&nbsp;<\/p>\n<p><code>invalid syntax<\/code><\/p>\n<p><code>in<\/code> is a keyword, you can not use <code>in<\/code> as a name of parametr<\/p>\n<p>&nbsp;<\/p>\n<p>Ex. 20<\/p>\n<p>What is the output of the following code snippet?<\/p>\n<pre class=\"lang:default decode:true\">x = 10\r\n\r\ndef fun():\r\n  global x\r\n  if x &gt;= 10:\r\n    x += 100\r\n\r\nprint(x)<\/pre>\n<p>&nbsp;<\/p>\n<p><code>10<\/code><\/p>\n<p>The code does not call the fun() function. As a result, the program does not execute the body of the function and the content of the variable x does not change. Therefore, the print statement returns 10 on the screen.<\/p>\n<p>&nbsp;<\/p>\n<p>Ex. 21<\/p>\n<div class=\"result-pane--question-header-wrapper--3DCpC\">\n<div class=\"result-pane--question-header--pTUOx\">\n<div id=\"question-prompt\" class=\"result-pane--question-format--PBvdY ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>What is the output of the following code snippet?<\/p>\n<div class=\"ud-component--base-components--code-block\">\n<div>\n<pre class=\"lang:default decode:true\">def fun(x, y = 1):\r\n  return x * y\r\n\r\nprint(fun('3', 2))<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--question-result-pane-expanded-content--Og5Vc\">\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-correct--PLOEU\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>&nbsp;<\/p>\n<p><code><strong>33<\/strong><\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-skipped--1NDPn\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\"><\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--question-related-fields--c3m--\">\n<div class=\"overall-explanation-pane--overall-explanation--G-hLQ ud-form-group\">\n<div id=\"overall-explanation\" class=\"ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<ul>\n<li>The argument <code><strong>'3'<\/strong><\/code> is a string, and argument <code><strong>2<\/strong><\/code>, which is an integer, overrides the\u00a0 default value of the <code><strong>y<\/strong><\/code> parameter of <code><strong>fun()<\/strong><\/code>. So the function will return the string <code><strong>'33'<\/strong><\/code> to the <code><strong>print<\/strong><\/code> statement:<code><strong>x * y<\/strong><\/code> <strong>-&gt;<\/strong> <code><strong>'3' * 2<\/strong><\/code><strong>-&gt;<\/strong> <code><strong>'33'<\/strong><\/code>.<\/li>\n<\/ul>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Ex. 22<\/p>\n<div class=\"result-pane--question-header-wrapper--3DCpC\">\n<div class=\"result-pane--question-header--pTUOx\">\n<div id=\"question-prompt\" class=\"result-pane--question-format--PBvdY ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>What is the output of the following code snippet?<\/p>\n<div class=\"ud-component--base-components--code-block\">\n<div>\n<pre class=\"lang:default decode:true\">def rectangle(b, h):\r\n  perimeter = (b + h) * 2\r\n  area = b * h\r\n  return b, h, area, perimeter\r\n\r\nprint(rectangle(10, 3)[2])<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--question-result-pane-expanded-content--Og5Vc\">\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-skipped--1NDPn\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\"><\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-correct--PLOEU\" data-purpose=\"answer\">\n<div><\/div>\n<div><span class=\"result-pane--answer-by-user-label--PSH86 ud-heading-xs\" data-purpose=\"answer-result-header-user-label\">Correct answer<\/span><\/div>\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p><code><strong>30<\/strong><\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--question-related-fields--c3m--\">\n<div class=\"overall-explanation-pane--overall-explanation--G-hLQ ud-form-group\">\n<p><label class=\"ud-heading-md ud-form-label ud-heading-sm\" for=\"form-group--479\"><\/label>The <code><strong>return<\/strong><\/code> statement returns only <strong>one<\/strong> value, but, in our case, the code does not raise any exceptions because the function returns a <strong>single tuple<\/strong> of four elements.\u00a0 Then, the <code><strong>print<\/strong><\/code> statement sends to the screen the element with index <code><strong>2<\/strong><\/code> of the returned tuple:<\/p>\n<div id=\"overall-explanation\" class=\"ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p><strong>step by step<\/strong><\/p>\n<p>Step 1 &#8211; <code><strong>print(rectangle(10, 3)[2])<\/strong><\/code><\/p>\n<p>Step 2 &#8211; <code><strong>print((10, 3, 30, 26)[2])<\/strong><\/code><\/p>\n<p>Step 3 &#8211; <code><strong>print(30)<\/strong><\/code><\/p>\n<p>Output &#8211; <code><strong>30<\/strong><\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<h2>Scenario<\/h2>\n<p>Your task is to write and test a function which takes one argument (a year) and returns <code>True<\/code> if the year is a <i>leap year<\/i>, or <code>False<\/code> otherwise.<\/p>\n<p><span class=\"ILfuVd\" lang=\"en\"><span class=\"hgKElc\">To determine if a year is a leap year, we apply a simple rule: <b>if the year is divisible by 4, it&#8217;s a leap year, except for end-of-century years, which must also be divisible by 400<\/b>. For instance, the year 2000 was a leap year, while 1900 was not.<\/span><\/span><\/p>\n<pre class=\"lang:default decode:true\">def is_year_leap(year):\r\n    x = year % 4\r\n    y = year % 100\r\n    z = year % 400\r\n    \r\n    if (x == 0 and y != 0) or (y == 0 and z == 0):\r\n        print (\" x=\",x, \" y=\", y, \" z=\", z, sep=\"\")\r\n        return True\r\n    else:\r\n        print (\" x=\",x, \" y=\", y, \" z=\", z, sep=\"\")\r\n        return False\r\n\r\n\r\ntest_data = [1900, 2000, 2016, 1987]\r\ntest_results = [False, True, True, False]\r\nfor i in range(len(test_data)):\r\n\tyr = test_data[i]\r\n\tprint(yr,\"-&gt;\",end=\"\")\r\n\tresult = is_year_leap(yr)\r\n\tif result == test_results[i]:\r\n\t\tprint(\"OK\")\r\n\telse:\r\n\t\tprint(\"Failed\")<\/pre>\n<h2>Scenario<\/h2>\n<p>Your task is to write and test a function which takes two arguments (a year and a month) and returns the number of days for the given month\/year pair (while only February is sensitive to the <code>year<\/code> value, your function should be universal).<\/p>\n<p>The initial part of the function is ready. Now, convince the function to return <code>None<\/code> if its arguments don&#8217;t make sense.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-5788 size-full\" src=\"http:\/\/miro.borodziuk.eu\/wp-content\/uploads\/1000_F_632556522_ni86RteSYngMwg9GI6CTmh0ralWBSSSC.jpg\" alt=\"\" width=\"1000\" height=\"700\" srcset=\"http:\/\/miro.borodziuk.eu\/wp-content\/uploads\/1000_F_632556522_ni86RteSYngMwg9GI6CTmh0ralWBSSSC.jpg 1000w, http:\/\/miro.borodziuk.eu\/wp-content\/uploads\/1000_F_632556522_ni86RteSYngMwg9GI6CTmh0ralWBSSSC-300x210.jpg 300w, http:\/\/miro.borodziuk.eu\/wp-content\/uploads\/1000_F_632556522_ni86RteSYngMwg9GI6CTmh0ralWBSSSC-768x538.jpg 768w\" sizes=\"(max-width: 767px) 89vw, (max-width: 1000px) 54vw, (max-width: 1071px) 543px, 580px\" \/><\/p>\n<pre class=\"lang:default decode:true \">def is_year_leap(year):\r\n    x = year % 4 \r\n    y = year % 100 \r\n    z = year % 400 \r\n    if (x == 0 and y != 0) or (y == 0 and z == 0): \r\n        return True \r\n    else: \r\n        return False\r\n\r\ndef days_in_month(year, month):\r\n    even = month % 2 == 0\r\n    if month == 2:\r\n        if is_year_leap(year):\r\n            return 29\r\n        else:\r\n            return 28\r\n    elif month &lt;= 7:\r\n        if even:\r\n            return 30\r\n        else:\r\n            return 31\r\n    elif month &gt; 7:\r\n        if even:\r\n            return 31\r\n        else:\r\n            return 30\r\n    \r\ntest_years = [1900, 2000, 2016, 1987]\r\ntest_months = [2, 2, 1, 11]\r\ntest_results = [28, 29, 31, 30]\r\nfor i in range(len(test_years)):\r\n\tyr = test_years[i]\r\n\tmo = test_months[i]\r\n\tprint(yr, mo, \"-&gt;\", end=\"\")\r\n\tresult = days_in_month(yr, mo)\r\n\tif result == test_results[i]:\r\n\t\tprint(\"OK\")\r\n\telse:\r\n\t\tprint(\"Failed\")\r\n<\/pre>\n<p>&nbsp;<\/p>\n<h2>Scenario<\/h2>\n<p>Your task is to write and test a function which takes three arguments (a year, a month, and a day of the month) and returns the corresponding day of the year, or returns <code>None<\/code> if any of the arguments is invalid.<\/p>\n<pre class=\"lang:default decode:true \">def is_year_leap(year):\r\n    x = year % 4 \r\n    y = year % 100 \r\n    z = year % 400 \r\n    if (x == 0 and y != 0) or (y == 0 and z == 0): \r\n        return True \r\n    else: \r\n        return False\r\n\r\ndef days_in_month(year, month):\r\n    even = month % 2 == 0\r\n    if month == 2:\r\n        if is_year_leap(year):\r\n            return 29\r\n        else:\r\n            return 28\r\n    elif month &lt;= 7:\r\n        if even:\r\n            return 30\r\n        else:\r\n            return 31\r\n    elif month &gt; 7:\r\n        if even:\r\n            return 31\r\n        else:\r\n            return 30\r\n\r\ndef day_of_year(year, month, day):\r\n    count=0\r\n    for month in range (1,month):\r\n        count+=days_in_month(year, month)\r\n        #print(month, count)\r\n    count+=day\r\n    return count\r\n\r\nprint(day_of_year(2001, 12, 31))<\/pre>\n<p>&nbsp;<\/p>\n<h2>Scenario<\/h2>\n<p><i>A natural number is <b>prime<\/b> if it is greater than 1 and has no divisors other than 1 and itself.<\/i><\/p>\n<p>Complicated? Not at all. For example, 8 isn&#8217;t a prime number, as you can divide it by 2 and 4 (we can&#8217;t use divisors equal to 1 and 8, as the definition prohibits this).<\/p>\n<p>On the other hand, 7 is a prime number, as we can&#8217;t find any legal divisors for it.<\/p>\n<p>Your task is to write a function checking whether a number is prime or not.<\/p>\n<p>The function:<\/p>\n<ul>\n<li>is called <code>is_prime<\/code>;<\/li>\n<li>takes one argument (the value to check)<\/li>\n<li>returns <code>True<\/code> if the argument is a prime number, and <code>False<\/code> otherwise.<\/li>\n<\/ul>\n<p>Hint: try to divide the argument by all subsequent values (starting from 2) and check the remainder &#8211; if it&#8217;s zero, your number cannot be a prime; think carefully about when you should stop the process.<\/p>\n<pre class=\"lang:default decode:true \">def is_prime(num):\r\n    if num &gt; 1:\r\n        flag = 1\r\n        for divider in range (2,10):\r\n            if num % divider == 0 and num != divider and num&gt;divider:\r\n               # print(num, divider, sep=\" -&gt; \")\r\n                flag=0\r\n    return flag\r\n\r\nfor i in range(1, 100):\r\n\tif is_prime(i + 1):\r\n\t\t\tprint(i + 1, end=\" \")\r\nprint()<\/pre>\n<p>2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97<\/p>\n<h1>Fibonacci numbers<\/h1>\n<p>Are you familiar with <strong>Fibonacci<\/strong> numbers?<\/p>\n<p>They are a <strong>sequence of integer numbers<\/strong> built using a very simple rule:<\/p>\n<ul>\n<li>the first element of the sequence is equal to one (<strong>Fib<sub>1<\/sub> = 1<\/strong>)<\/li>\n<li>the second is also equal to one (<strong>Fib<sub>2<\/sub> = 1<\/strong>)<\/li>\n<li>every subsequent number is the the_sum of the two preceding numbers:<br \/>\n(<strong>Fib<sub>i<\/sub> = Fib<sub>i-1<\/sub> + Fib<sub>i-2<\/sub><\/strong>)<\/li>\n<\/ul>\n<p>Here are some of the first Fibonacci numbers:<\/p>\n<p>fib_1 = 1<br \/>\nfib_2 = 1<br \/>\nfib_3 = 1 + 1 = 2<br \/>\nfib_4 = 1 + 2 = 3<br \/>\nfib_5 = 2 + 3 = 5<br \/>\nfib_6 = 3 + 5 = 8<br \/>\nfib_7 = 5 + 8 = 13<\/p>\n<p>What do you think about <strong>implementing this as a function<\/strong>?<\/p>\n<p>Let&#8217;s create our <code>fib<\/code> function and test it. Here it is:<\/p>\n<pre class=\"lang:default decode:true \">def fib(n):\r\n    if n &lt; 1:\r\n        return None\r\n    if n &lt; 3:\r\n        return 1\r\n\r\n    elem_1 = elem_2 = 1\r\n    the_sum = 0\r\n    for i in range(3, n + 1):\r\n        the_sum = elem_1 + elem_2\r\n        elem_1, elem_2 = elem_2, the_sum\r\n    return the_sum\r\n\r\n\r\nfor n in range(1, 10):  # testing\r\n    print(n, \"-&gt;\", fib(n))\r\n\r\n<\/pre>\n<p>Recursion version:<\/p>\n<pre class=\"lang:default decode:true \">def fib(n):\r\n    if n &lt; 1:\r\n        return None\r\n    if n &lt; 3:\r\n        return 1\r\n    return fib(n - 1) + fib(n - 2)\r\n\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>1. A function is a block of code that performs a specific task when the function is called (invoked). You can use functions to make your code reusable, better organized, and more readable. Functions can have parameters and return values.<\/p>\n","protected":false},"author":2,"featured_media":5926,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[100],"tags":[],"_links":{"self":[{"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/posts\/5167"}],"collection":[{"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/comments?post=5167"}],"version-history":[{"count":33,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/posts\/5167\/revisions"}],"predecessor-version":[{"id":5927,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/posts\/5167\/revisions\/5927"}],"wp:featuredmedia":[{"embeddable":true,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/media\/5926"}],"wp:attachment":[{"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/media?parent=5167"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/categories?post=5167"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/tags?post=5167"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}