{"id":2398,"date":"2012-12-22T04:16:46","date_gmt":"2012-12-22T04:16:46","guid":{"rendered":"https:\/\/www.pythonforbeginners.com\/?p=2398"},"modified":"2020-12-02T20:59:46","modified_gmt":"2020-12-03T02:59:46","slug":"python-functions-cheat-sheet","status":"publish","type":"post","link":"https:\/\/www.pythonforbeginners.com\/basics\/python-functions-cheat-sheet","title":{"rendered":"Functions"},"content":{"rendered":"<h2>What is a function in Python?<\/h2>\n<p>A function is something you can call (possibly with some parameters, the things you put in the parentheses), which performs an action and returns a value.<\/p>\n<h2>Why should I use functions?<\/h2>\n<ul>\n<li>Reduce code tasks into simples tasks<\/li>\n<li>Can easier split up the code between developers<\/li>\n<li>Elimination of duplicate code<\/li>\n<li>Reuse code<\/li>\n<li>Get a good structure of the code<\/li>\n<li>Easier debugging.<\/li>\n<\/ul>\n<h2>What are the rules of functions?<\/h2>\n<ul>\n<li>A function in Python must be defined before it\u2019s used.<\/li>\n<li>Create a function by using the keyword \u201cdef\u201d followed by the functions name and the parentheses ().<\/li>\n<li>The function has to be named plus specify what parameter it has (if any).<\/li>\n<li>A function can use a number of arguments and every argument is responding to a parameter in the function.<\/li>\n<li>A function can use a number of arguments and every argument is responding to a parameter in the function.<\/li>\n<li>&nbsp;The keyword &#8220;def&#8221; is required and must be in lowercase.<\/li>\n<li>The name can be anything you like.<\/li>\n<li>The end of the line has to end with a colon (:)<\/li>\n<li>The function often ends by returning a value using return.<\/li>\n<li>The code inside the function must be indented<\/li>\n<li>The function is used when called.&nbsp;<\/li>\n<\/ul>\n<h2>Parameters (Arguments)<\/h2>\n<p>Parameters (also known as arguments) are inputs to functions. All parameters (arguments) in the Python language are passed by reference. There are some different types of parameters, two of them are:<\/p>\n<h3>Position<\/h3>\n<p>Positional arguments do not have keywords and are assigned first.<\/p>\n<h3>Keyword<\/h3>\n<p>Keyword arguments have keywords and are assigned second, after positional arguments. When you call a function you make a decision to use position or keyword or a mixture. You can choose to do all keywords if you want.<\/p>\n<h2>Call<\/h2>\n<p>A call of a function a procedure or a function must have parenthesis. Between the parenthesis, you can have one or more parameter values, but it can also be empty.<\/p>\n<p>The first thing that happens is that the functions parameters get their values, and then continue with the rest of the code in the function. When a functions value is done, it returns it to the call.<\/p>\n<p><strong>Function call with one parameter:<\/strong><\/p>\n<p>normal = celsius_to_fahrenheit(c_temp)<\/p>\n<p><strong> Function call without parameters:<\/strong><\/p>\n<p>x = input()<\/p>\n<p><strong> Procedure call with two parameters:<\/strong><\/p>\n<p>rectangle(20,10)<\/p>\n<p><strong> Procedure call without parameters:<\/strong><\/p>\n<p>say_hello()<\/p>\n<p>Remember that when Python makes a call, the function must already be defined.<\/p>\n<h2>Return<\/h2>\n<p>While the parameters are the inputs to functions, the Return values are the outputs.<\/p>\n<p>The return keyword is used to return values from a function. The function will exit upon the return command. (all code after that will be ignored)<\/p>\n<p>A function may or may not return a value. If a function does not have a return keyword, it will send a None value.<\/p>\n<h2>Create functions in Python<\/h2>\n<p>First thing when creating a function in Python is to define it and give it a name (possibly with some parameters between the parentheses)<\/p>\n<p>define it and give it a name &gt;&gt; def name()<\/p>\n<p>Create directions for the function &gt;&gt; commands<\/p>\n<p>Call the function &gt;&gt; name()<\/p>\n<p>You can send values to your function, by creating variables in the definition. (These variables only works inside this particular functions)<\/p>\n<p>Let&#8217;s see an example:<\/p>\n<p>The first line defines the function numbers()<\/p>\n<p>The function has two parameters num1 and num2<\/p>\n<p>The second lines makes the addition of num1 and num2<\/p>\n<pre><code class=\"language-python\">def numbers(num1, num2): \n\n   \n    print num1+num2 <\/code><\/pre>\n<p>If this definition is at the beginning of the program, all we have to do is write def numbers(1,2) to send the values to the function.<\/p>\n<p>We do that by placing values in the function call. You can also define mathematical functions. This takes the square root of a number: def square(x): return x*x<\/p>\n<p>Let&#8217;s see an example how to create a simple function any parameters.<\/p>\n<pre><code class=\"language-python\">def name():\n    # Get the user's name.\n    name = raw_input('Enter your name: ') \n\n    # Return the name.\n    return name         \n\nname()\n<\/code><\/pre>\n<p>In this second example show how an argument is passed to a function:<\/p>\n<pre><code class=\"language-python\">def even(number):        \n    if number % 2 == 0:\n        return True\n   \n    else:\n        return False\n\nprint even(10)\n<\/code><\/pre>\n<h2>Examples<\/h2>\n<p>If you haven&#8217;t read the <a title=\"non-programmers\" href=\"http:\/\/en.wikibooks.org\/wiki\/Non-Programmer's_Tutorial_for_Python_2.6\/Defining_Functions\" target=\"_blank\" rel=\"noopener noreferrer\">Non-Programmer&#8217;s Tutorial for Python<\/a> yet, read it. It&#8217;s a great resource for <a href=\"https:\/\/www.pythonforbeginners.com\/learn-python\">learning Python<\/a>.<\/p>\n<p>This example which converts temperatures is a good example of how to use functions.<\/p>\n<pre><code class=\"language-python\">def print_options():\n    print \"Options:\"\n    print \" 'p' print options\"\n    print \" 'c' convert from celsius\"\n    print \" 'f' convert from fahrenheit\"\n    print \" 'q' quit the program\"\n \ndef celsius_to_fahrenheit(c_temp):\n    return 9.0 \/ 5.0 * c_temp + 32\n \ndef fahrenheit_to_celsius(f_temp):\n    return (f_temp - 32.0) * 5.0 \/ 9.0\n \nchoice = \"p\"\n\nwhile choice != \"q\":\n\n    if choice == \"c\":\n        temp = input(\"Celsius temperature: \")\n        print \"Fahrenheit:\", celsius_to_fahrenheit(temp)\n\n    elif choice == \"f\":\n        temp = input(\"Fahrenheit temperature: \")\n        print \"Celsius:\", fahrenheit_to_celsius(temp)\n\n    elif choice != \"q\":\n        print_options()\n\n    choice = raw_input(\"option: \")\n<\/code><\/pre>\n<p>I hope that you like this cheat sheet and that you have learned something today.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>What is a function in Python? A function is something you can call (possibly with some parameters, the things you put in the parentheses), which performs an action and returns a value. Why should I use functions? Reduce code tasks into simples tasks Can easier split up the code between developers Elimination of duplicate code [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_genesis_hide_title":false,"_genesis_hide_breadcrumbs":false,"_genesis_hide_singular_image":false,"_genesis_hide_footer_widgets":false,"_genesis_custom_body_class":"","_genesis_custom_post_class":"","_genesis_layout":"","_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[96,204],"tags":[],"class_list":{"0":"post-2398","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-basics","7":"category-functions","8":"entry"},"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.3 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Functions - PythonForBeginners.com<\/title>\n<meta name=\"description\" content=\"Functions will help you improve your python skills with easy to follow examples and tutorials. Click here to view code examples.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.pythonforbeginners.com\/basics\/python-functions-cheat-sheet\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Functions - PythonForBeginners.com\" \/>\n<meta property=\"og:description\" content=\"Functions will help you improve your python skills with easy to follow examples and tutorials. Click here to view code examples.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.pythonforbeginners.com\/basics\/python-functions-cheat-sheet\" \/>\n<meta property=\"og:site_name\" content=\"PythonForBeginners.com\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/pythonbeginners\" \/>\n<meta property=\"article:published_time\" content=\"2012-12-22T04:16:46+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2020-12-03T02:59:46+00:00\" \/>\n<meta name=\"author\" content=\"PFB Staff Writer\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@pythonbeginners\" \/>\n<meta name=\"twitter:site\" content=\"@pythonbeginners\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"PFB Staff Writer\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/www.pythonforbeginners.com\\\/basics\\\/python-functions-cheat-sheet#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.pythonforbeginners.com\\\/basics\\\/python-functions-cheat-sheet\"},\"author\":{\"name\":\"PFB Staff Writer\",\"@id\":\"https:\\\/\\\/www.pythonforbeginners.com\\\/#\\\/schema\\\/person\\\/1f49841b9ba76108d92e7ef1ca5ee648\"},\"headline\":\"Functions\",\"datePublished\":\"2012-12-22T04:16:46+00:00\",\"dateModified\":\"2020-12-03T02:59:46+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.pythonforbeginners.com\\\/basics\\\/python-functions-cheat-sheet\"},\"wordCount\":702,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\\\/\\\/www.pythonforbeginners.com\\\/#organization\"},\"articleSection\":[\"Basics\",\"Functions\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.pythonforbeginners.com\\\/basics\\\/python-functions-cheat-sheet#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.pythonforbeginners.com\\\/basics\\\/python-functions-cheat-sheet\",\"url\":\"https:\\\/\\\/www.pythonforbeginners.com\\\/basics\\\/python-functions-cheat-sheet\",\"name\":\"Functions - PythonForBeginners.com\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.pythonforbeginners.com\\\/#website\"},\"datePublished\":\"2012-12-22T04:16:46+00:00\",\"dateModified\":\"2020-12-03T02:59:46+00:00\",\"description\":\"Functions will help you improve your python skills with easy to follow examples and tutorials. Click here to view code examples.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.pythonforbeginners.com\\\/basics\\\/python-functions-cheat-sheet#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.pythonforbeginners.com\\\/basics\\\/python-functions-cheat-sheet\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.pythonforbeginners.com\\\/basics\\\/python-functions-cheat-sheet#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.pythonforbeginners.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Functions\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.pythonforbeginners.com\\\/#website\",\"url\":\"https:\\\/\\\/www.pythonforbeginners.com\\\/\",\"name\":\"PythonForBeginners.com\",\"description\":\"Learn By Example\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.pythonforbeginners.com\\\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.pythonforbeginners.com\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/www.pythonforbeginners.com\\\/#organization\",\"name\":\"PythonForBeginners.com\",\"url\":\"https:\\\/\\\/www.pythonforbeginners.com\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.pythonforbeginners.com\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/www.pythonforbeginners.com\\\/wp-content\\\/uploads\\\/2020\\\/05\\\/PFB-Logo-Final.png\",\"contentUrl\":\"https:\\\/\\\/www.pythonforbeginners.com\\\/wp-content\\\/uploads\\\/2020\\\/05\\\/PFB-Logo-Final.png\",\"width\":1868,\"height\":318,\"caption\":\"PythonForBeginners.com\"},\"image\":{\"@id\":\"https:\\\/\\\/www.pythonforbeginners.com\\\/#\\\/schema\\\/logo\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/www.facebook.com\\\/pythonbeginners\",\"https:\\\/\\\/x.com\\\/pythonbeginners\"]},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.pythonforbeginners.com\\\/#\\\/schema\\\/person\\\/1f49841b9ba76108d92e7ef1ca5ee648\",\"name\":\"PFB Staff Writer\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/43a6730888902641f2b8e13d1eb78522f178077d85b17a796302635c434a3ac0?s=96&d=mm&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/43a6730888902641f2b8e13d1eb78522f178077d85b17a796302635c434a3ac0?s=96&d=mm&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/43a6730888902641f2b8e13d1eb78522f178077d85b17a796302635c434a3ac0?s=96&d=mm&r=g\",\"caption\":\"PFB Staff Writer\"},\"url\":\"https:\\\/\\\/www.pythonforbeginners.com\\\/author\\\/pfb_staff\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Functions - PythonForBeginners.com","description":"Functions will help you improve your python skills with easy to follow examples and tutorials. Click here to view code examples.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.pythonforbeginners.com\/basics\/python-functions-cheat-sheet","og_locale":"en_US","og_type":"article","og_title":"Functions - PythonForBeginners.com","og_description":"Functions will help you improve your python skills with easy to follow examples and tutorials. Click here to view code examples.","og_url":"https:\/\/www.pythonforbeginners.com\/basics\/python-functions-cheat-sheet","og_site_name":"PythonForBeginners.com","article_publisher":"https:\/\/www.facebook.com\/pythonbeginners","article_published_time":"2012-12-22T04:16:46+00:00","article_modified_time":"2020-12-03T02:59:46+00:00","author":"PFB Staff Writer","twitter_card":"summary_large_image","twitter_creator":"@pythonbeginners","twitter_site":"@pythonbeginners","twitter_misc":{"Written by":"PFB Staff Writer","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.pythonforbeginners.com\/basics\/python-functions-cheat-sheet#article","isPartOf":{"@id":"https:\/\/www.pythonforbeginners.com\/basics\/python-functions-cheat-sheet"},"author":{"name":"PFB Staff Writer","@id":"https:\/\/www.pythonforbeginners.com\/#\/schema\/person\/1f49841b9ba76108d92e7ef1ca5ee648"},"headline":"Functions","datePublished":"2012-12-22T04:16:46+00:00","dateModified":"2020-12-03T02:59:46+00:00","mainEntityOfPage":{"@id":"https:\/\/www.pythonforbeginners.com\/basics\/python-functions-cheat-sheet"},"wordCount":702,"commentCount":0,"publisher":{"@id":"https:\/\/www.pythonforbeginners.com\/#organization"},"articleSection":["Basics","Functions"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.pythonforbeginners.com\/basics\/python-functions-cheat-sheet#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.pythonforbeginners.com\/basics\/python-functions-cheat-sheet","url":"https:\/\/www.pythonforbeginners.com\/basics\/python-functions-cheat-sheet","name":"Functions - PythonForBeginners.com","isPartOf":{"@id":"https:\/\/www.pythonforbeginners.com\/#website"},"datePublished":"2012-12-22T04:16:46+00:00","dateModified":"2020-12-03T02:59:46+00:00","description":"Functions will help you improve your python skills with easy to follow examples and tutorials. Click here to view code examples.","breadcrumb":{"@id":"https:\/\/www.pythonforbeginners.com\/basics\/python-functions-cheat-sheet#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.pythonforbeginners.com\/basics\/python-functions-cheat-sheet"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.pythonforbeginners.com\/basics\/python-functions-cheat-sheet#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.pythonforbeginners.com\/"},{"@type":"ListItem","position":2,"name":"Functions"}]},{"@type":"WebSite","@id":"https:\/\/www.pythonforbeginners.com\/#website","url":"https:\/\/www.pythonforbeginners.com\/","name":"PythonForBeginners.com","description":"Learn By Example","publisher":{"@id":"https:\/\/www.pythonforbeginners.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.pythonforbeginners.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.pythonforbeginners.com\/#organization","name":"PythonForBeginners.com","url":"https:\/\/www.pythonforbeginners.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.pythonforbeginners.com\/#\/schema\/logo\/image\/","url":"https:\/\/www.pythonforbeginners.com\/wp-content\/uploads\/2020\/05\/PFB-Logo-Final.png","contentUrl":"https:\/\/www.pythonforbeginners.com\/wp-content\/uploads\/2020\/05\/PFB-Logo-Final.png","width":1868,"height":318,"caption":"PythonForBeginners.com"},"image":{"@id":"https:\/\/www.pythonforbeginners.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/pythonbeginners","https:\/\/x.com\/pythonbeginners"]},{"@type":"Person","@id":"https:\/\/www.pythonforbeginners.com\/#\/schema\/person\/1f49841b9ba76108d92e7ef1ca5ee648","name":"PFB Staff Writer","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/43a6730888902641f2b8e13d1eb78522f178077d85b17a796302635c434a3ac0?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/43a6730888902641f2b8e13d1eb78522f178077d85b17a796302635c434a3ac0?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/43a6730888902641f2b8e13d1eb78522f178077d85b17a796302635c434a3ac0?s=96&d=mm&r=g","caption":"PFB Staff Writer"},"url":"https:\/\/www.pythonforbeginners.com\/author\/pfb_staff"}]}},"jetpack_publicize_connections":[],"featured_image_src":null,"featured_image_src_square":null,"author_info":{"display_name":"PFB Staff Writer","author_link":"https:\/\/www.pythonforbeginners.com\/author\/pfb_staff"},"jetpack_featured_media_url":"","jetpack-related-posts":[],"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.pythonforbeginners.com\/wp-json\/wp\/v2\/posts\/2398","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.pythonforbeginners.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.pythonforbeginners.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.pythonforbeginners.com\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.pythonforbeginners.com\/wp-json\/wp\/v2\/comments?post=2398"}],"version-history":[{"count":3,"href":"https:\/\/www.pythonforbeginners.com\/wp-json\/wp\/v2\/posts\/2398\/revisions"}],"predecessor-version":[{"id":8216,"href":"https:\/\/www.pythonforbeginners.com\/wp-json\/wp\/v2\/posts\/2398\/revisions\/8216"}],"wp:attachment":[{"href":"https:\/\/www.pythonforbeginners.com\/wp-json\/wp\/v2\/media?parent=2398"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.pythonforbeginners.com\/wp-json\/wp\/v2\/categories?post=2398"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.pythonforbeginners.com\/wp-json\/wp\/v2\/tags?post=2398"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}