{"appState":{"pageLoadApiCallsStatus":true},"categoryState":{"relatedCategories":{"headers":{"timestamp":"2025-04-17T16:01:07+00:00"},"categoryId":33606,"data":{"title":"Python","slug":"python","image":{"src":null,"width":0,"height":0},"breadcrumbs":[{"name":"Technology","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33512"},"slug":"technology","categoryId":33512},{"name":"Programming & Web Design","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33592"},"slug":"programming-web-design","categoryId":33592},{"name":"Python","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33606"},"slug":"python","categoryId":33606}],"parentCategory":{"categoryId":33592,"title":"Programming & Web Design","slug":"programming-web-design","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33592"}},"childCategories":[],"description":"Don't be scared, it's not poisonous. Python is one of the easiest languages you can learn. Check out our articles on Python here.","relatedArticles":{"self":"https://dummies-api.dummies.com/v2/articles?category=33606&offset=0&size=5"},"hasArticle":true,"hasBook":true,"articleCount":83,"bookCount":6},"_links":{"self":"https://dummies-api.dummies.com/v2/categories/33606"}},"relatedCategoriesLoadedStatus":"success"},"listState":{"list":{"count":10,"total":84,"items":[{"headers":{"creationTime":"2019-10-09T22:32:15+00:00","modifiedTime":"2024-10-28T20:21:54+00:00","timestamp":"2024-10-28T21:01:27+00:00"},"data":{"breadcrumbs":[{"name":"Technology","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33512"},"slug":"technology","categoryId":33512},{"name":"Programming & Web Design","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33592"},"slug":"programming-web-design","categoryId":33592},{"name":"Python","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33606"},"slug":"python","categoryId":33606}],"title":"How to Define and Use Python Lists","strippedTitle":"how to define and use python lists","slug":"how-to-define-and-use-python-lists","canonicalUrl":"","seo":{"metaDescription":"Use this guide from Dummies.com to learn how to define and use Python lists. This Python tutorial helps you make the most of your Python lists.","noIndex":0,"noFollow":0},"content":"The simplest data collection in <a href=\"https://www.dummies.com/programming/python/python-all-in-one-for-dummies-cheat-sheet/\">Python</a> is a list. A <em>list</em> is any list of data items, separated by commas, inside square brackets. Typically, you assign a name to the Python list using an = sign, just as you would with variables. If the list contains numbers, then don't use quotation marks around them. For example, here is a list of test scores:\r\n<pre class=\"code\">scores = [88, 92, 78, 90, 98, 84]</pre>\r\nIf the list contains strings then, as always, those strings should be enclosed in single or double quotation marks, as in this example:\r\n\r\nTo display the contents of a list on the screen, you can print it just as you would print any regular variable. For example, executing <code>print(students)</code> in your code after defining that list shows this on the screen.\r\n<pre class=\"code\">['Mark', 'Amber', 'Todd', 'Anita', 'Sandy']</pre>\r\nThis may not be exactly what you had in mind. But don’t worry, Python offers lots of great ways to access data in lists and display it however you like.\r\n<h2 id=\"tab1\" >Referencing Python list items by position</h2>\r\nEach item in a list has a position number, starting with zero, even though you don’t see any numbers. You can refer to any item in the list by its number using the name for the list followed by a number in square brackets. In other words, use this syntax:\r\n<pre class=\"code\">&lt;em&gt;listname&lt;/em&gt;[&lt;em&gt;x&lt;/em&gt;]\r\n\r\nReplace &lt;em&gt;&lt;code&gt;listname&lt;/code&gt;&lt;/em&gt; with the name of the list you're accessing and replace &lt;em&gt;&lt;code&gt;x&lt;/code&gt;&lt;/em&gt; with the position number of item you want. Remember, the first item is always number zero, not one. For example, in the first line below, I define a list named &lt;code&gt;students&lt;/code&gt;, and then print item number zero from that list. The result, when executing the code, is that the name &lt;code&gt;Mark&lt;/code&gt; is displayed.</pre>\r\n<pre class=\"code\">students = [\"Mark\", \"Amber\", \"Todd\", \"Anita\", \"Sandy\"]\r\nprint(students[0])\r\nMark</pre>\r\n<technicalstuff>\r\n\r\nWhen reading access list items, professionals use the word <em>sub</em> before the number. For example, <em>students[0]</em> would be spoken as <em>students sub zero</em>.\r\n\r\nThis next example shows a list named <code>scores</code>. The <code>print()</code> function prints the position number of the last score in the list, which is 4 (because the first one is always zero).\r\n<pre class=\"code\">scores = [88, 92, 78, 90, 84]\r\nprint(scores[4])\r\n84</pre>\r\nIf you try to access a list item that doesn't exist, you get an “index out of range” error. The <em>index</em> part is a reference to the number inside the square brackets. For example, the image below shows a little experiment in a <a href=\"https://www.dummies.com/programming/python/tips-for-using-jupyter-notebook-for-python-programming/\">Jupyter notebook</a> where a list of scores was created and then the printing of <code>score[5]</code> was attempted.\r\n\r\nIt failed and generated an error because there is no <code>scores[5]</code>. There's only <code>scores[0]</code>, <code>scores[1]</code>, <code>scores[2]</code>, <code>scores[3]</code>, and <code>scores[4]</code> because the counting always starts at zero with the first one on the list.\r\n\r\n[caption id=\"attachment_264920\" align=\"aligncenter\" width=\"535\"]<img class=\"wp-image-264920 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-index-range.jpg\" alt=\"Python index range\" width=\"535\" height=\"212\" /> Index out of range error because there is no scores[5].[/caption] \r\n<h2 id=\"tab2\" >Looping through a Python list</h2>\r\nTo access each item in a list, just use a for loop with this syntax:\r\n<pre class=\"code\">for &lt;em&gt;x&lt;/em&gt; in &lt;em&gt;list&lt;/em&gt;:</pre>\r\nReplace <em<code>&gt;x</code> with a variable name of your choosing. Replace <em><code>list</code></em> with the name of the list. An easy way to make the code readable is to always use a plural for the list name (such as <code>students</code>, <code>scores</code>). Then you can use the singular name (<code>student</code>, <code>score</code>) for the variable name. You don't need to use subscript numbers (numbers in square brackets) with this approach either. For example, the following code prints each score in the scores list:\r\n<pre class=\"code\">for score in scores:\r\nprint(score)</pre>\r\nRemember to always indent the code that’s to be executed within the loop. This image shows a more complete example where you can see the result of running the code in a Jupyter notebook.\r\n\r\n[caption id=\"attachment_264921\" align=\"aligncenter\" width=\"262\"]<img class=\"wp-image-264921 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-loop-list.jpg\" alt=\"Looping through a Python list\" width=\"262\" height=\"219\" /> Looping through a list.[/caption]\r\n\r\n \r\n<h2 id=\"tab3\" >Seeing whether a Python list contains an item</h2>\r\nIf you want your code to check the contents of a list to see whether it already contains some item, use <code>in &lt;em&gt;listname&lt;/em&gt;</code> in an <code>if</code> statement or a variable assignment.\r\n\r\nFor example, the code in the image below creates a list of names. Then, two variables store the results of searching the list for the names <em>Anita</em> and <em>Bob</em>. Printing the contents of each variable shows True for the one where the name (Anita) is in the list. The test to see whether Bob is in the list proves False.\r\n\r\n[caption id=\"attachment_264922\" align=\"aligncenter\" width=\"460\"]<img class=\"wp-image-264922 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-list-contain.jpg\" alt=\"Seeing whether an item is in a Python list\" width=\"460\" height=\"244\" /> Seeing whether an item is in a list.[/caption]\r\n\r\n \r\n<h2 id=\"tab4\" >Getting the length of a Python list</h2>\r\nTo determine how many items are in a list, use the <code>len()</code> function (short for <em>length</em>). Put the name of the list inside the parentheses. For example, type the following code into a Jupyter notebook or Python prompt or whatever:\r\n<pre class=\"code\">students = [\"Mark\", \"Amber\", \"Todd\", \"Anita\", \"Sandy\"]\r\nprint(len(students))</pre>\r\nRunning that code produces this output:\r\n<pre class=\"code\">5</pre>\r\nThere are indeed five items in the list, though the last one is always one less than the number because Python starts counting at zero. So the last one, Sandy, actually refers to students[4] and not students[5].\r\n<h2 id=\"tab5\" >Appending an item to the end of a Python list</h2>\r\nWhen you want your Python code to add a new item to the end of a list, use the <code>.append()</code> method with the value you want to add inside the parentheses. You can use either a variable name or a literal value inside the quotation marks.\r\n\r\nFor instance, in the following image the line that reads <code>students.append(\"Goober\")</code> adds the name Goober to the list. The line that reads <code>students.append(new_student)</code> adds whatever name is stored in the variable named <code>new_student</code> to the list. The <code>.append()</code> method always adds to the end of the list. So when you print the list you see those two new names at the end.\r\n\r\n[caption id=\"attachment_264923\" align=\"aligncenter\" width=\"533\"]<img class=\"wp-image-264923 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-append-list.jpg\" alt=\"Python append list\" width=\"533\" height=\"272\" /> Appending two new names to the end of the list.[/caption]\r\n\r\n \r\n\r\nYou can use a test to see whether an item is in a list and then append it only when the item isn't already there. For example, the code below won’t add the name Amber to the list because that name is already in the list:\r\n<pre class=\"code\">student_name = \"Amanda\"\r\n\r\n#Add student_name but only if not already in the list.\r\nif student_name in students:\r\n print (student_name + \" already in the list\")\r\nelse: \r\n students.append(student_name)\r\n print (student_name + \" added to the list\")</pre>\r\n<h2 id=\"tab6\" >Inserting an item into a Python list</h2>\r\nAlthough the <code>append()</code> method allows you to add an item to the end of a list, the <code>insert()</code> method allows you to add an item to the list in any position. The syntax for <code>insert()</code> is\r\n<pre class=\"code\">&lt;em&gt;listname&lt;/em&gt;.insert(&lt;em&gt;position&lt;/em&gt;, &lt;em&gt;item&lt;/em&gt;)</pre>\r\nReplace <em>listname</em> with the name of the list, <em>position</em> with the position at which you want to insert the item (for example, 0 to make it the first item, 1 to make it the second item, and so forth). Replace <em>item</em> with the value, or the name of a variable that contains the value, that you want to put into the list.\r\n\r\nFor example, the following code makes Lupe the first item in the list:\r\n<pre class=\"code\">#Create a list of strings (names).\r\nstudents = [\"Mark\", \"Amber\", \"Todd\", \"Anita\", \"Sandy\"]\r\n\r\nstudent_name = \"Lupe\"\r\n# Add student name to front of the list.\r\nstudents.insert(0,student_name)\r\n\r\n#Show me the new list.\r\nprint(students)</pre>\r\nIf you run the code, <code>print(students)</code> will show the list after the new name has been inserted, as follows:\r\n<pre class=\"code\">['Lupe', 'Mark', 'Amber', 'Todd', 'Anita', 'Sandy']</pre>\r\n<h2 id=\"tab7\" >Changing an item in a Python list</h2>\r\nYou can change an item in a list using the = assignment operator (check out these <a href=\"https://www.dummies.com/programming/python/common-python-operators/\">common Python operators</a>) just like you do with variables. Just make sure you include the index number in square brackets of the item you want to change. The syntax is:\r\n\r\n<em>listname</em>[<em>index</em>]=<em>newvalue</em>\r\n\r\nReplace <em><code>listname</code></em> with the name of the list; replace <em><code>index</code></em> with the subscript (index number) of the item you want to change; and replace <em><code>newvalue</code></em> with whatever you want to put in the list item. For example, take a look at this code:\r\n<pre class=\"code\">#Create a list of strings (names).\r\nstudents = [\"Mark\", \"Amber\", \"Todd\", \"Anita\", \"Sandy\"]\r\nstudents[3] = \"Hobart\"\r\nprint(students)</pre>\r\nWhen you run this code, the output is as follows, because Anita's name has been changed to Hobart.\r\n<pre class=\"code\">['Mark', 'Amber', 'Todd', 'Hobart', 'Sandy']</pre>\r\n<h2 id=\"tab8\" >Combining Python lists</h2>\r\nIf you have two lists that you want to combine into a single list, use the <code>extend()</code> function with the syntax:\r\n<pre class=\"code\">&lt;em&gt;original_list&lt;/em&gt;.extend(&lt;em&gt;additional_items_list&lt;/em&gt;)</pre>\r\nIn your code, replace <em>original_list</em> with the name of the list to which you’ll be adding new list items. Replace <em>additional_items_list</em> with the name of the list that contains the items you want to add to the first list. Here is a simple example using lists named <code>list1</code> and <code>list2</code>. After executing <code>list1.extend(list2)</code>, the first list contains the items from both lists, as you can see in the output of the <code>print()</code> statement at the end.\r\n<pre class=\"code\"># Create two lists of Names.\r\nlist1 = [\"Zara\", \"Lupe\", \"Hong\", \"Alberto\", \"Jake\"]\r\nlist2 = [\"Huey\", \"Dewey\", \"Louie\", \"Nader\", \"Bubba\"]\r\n\r\n# Add list2 names to list1.\r\nlist1.extend(list2)\r\n\r\n# Print list 1.\r\nprint(list1)\r\n\r\n['Zara', 'Lupe', 'Hong', 'Alberto', 'Jake', 'Huey', 'Dewey', 'Louie', 'Nader', 'Bubba']</pre>\r\nEasy Parcheesi, no?\r\n<h2 id=\"tab9\" >Removing Python list items</h2>\r\nPython offers a <code>remove()</code> method so you can remove any value from the list. If the item is in the list multiple times, only the first occurrence is removed. For example, the following code shows a list of letters with the letter <em>C</em> repeated a few times. Then the code uses <code>letters.remove(\"C\")</code> to remove the letter <em>C</em> from the list:\r\n<pre class=\"code\"># Remove \"C\" from the list.\r\nletters.remove(\"C\")\r\n\r\n#Show me the new list.\r\nprint(letters)</pre>\r\nWhen you actually execute this code and then print the list, you'll see that only the first letter <em>C</em> has been removed:\r\n<pre class=\"code\">['A', 'B', 'D', 'C', 'E', 'C']</pre>\r\nIf you need to remove all of an item, you can use a <code>while</code> loop to repeat the <code>.remove</code> as long as the item still remains in the list. For example, this code repeats the .remove as long as the “C” is still in the list.\r\n<pre class=\"code\">#Create a list of strings.\r\nletters = [\"A\", \"B\", \"C\", \"D\", \"C\", \"E\", \"C\"]</pre>\r\nIf you want to remove an item based on its position in the list, use <code>pop()</code> with an index number rather than <code>remove()</code> with a value. If you want to remove the last item from the list, use <code>pop()</code> without an index number.\r\n\r\nFor example, the following code creates a list, one line removes the first item (0), and another removes the last item <code>(pop()</code> with nothing in the parentheses). Printing the list shows those two items have been removed:\r\n<pre class=\"code\">#Create a list of strings.\r\nletters = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\"]\r\n \r\n#Remove the first item.\r\nletters.pop(0)\r\n#Remove the last item.\r\nletters.pop()\r\n \r\n#Show me the new list.\r\nprint(letters)</pre>\r\nRunning the code shows that the popping the first and last items did, indeed, work:\r\n<pre class=\"code\">['B', 'C', 'D', 'E', 'F']</pre>\r\nWhen you <code>pop()</code> an item off the list, you can store a copy of that value in some variable. For example this image shows the same code as above. However, it stores copies of what's been removed in variables named <code>first_removed</code> and <code>last_removed</code>. At the end it <a href=\"https://www.dummies.com/programming/python/printing-lists-using-python/\">prints the Python list</a>, and also shows which letters were removed.\r\n\r\n[caption id=\"attachment_264924\" align=\"aligncenter\" width=\"535\"]<img class=\"wp-image-264924 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-remove-list-item.jpg\" alt=\"remove items from Python list\" width=\"535\" height=\"231\" /> Removing list items with pop().[/caption]\r\n\r\nPython also offers a <code>del</code> (short for <em>delete</em>) command that deletes any item from a list based on its index number (position). But again, you have to remember that the first item is zero. So, let's say you run the following code to delete item number 2 from the list:\r\n<pre class=\"code\"># Create a list of strings.\r\nletters = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\"]\r\n \r\n# Remove item sub 2.\r\ndel letters[2]\r\n \r\nprint(letters)</pre>\r\nRunning that code shows the list again, as follows. The letter <em>C</em> has been deleted, which is the correct item to delete because letters are numbered 0, 1, 2, 3, and so forth.\r\n<pre class=\"code\">['A', 'B', 'D', 'E', 'F', 'G']</pre>\r\nYou can also use del to delete an entire list. Just don’t use the square brackets and the index number. For example, the code you see below creates a list then deletes it. Trying to print the list after the deletion causes an error, because the list no longer exists when the <code>print()</code> statement is executed.\r\n\r\n[caption id=\"attachment_264925\" align=\"aligncenter\" width=\"535\"]<img class=\"wp-image-264925 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-delete-list.jpg\" alt=\"delete Python list\" width=\"535\" height=\"273\" /> Deleting a list and then trying to print it causes an error.[/caption]\r\n\r\n \r\n<h2 id=\"tab10\" >Clearing out a Python list</h2>\r\nIf you want to delete the contents of a list but not the list itself, use <code>.clear()</code>. The list still exists; however, it contains no items. In other words, it's an empty list. The following code shows how you could test this. Running the code displays [] at the end, which lets you know the list is empty:\r\n<pre class=\"code\"># Create a list of strings.\r\nletters = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\"]\r\n \r\n# Clear the list of all entries.\r\nletters.clear()\r\n \r\n# Show me the new list.\r\nprint(letters)\r\n</pre>\r\n\r\n<h2 id=\"tab11\" >Counting how many times an item appears in a Python list</h2>\r\nYou can use the Python <code>count()</code> method to count how many times an item appears in a list. As with other list methods, the syntax is simple:\r\n<pre class=\"code\">&lt;em&gt;listname&lt;/em&gt;.count(&lt;em&gt;x&lt;/em&gt;)</pre>\r\nReplace <em>listname</em> with the name of your list, and <em>x</em> with the value you're looking for (or the name of a variable that contains that value).\r\n\r\nThe code in the image below counts how many times the letter <em>B</em> appears in the list, using a literal B inside the parentheses of <code>.count()</code>. This same code also counts the number of <em>C</em> grades, but that value was stored in a variable just to show the difference in syntax. Both counts worked, as you can see in the output of the program at the bottom. One was added to count the <em>F</em>'s, not using any variables. The <em>F</em>’s were counted right in the code that displays the message. There are no <em>F</em> grades, so this returns zero, as you can see in the output.\r\n\r\n[caption id=\"attachment_264926\" align=\"aligncenter\" width=\"535\"]<img class=\"wp-image-264926 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-count-list-item.jpg\" alt=\"count Python list items\" width=\"535\" height=\"296\" /> Counting items in a list.[/caption]\r\n\r\nWhen trying to combine numbers and strings to form a message, remember you have to convert the numbers to strings using the <code>str()</code> function. Otherwise, you get an error that reads something like can only <code>concatenate str (not \"int\") to str</code>. In that message, <code>int</code> is short for <em>integer</em>, and <code>str</code> is short for <em>string</em>.\r\n<h2 id=\"tab12\" >Finding a Python list item's index</h2>\r\nPython offers an .index() method that returns a number indicating the position, based on index number, of an item in a list. The syntax is:\r\n<pre class=\"code\">&lt;em&gt;listname&lt;/em&gt;.index(&lt;em&gt;x&lt;/em&gt;)</pre>\r\nAs always, replace <em><code>listname</code></em> with name of the list you want to search. Replace <em>x</em> what whatever you're looking for (either as a literal or as a variable name, as always). Of course, there’s no guarantee that the item is in the list, and even if it is, there’s no guarantee that the item is in the list only once. If the item isn’t in the list, then an error occurs. If the item is in the list multiple times, then the index of the first matching item is returned.\r\n\r\nThe following image shows an example where the program crashes at the line <code>f_index = grades.index(look_for)</code> because there is no <em>F</em> in the list.\r\n\r\n[caption id=\"attachment_264927\" align=\"aligncenter\" width=\"535\"]<img class=\"wp-image-264927 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-list-iem-index.jpg\" alt=\"Python list item index\" width=\"535\" height=\"374\" /> Program fails when trying to find index of a nonexistent list item.[/caption]\r\n\r\n \r\n\r\nAn easy way to get around that problem is to use an <code>if</code> statement to see whether an item is in the list before you try to get its index number. If the item isn't in the list, display a message saying so. Otherwise, get the index number and show it in a message. That code is as follows:\r\n<pre class=\"code\"># Create a list of strings.\r\ngrades = [\"C\", \"B\", \"A\", \"D\", \"C\", \"B\", \"C\"]\r\n# Decide what to look for\r\nlook_for = \"F\"\r\n# See if the item is in the list.\r\nif look_for in grades:\r\n # If it's in the list, get and show the index.\r\n print(str(look_for) + \" is at index \" + str(grades.index(look_for)))\r\nelse:\r\n # If not in the list, don't even try for index number.\r\n print(str(look_for) + \" isn't in the list.\")</pre>\r\n<h2 id=\"tab13\" >Alphabetizing and sorting Python lists</h2>\r\nPython offers a <code>sort()</code> method for sorting lists. In its simplest form, it alphabetizes the items in the list (if they’re strings). If the list contains numbers, they’re sorted smallest to largest. For a simple sort like that, just use <code>sort()</code> with empty parentheses:\r\n<pre class=\"code\">&lt;em&gt;listname&lt;/em&gt;.sort()</pre>\r\nReplace <em><code>listname</code></em> with the name of your list. The following image shows an example using a list of strings and a list of numbers. In the example, a new list was created for each of them simply by assigning each sorted list to a new list name. Then the code prints the contents of each sorted list.\r\n\r\n[caption id=\"attachment_264928\" align=\"aligncenter\" width=\"496\"]<img class=\"wp-image-264928 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-sort-list.jpg\" alt=\"sort Python list\" width=\"496\" height=\"296\" /> Sorting strings and numbers.[/caption]\r\n\r\n \r\n\r\nIf your list contains strings with a mixture of uppercase and lowercase letters, and if the results of the sort don't look right, try replacing <code>.sort()</code> with <code>.sort(key=lambda s:s.lower())</code> and then running the code again.\r\n\r\nDates are a little trickier because you can’t just type them in as strings, like <code>\"12/31/2020\"</code>. They have to be the <code>date</code> data type to sort correctly. This means using the <code>datetime</code> module and the <code>date()</code> method to define each date. You can add the dates to the list as you would any other list. For example, in the following line, the code creates a list of four dates, and the code is perfectly fine.\r\n<pre class=\"code\">dates = [dt.date(2020,12,31), dt.date(2019,1,31), dt.date(2018,2,28), dt.date(2020,1,1)]</pre>\r\nThe computer certainly won't mind if you create the list this way. But if you want to make the code more readable to yourself or other developers, you may want to create and append each date, one at a time, so just so it’s a little easier to see what’s going on and so you don’t have to deal with so many commas in one line of code. The image below shows an example where an empty list named <code>datelist</code> was created:\r\n<pre class=\"code\">datelist = []</pre>\r\n[caption id=\"attachment_264929\" align=\"aligncenter\" width=\"481\"]<img class=\"wp-image-264929 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-display-dates.jpg\" alt=\"display dates in Python\" width=\"481\" height=\"353\" /> Sorting and displaying dates in a nice format.[/caption]\r\n\r\n \r\n\r\nThen one date at a time was appended to the list using the <code>dt.date(&lt;em&gt;year&lt;/em&gt;,&lt;em&gt;month&lt;/em&gt;,&lt;em&gt;day&lt;/em&gt;)</code> syntax.\r\n\r\nAfter the list is created, the code uses <code>datelist.sort()</code> to sort them into chronological order (earliest to latest). You don’t need to use <code>print(datelist)</code> in that code because that method displays the dates with the data type information included, like this:\r\n<pre class=\"code\">[datetime.date(2018, 2, 28), datetime.date(2019, 1, 31), datetime.date (2020, 1, 1), datetime.date(2020, 12, 31)]</pre>\r\nNot the easiest list to read. So, rather than print the whole list with one <code>print()</code> statement, you can loop through each date in the list, and printed each one formatted with the f-string <code>%m/%d/%Y</code>. This displays each date on its own line in <em>mm/dd/yyyy</</em> format, as you can see at the bottom of the image above.\r\n\r\nIf you want to sort items in reverse order, put <code>reverse=True</code> inside the sort() parentheses (and don't forget to make the first letter uppercase). The image below shows examples of sorting all three lists in descending (reverse) order using <code>reverse=True</code>.\r\n\r\n[caption id=\"attachment_264930\" align=\"aligncenter\" width=\"403\"]<img class=\"wp-image-264930 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-sort-info-reverse.jpg\" alt=\"sort info in Python list in reverse\" width=\"403\" height=\"450\" /> Sorting strings, numbers, and dates in reverse order.[/caption]\r\n\r\n \r\n<h2 id=\"tab14\" >Reversing a Python list</h2>\r\nYou can also reverse the order of items in a list using the <code>.reverse</code> method. This is not the same as sorting in reverse, because when you sort in reverse, you still actually sort: Z–A for strings, largest to smallest for numbers, latest to earliest for dates. When you reverse a list, you simply reverse the items in the list, no matter their order, without trying to sort them in any way.\r\n\r\nThe following code shows an example in which you reverse the order of the names in the list and then print the list. The output shows the list items reversed from their original order:\r\n<pre class=\"code\"># Create a list of strings.\r\nnames = [\"Zara\", \"Lupe\", \"Hong\", \"Alberto\", \"Jake\"]\r\n# Reverse the list\r\nnames.reverse()\r\n# Print the list\r\nprint(names)\r\n \r\n['Jake', 'Alberto', 'Hong', 'Lupe', 'Zara']</pre>\r\n<h2 id=\"tab15\" >Copying a Python list</h2>\r\nIf you ever need to work with a copy of a list, use the <code>.copy()</code> method so as not to alter the original list,. For example, the following code is similar to the preceding code, except that instead of reversing the order of the original list, you make a copy of the list and reverse that one. Printing the contents of each list shows how the first list is still in the original order whereas the second one is reversed:\r\n<pre class=\"code\"># Create a list of strings.\r\nnames = [\"Zara\", \"Lupe\", \"Hong\", \"Alberto\", \"Jake\"]\r\n \r\n# Make a copy of the list\r\nbackward_names = names.copy()\r\n# Reverse the copy\r\nbackward_names.reverse()\r\n \r\n# Print the list\r\nprint(names)\r\nprint(backward_names)\r\n \r\n['Zara', 'Lupe', 'Hong', 'Alberto', 'Jake']\r\n['Jake', 'Alberto', 'Hong', 'Lupe', 'Zara']</pre>\r\nFor future references, the following table summarizes the methods you've learned about.\r\n<table><caption>Methods for Working with Lists</caption>\r\n<thead>\r\n<tr>\r\n<td>Method</td>\r\n<td>What it Does</td>\r\n</tr>\r\n</thead>\r\n<tbody>\r\n<tr>\r\n<td><code>append()</code></td>\r\n<td>Adds an item to the end of the list.</td>\r\n</tr>\r\n<tr>\r\n<td><code>clear()</code></td>\r\n<td>Removes all items from the list, leaving it empty.</td>\r\n</tr>\r\n<tr>\r\n<td><code>copy()</code></td>\r\n<td>Makes a copy of a list.</td>\r\n</tr>\r\n<tr>\r\n<td><code>count()</code></td>\r\n<td>Counts how many times an element appears in a list.</td>\r\n</tr>\r\n<tr>\r\n<td><code>extend()</code></td>\r\n<td>Appends the items from one list to the end of another list.</td>\r\n</tr>\r\n<tr>\r\n<td><code>index()</code></td>\r\n<td>Returns the index number (position) of an element within a list.</td>\r\n</tr>\r\n<tr>\r\n<td><code>insert()</code></td>\r\n<td>Inserts an item into the list at a specific position.</td>\r\n</tr>\r\n<tr>\r\n<td><code>pop()</code></td>\r\n<td>Removes an element from the list, and provides a copy of that item that you can store in a variable.</td>\r\n</tr>\r\n<tr>\r\n<td><code>remove()</code></td>\r\n<td>Removes one item from the list.</td>\r\n</tr>\r\n<tr>\r\n<td><code>reverse()</code></td>\r\n<td>Reverses the order of items in the list.</td>\r\n</tr>\r\n<tr>\r\n<td><code>sort()</code></td>\r\n<td>Sorts the list in ascending order. Put <code>reverse=True</code> inside the parentheses to sort in descending order.</td>\r\n</tr>\r\n</tbody>\r\n</table>\r\n<h1></h1>","description":"The simplest data collection in <a href=\"https://www.dummies.com/programming/python/python-all-in-one-for-dummies-cheat-sheet/\">Python</a> is a list. A <em>list</em> is any list of data items, separated by commas, inside square brackets. Typically, you assign a name to the Python list using an = sign, just as you would with variables. If the list contains numbers, then don't use quotation marks around them. For example, here is a list of test scores:\r\n<pre class=\"code\">scores = [88, 92, 78, 90, 98, 84]</pre>\r\nIf the list contains strings then, as always, those strings should be enclosed in single or double quotation marks, as in this example:\r\n\r\nTo display the contents of a list on the screen, you can print it just as you would print any regular variable. For example, executing <code>print(students)</code> in your code after defining that list shows this on the screen.\r\n<pre class=\"code\">['Mark', 'Amber', 'Todd', 'Anita', 'Sandy']</pre>\r\nThis may not be exactly what you had in mind. But don’t worry, Python offers lots of great ways to access data in lists and display it however you like.\r\n<h2 id=\"tab1\" >Referencing Python list items by position</h2>\r\nEach item in a list has a position number, starting with zero, even though you don’t see any numbers. You can refer to any item in the list by its number using the name for the list followed by a number in square brackets. In other words, use this syntax:\r\n<pre class=\"code\">&lt;em&gt;listname&lt;/em&gt;[&lt;em&gt;x&lt;/em&gt;]\r\n\r\nReplace &lt;em&gt;&lt;code&gt;listname&lt;/code&gt;&lt;/em&gt; with the name of the list you're accessing and replace &lt;em&gt;&lt;code&gt;x&lt;/code&gt;&lt;/em&gt; with the position number of item you want. Remember, the first item is always number zero, not one. For example, in the first line below, I define a list named &lt;code&gt;students&lt;/code&gt;, and then print item number zero from that list. The result, when executing the code, is that the name &lt;code&gt;Mark&lt;/code&gt; is displayed.</pre>\r\n<pre class=\"code\">students = [\"Mark\", \"Amber\", \"Todd\", \"Anita\", \"Sandy\"]\r\nprint(students[0])\r\nMark</pre>\r\n<technicalstuff>\r\n\r\nWhen reading access list items, professionals use the word <em>sub</em> before the number. For example, <em>students[0]</em> would be spoken as <em>students sub zero</em>.\r\n\r\nThis next example shows a list named <code>scores</code>. The <code>print()</code> function prints the position number of the last score in the list, which is 4 (because the first one is always zero).\r\n<pre class=\"code\">scores = [88, 92, 78, 90, 84]\r\nprint(scores[4])\r\n84</pre>\r\nIf you try to access a list item that doesn't exist, you get an “index out of range” error. The <em>index</em> part is a reference to the number inside the square brackets. For example, the image below shows a little experiment in a <a href=\"https://www.dummies.com/programming/python/tips-for-using-jupyter-notebook-for-python-programming/\">Jupyter notebook</a> where a list of scores was created and then the printing of <code>score[5]</code> was attempted.\r\n\r\nIt failed and generated an error because there is no <code>scores[5]</code>. There's only <code>scores[0]</code>, <code>scores[1]</code>, <code>scores[2]</code>, <code>scores[3]</code>, and <code>scores[4]</code> because the counting always starts at zero with the first one on the list.\r\n\r\n[caption id=\"attachment_264920\" align=\"aligncenter\" width=\"535\"]<img class=\"wp-image-264920 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-index-range.jpg\" alt=\"Python index range\" width=\"535\" height=\"212\" /> Index out of range error because there is no scores[5].[/caption] \r\n<h2 id=\"tab2\" >Looping through a Python list</h2>\r\nTo access each item in a list, just use a for loop with this syntax:\r\n<pre class=\"code\">for &lt;em&gt;x&lt;/em&gt; in &lt;em&gt;list&lt;/em&gt;:</pre>\r\nReplace <em<code>&gt;x</code> with a variable name of your choosing. Replace <em><code>list</code></em> with the name of the list. An easy way to make the code readable is to always use a plural for the list name (such as <code>students</code>, <code>scores</code>). Then you can use the singular name (<code>student</code>, <code>score</code>) for the variable name. You don't need to use subscript numbers (numbers in square brackets) with this approach either. For example, the following code prints each score in the scores list:\r\n<pre class=\"code\">for score in scores:\r\nprint(score)</pre>\r\nRemember to always indent the code that’s to be executed within the loop. This image shows a more complete example where you can see the result of running the code in a Jupyter notebook.\r\n\r\n[caption id=\"attachment_264921\" align=\"aligncenter\" width=\"262\"]<img class=\"wp-image-264921 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-loop-list.jpg\" alt=\"Looping through a Python list\" width=\"262\" height=\"219\" /> Looping through a list.[/caption]\r\n\r\n \r\n<h2 id=\"tab3\" >Seeing whether a Python list contains an item</h2>\r\nIf you want your code to check the contents of a list to see whether it already contains some item, use <code>in &lt;em&gt;listname&lt;/em&gt;</code> in an <code>if</code> statement or a variable assignment.\r\n\r\nFor example, the code in the image below creates a list of names. Then, two variables store the results of searching the list for the names <em>Anita</em> and <em>Bob</em>. Printing the contents of each variable shows True for the one where the name (Anita) is in the list. The test to see whether Bob is in the list proves False.\r\n\r\n[caption id=\"attachment_264922\" align=\"aligncenter\" width=\"460\"]<img class=\"wp-image-264922 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-list-contain.jpg\" alt=\"Seeing whether an item is in a Python list\" width=\"460\" height=\"244\" /> Seeing whether an item is in a list.[/caption]\r\n\r\n \r\n<h2 id=\"tab4\" >Getting the length of a Python list</h2>\r\nTo determine how many items are in a list, use the <code>len()</code> function (short for <em>length</em>). Put the name of the list inside the parentheses. For example, type the following code into a Jupyter notebook or Python prompt or whatever:\r\n<pre class=\"code\">students = [\"Mark\", \"Amber\", \"Todd\", \"Anita\", \"Sandy\"]\r\nprint(len(students))</pre>\r\nRunning that code produces this output:\r\n<pre class=\"code\">5</pre>\r\nThere are indeed five items in the list, though the last one is always one less than the number because Python starts counting at zero. So the last one, Sandy, actually refers to students[4] and not students[5].\r\n<h2 id=\"tab5\" >Appending an item to the end of a Python list</h2>\r\nWhen you want your Python code to add a new item to the end of a list, use the <code>.append()</code> method with the value you want to add inside the parentheses. You can use either a variable name or a literal value inside the quotation marks.\r\n\r\nFor instance, in the following image the line that reads <code>students.append(\"Goober\")</code> adds the name Goober to the list. The line that reads <code>students.append(new_student)</code> adds whatever name is stored in the variable named <code>new_student</code> to the list. The <code>.append()</code> method always adds to the end of the list. So when you print the list you see those two new names at the end.\r\n\r\n[caption id=\"attachment_264923\" align=\"aligncenter\" width=\"533\"]<img class=\"wp-image-264923 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-append-list.jpg\" alt=\"Python append list\" width=\"533\" height=\"272\" /> Appending two new names to the end of the list.[/caption]\r\n\r\n \r\n\r\nYou can use a test to see whether an item is in a list and then append it only when the item isn't already there. For example, the code below won’t add the name Amber to the list because that name is already in the list:\r\n<pre class=\"code\">student_name = \"Amanda\"\r\n\r\n#Add student_name but only if not already in the list.\r\nif student_name in students:\r\n print (student_name + \" already in the list\")\r\nelse: \r\n students.append(student_name)\r\n print (student_name + \" added to the list\")</pre>\r\n<h2 id=\"tab6\" >Inserting an item into a Python list</h2>\r\nAlthough the <code>append()</code> method allows you to add an item to the end of a list, the <code>insert()</code> method allows you to add an item to the list in any position. The syntax for <code>insert()</code> is\r\n<pre class=\"code\">&lt;em&gt;listname&lt;/em&gt;.insert(&lt;em&gt;position&lt;/em&gt;, &lt;em&gt;item&lt;/em&gt;)</pre>\r\nReplace <em>listname</em> with the name of the list, <em>position</em> with the position at which you want to insert the item (for example, 0 to make it the first item, 1 to make it the second item, and so forth). Replace <em>item</em> with the value, or the name of a variable that contains the value, that you want to put into the list.\r\n\r\nFor example, the following code makes Lupe the first item in the list:\r\n<pre class=\"code\">#Create a list of strings (names).\r\nstudents = [\"Mark\", \"Amber\", \"Todd\", \"Anita\", \"Sandy\"]\r\n\r\nstudent_name = \"Lupe\"\r\n# Add student name to front of the list.\r\nstudents.insert(0,student_name)\r\n\r\n#Show me the new list.\r\nprint(students)</pre>\r\nIf you run the code, <code>print(students)</code> will show the list after the new name has been inserted, as follows:\r\n<pre class=\"code\">['Lupe', 'Mark', 'Amber', 'Todd', 'Anita', 'Sandy']</pre>\r\n<h2 id=\"tab7\" >Changing an item in a Python list</h2>\r\nYou can change an item in a list using the = assignment operator (check out these <a href=\"https://www.dummies.com/programming/python/common-python-operators/\">common Python operators</a>) just like you do with variables. Just make sure you include the index number in square brackets of the item you want to change. The syntax is:\r\n\r\n<em>listname</em>[<em>index</em>]=<em>newvalue</em>\r\n\r\nReplace <em><code>listname</code></em> with the name of the list; replace <em><code>index</code></em> with the subscript (index number) of the item you want to change; and replace <em><code>newvalue</code></em> with whatever you want to put in the list item. For example, take a look at this code:\r\n<pre class=\"code\">#Create a list of strings (names).\r\nstudents = [\"Mark\", \"Amber\", \"Todd\", \"Anita\", \"Sandy\"]\r\nstudents[3] = \"Hobart\"\r\nprint(students)</pre>\r\nWhen you run this code, the output is as follows, because Anita's name has been changed to Hobart.\r\n<pre class=\"code\">['Mark', 'Amber', 'Todd', 'Hobart', 'Sandy']</pre>\r\n<h2 id=\"tab8\" >Combining Python lists</h2>\r\nIf you have two lists that you want to combine into a single list, use the <code>extend()</code> function with the syntax:\r\n<pre class=\"code\">&lt;em&gt;original_list&lt;/em&gt;.extend(&lt;em&gt;additional_items_list&lt;/em&gt;)</pre>\r\nIn your code, replace <em>original_list</em> with the name of the list to which you’ll be adding new list items. Replace <em>additional_items_list</em> with the name of the list that contains the items you want to add to the first list. Here is a simple example using lists named <code>list1</code> and <code>list2</code>. After executing <code>list1.extend(list2)</code>, the first list contains the items from both lists, as you can see in the output of the <code>print()</code> statement at the end.\r\n<pre class=\"code\"># Create two lists of Names.\r\nlist1 = [\"Zara\", \"Lupe\", \"Hong\", \"Alberto\", \"Jake\"]\r\nlist2 = [\"Huey\", \"Dewey\", \"Louie\", \"Nader\", \"Bubba\"]\r\n\r\n# Add list2 names to list1.\r\nlist1.extend(list2)\r\n\r\n# Print list 1.\r\nprint(list1)\r\n\r\n['Zara', 'Lupe', 'Hong', 'Alberto', 'Jake', 'Huey', 'Dewey', 'Louie', 'Nader', 'Bubba']</pre>\r\nEasy Parcheesi, no?\r\n<h2 id=\"tab9\" >Removing Python list items</h2>\r\nPython offers a <code>remove()</code> method so you can remove any value from the list. If the item is in the list multiple times, only the first occurrence is removed. For example, the following code shows a list of letters with the letter <em>C</em> repeated a few times. Then the code uses <code>letters.remove(\"C\")</code> to remove the letter <em>C</em> from the list:\r\n<pre class=\"code\"># Remove \"C\" from the list.\r\nletters.remove(\"C\")\r\n\r\n#Show me the new list.\r\nprint(letters)</pre>\r\nWhen you actually execute this code and then print the list, you'll see that only the first letter <em>C</em> has been removed:\r\n<pre class=\"code\">['A', 'B', 'D', 'C', 'E', 'C']</pre>\r\nIf you need to remove all of an item, you can use a <code>while</code> loop to repeat the <code>.remove</code> as long as the item still remains in the list. For example, this code repeats the .remove as long as the “C” is still in the list.\r\n<pre class=\"code\">#Create a list of strings.\r\nletters = [\"A\", \"B\", \"C\", \"D\", \"C\", \"E\", \"C\"]</pre>\r\nIf you want to remove an item based on its position in the list, use <code>pop()</code> with an index number rather than <code>remove()</code> with a value. If you want to remove the last item from the list, use <code>pop()</code> without an index number.\r\n\r\nFor example, the following code creates a list, one line removes the first item (0), and another removes the last item <code>(pop()</code> with nothing in the parentheses). Printing the list shows those two items have been removed:\r\n<pre class=\"code\">#Create a list of strings.\r\nletters = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\"]\r\n \r\n#Remove the first item.\r\nletters.pop(0)\r\n#Remove the last item.\r\nletters.pop()\r\n \r\n#Show me the new list.\r\nprint(letters)</pre>\r\nRunning the code shows that the popping the first and last items did, indeed, work:\r\n<pre class=\"code\">['B', 'C', 'D', 'E', 'F']</pre>\r\nWhen you <code>pop()</code> an item off the list, you can store a copy of that value in some variable. For example this image shows the same code as above. However, it stores copies of what's been removed in variables named <code>first_removed</code> and <code>last_removed</code>. At the end it <a href=\"https://www.dummies.com/programming/python/printing-lists-using-python/\">prints the Python list</a>, and also shows which letters were removed.\r\n\r\n[caption id=\"attachment_264924\" align=\"aligncenter\" width=\"535\"]<img class=\"wp-image-264924 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-remove-list-item.jpg\" alt=\"remove items from Python list\" width=\"535\" height=\"231\" /> Removing list items with pop().[/caption]\r\n\r\nPython also offers a <code>del</code> (short for <em>delete</em>) command that deletes any item from a list based on its index number (position). But again, you have to remember that the first item is zero. So, let's say you run the following code to delete item number 2 from the list:\r\n<pre class=\"code\"># Create a list of strings.\r\nletters = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\"]\r\n \r\n# Remove item sub 2.\r\ndel letters[2]\r\n \r\nprint(letters)</pre>\r\nRunning that code shows the list again, as follows. The letter <em>C</em> has been deleted, which is the correct item to delete because letters are numbered 0, 1, 2, 3, and so forth.\r\n<pre class=\"code\">['A', 'B', 'D', 'E', 'F', 'G']</pre>\r\nYou can also use del to delete an entire list. Just don’t use the square brackets and the index number. For example, the code you see below creates a list then deletes it. Trying to print the list after the deletion causes an error, because the list no longer exists when the <code>print()</code> statement is executed.\r\n\r\n[caption id=\"attachment_264925\" align=\"aligncenter\" width=\"535\"]<img class=\"wp-image-264925 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-delete-list.jpg\" alt=\"delete Python list\" width=\"535\" height=\"273\" /> Deleting a list and then trying to print it causes an error.[/caption]\r\n\r\n \r\n<h2 id=\"tab10\" >Clearing out a Python list</h2>\r\nIf you want to delete the contents of a list but not the list itself, use <code>.clear()</code>. The list still exists; however, it contains no items. In other words, it's an empty list. The following code shows how you could test this. Running the code displays [] at the end, which lets you know the list is empty:\r\n<pre class=\"code\"># Create a list of strings.\r\nletters = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\"]\r\n \r\n# Clear the list of all entries.\r\nletters.clear()\r\n \r\n# Show me the new list.\r\nprint(letters)\r\n</pre>\r\n\r\n<h2 id=\"tab11\" >Counting how many times an item appears in a Python list</h2>\r\nYou can use the Python <code>count()</code> method to count how many times an item appears in a list. As with other list methods, the syntax is simple:\r\n<pre class=\"code\">&lt;em&gt;listname&lt;/em&gt;.count(&lt;em&gt;x&lt;/em&gt;)</pre>\r\nReplace <em>listname</em> with the name of your list, and <em>x</em> with the value you're looking for (or the name of a variable that contains that value).\r\n\r\nThe code in the image below counts how many times the letter <em>B</em> appears in the list, using a literal B inside the parentheses of <code>.count()</code>. This same code also counts the number of <em>C</em> grades, but that value was stored in a variable just to show the difference in syntax. Both counts worked, as you can see in the output of the program at the bottom. One was added to count the <em>F</em>'s, not using any variables. The <em>F</em>’s were counted right in the code that displays the message. There are no <em>F</em> grades, so this returns zero, as you can see in the output.\r\n\r\n[caption id=\"attachment_264926\" align=\"aligncenter\" width=\"535\"]<img class=\"wp-image-264926 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-count-list-item.jpg\" alt=\"count Python list items\" width=\"535\" height=\"296\" /> Counting items in a list.[/caption]\r\n\r\nWhen trying to combine numbers and strings to form a message, remember you have to convert the numbers to strings using the <code>str()</code> function. Otherwise, you get an error that reads something like can only <code>concatenate str (not \"int\") to str</code>. In that message, <code>int</code> is short for <em>integer</em>, and <code>str</code> is short for <em>string</em>.\r\n<h2 id=\"tab12\" >Finding a Python list item's index</h2>\r\nPython offers an .index() method that returns a number indicating the position, based on index number, of an item in a list. The syntax is:\r\n<pre class=\"code\">&lt;em&gt;listname&lt;/em&gt;.index(&lt;em&gt;x&lt;/em&gt;)</pre>\r\nAs always, replace <em><code>listname</code></em> with name of the list you want to search. Replace <em>x</em> what whatever you're looking for (either as a literal or as a variable name, as always). Of course, there’s no guarantee that the item is in the list, and even if it is, there’s no guarantee that the item is in the list only once. If the item isn’t in the list, then an error occurs. If the item is in the list multiple times, then the index of the first matching item is returned.\r\n\r\nThe following image shows an example where the program crashes at the line <code>f_index = grades.index(look_for)</code> because there is no <em>F</em> in the list.\r\n\r\n[caption id=\"attachment_264927\" align=\"aligncenter\" width=\"535\"]<img class=\"wp-image-264927 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-list-iem-index.jpg\" alt=\"Python list item index\" width=\"535\" height=\"374\" /> Program fails when trying to find index of a nonexistent list item.[/caption]\r\n\r\n \r\n\r\nAn easy way to get around that problem is to use an <code>if</code> statement to see whether an item is in the list before you try to get its index number. If the item isn't in the list, display a message saying so. Otherwise, get the index number and show it in a message. That code is as follows:\r\n<pre class=\"code\"># Create a list of strings.\r\ngrades = [\"C\", \"B\", \"A\", \"D\", \"C\", \"B\", \"C\"]\r\n# Decide what to look for\r\nlook_for = \"F\"\r\n# See if the item is in the list.\r\nif look_for in grades:\r\n # If it's in the list, get and show the index.\r\n print(str(look_for) + \" is at index \" + str(grades.index(look_for)))\r\nelse:\r\n # If not in the list, don't even try for index number.\r\n print(str(look_for) + \" isn't in the list.\")</pre>\r\n<h2 id=\"tab13\" >Alphabetizing and sorting Python lists</h2>\r\nPython offers a <code>sort()</code> method for sorting lists. In its simplest form, it alphabetizes the items in the list (if they’re strings). If the list contains numbers, they’re sorted smallest to largest. For a simple sort like that, just use <code>sort()</code> with empty parentheses:\r\n<pre class=\"code\">&lt;em&gt;listname&lt;/em&gt;.sort()</pre>\r\nReplace <em><code>listname</code></em> with the name of your list. The following image shows an example using a list of strings and a list of numbers. In the example, a new list was created for each of them simply by assigning each sorted list to a new list name. Then the code prints the contents of each sorted list.\r\n\r\n[caption id=\"attachment_264928\" align=\"aligncenter\" width=\"496\"]<img class=\"wp-image-264928 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-sort-list.jpg\" alt=\"sort Python list\" width=\"496\" height=\"296\" /> Sorting strings and numbers.[/caption]\r\n\r\n \r\n\r\nIf your list contains strings with a mixture of uppercase and lowercase letters, and if the results of the sort don't look right, try replacing <code>.sort()</code> with <code>.sort(key=lambda s:s.lower())</code> and then running the code again.\r\n\r\nDates are a little trickier because you can’t just type them in as strings, like <code>\"12/31/2020\"</code>. They have to be the <code>date</code> data type to sort correctly. This means using the <code>datetime</code> module and the <code>date()</code> method to define each date. You can add the dates to the list as you would any other list. For example, in the following line, the code creates a list of four dates, and the code is perfectly fine.\r\n<pre class=\"code\">dates = [dt.date(2020,12,31), dt.date(2019,1,31), dt.date(2018,2,28), dt.date(2020,1,1)]</pre>\r\nThe computer certainly won't mind if you create the list this way. But if you want to make the code more readable to yourself or other developers, you may want to create and append each date, one at a time, so just so it’s a little easier to see what’s going on and so you don’t have to deal with so many commas in one line of code. The image below shows an example where an empty list named <code>datelist</code> was created:\r\n<pre class=\"code\">datelist = []</pre>\r\n[caption id=\"attachment_264929\" align=\"aligncenter\" width=\"481\"]<img class=\"wp-image-264929 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-display-dates.jpg\" alt=\"display dates in Python\" width=\"481\" height=\"353\" /> Sorting and displaying dates in a nice format.[/caption]\r\n\r\n \r\n\r\nThen one date at a time was appended to the list using the <code>dt.date(&lt;em&gt;year&lt;/em&gt;,&lt;em&gt;month&lt;/em&gt;,&lt;em&gt;day&lt;/em&gt;)</code> syntax.\r\n\r\nAfter the list is created, the code uses <code>datelist.sort()</code> to sort them into chronological order (earliest to latest). You don’t need to use <code>print(datelist)</code> in that code because that method displays the dates with the data type information included, like this:\r\n<pre class=\"code\">[datetime.date(2018, 2, 28), datetime.date(2019, 1, 31), datetime.date (2020, 1, 1), datetime.date(2020, 12, 31)]</pre>\r\nNot the easiest list to read. So, rather than print the whole list with one <code>print()</code> statement, you can loop through each date in the list, and printed each one formatted with the f-string <code>%m/%d/%Y</code>. This displays each date on its own line in <em>mm/dd/yyyy</</em> format, as you can see at the bottom of the image above.\r\n\r\nIf you want to sort items in reverse order, put <code>reverse=True</code> inside the sort() parentheses (and don't forget to make the first letter uppercase). The image below shows examples of sorting all three lists in descending (reverse) order using <code>reverse=True</code>.\r\n\r\n[caption id=\"attachment_264930\" align=\"aligncenter\" width=\"403\"]<img class=\"wp-image-264930 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-sort-info-reverse.jpg\" alt=\"sort info in Python list in reverse\" width=\"403\" height=\"450\" /> Sorting strings, numbers, and dates in reverse order.[/caption]\r\n\r\n \r\n<h2 id=\"tab14\" >Reversing a Python list</h2>\r\nYou can also reverse the order of items in a list using the <code>.reverse</code> method. This is not the same as sorting in reverse, because when you sort in reverse, you still actually sort: Z–A for strings, largest to smallest for numbers, latest to earliest for dates. When you reverse a list, you simply reverse the items in the list, no matter their order, without trying to sort them in any way.\r\n\r\nThe following code shows an example in which you reverse the order of the names in the list and then print the list. The output shows the list items reversed from their original order:\r\n<pre class=\"code\"># Create a list of strings.\r\nnames = [\"Zara\", \"Lupe\", \"Hong\", \"Alberto\", \"Jake\"]\r\n# Reverse the list\r\nnames.reverse()\r\n# Print the list\r\nprint(names)\r\n \r\n['Jake', 'Alberto', 'Hong', 'Lupe', 'Zara']</pre>\r\n<h2 id=\"tab15\" >Copying a Python list</h2>\r\nIf you ever need to work with a copy of a list, use the <code>.copy()</code> method so as not to alter the original list,. For example, the following code is similar to the preceding code, except that instead of reversing the order of the original list, you make a copy of the list and reverse that one. Printing the contents of each list shows how the first list is still in the original order whereas the second one is reversed:\r\n<pre class=\"code\"># Create a list of strings.\r\nnames = [\"Zara\", \"Lupe\", \"Hong\", \"Alberto\", \"Jake\"]\r\n \r\n# Make a copy of the list\r\nbackward_names = names.copy()\r\n# Reverse the copy\r\nbackward_names.reverse()\r\n \r\n# Print the list\r\nprint(names)\r\nprint(backward_names)\r\n \r\n['Zara', 'Lupe', 'Hong', 'Alberto', 'Jake']\r\n['Jake', 'Alberto', 'Hong', 'Lupe', 'Zara']</pre>\r\nFor future references, the following table summarizes the methods you've learned about.\r\n<table><caption>Methods for Working with Lists</caption>\r\n<thead>\r\n<tr>\r\n<td>Method</td>\r\n<td>What it Does</td>\r\n</tr>\r\n</thead>\r\n<tbody>\r\n<tr>\r\n<td><code>append()</code></td>\r\n<td>Adds an item to the end of the list.</td>\r\n</tr>\r\n<tr>\r\n<td><code>clear()</code></td>\r\n<td>Removes all items from the list, leaving it empty.</td>\r\n</tr>\r\n<tr>\r\n<td><code>copy()</code></td>\r\n<td>Makes a copy of a list.</td>\r\n</tr>\r\n<tr>\r\n<td><code>count()</code></td>\r\n<td>Counts how many times an element appears in a list.</td>\r\n</tr>\r\n<tr>\r\n<td><code>extend()</code></td>\r\n<td>Appends the items from one list to the end of another list.</td>\r\n</tr>\r\n<tr>\r\n<td><code>index()</code></td>\r\n<td>Returns the index number (position) of an element within a list.</td>\r\n</tr>\r\n<tr>\r\n<td><code>insert()</code></td>\r\n<td>Inserts an item into the list at a specific position.</td>\r\n</tr>\r\n<tr>\r\n<td><code>pop()</code></td>\r\n<td>Removes an element from the list, and provides a copy of that item that you can store in a variable.</td>\r\n</tr>\r\n<tr>\r\n<td><code>remove()</code></td>\r\n<td>Removes one item from the list.</td>\r\n</tr>\r\n<tr>\r\n<td><code>reverse()</code></td>\r\n<td>Reverses the order of items in the list.</td>\r\n</tr>\r\n<tr>\r\n<td><code>sort()</code></td>\r\n<td>Sorts the list in ascending order. Put <code>reverse=True</code> inside the parentheses to sort in descending order.</td>\r\n</tr>\r\n</tbody>\r\n</table>\r\n<h1></h1>","blurb":"","authors":[{"authorId":26709,"name":"Alan Shovic","slug":"alan-shovic","description":"","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/26709"}},{"authorId":26710,"name":"John C. Shovic","slug":"john-shovic","description":"John Shovic, PhD, is a computer science faculty member at the University of Idaho specializing in robotics and artificial intelligence.","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/26710"}}],"primaryCategoryTaxonomy":{"categoryId":33606,"title":"Python","slug":"python","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33606"}},"secondaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"tertiaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"trendingArticles":[{"articleId":192609,"title":"How to Pray the Rosary: A Comprehensive Guide","slug":"how-to-pray-the-rosary","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/192609"}},{"articleId":208741,"title":"Kabbalah For Dummies Cheat Sheet","slug":"kabbalah-for-dummies-cheat-sheet","categoryList":["body-mind-spirit","religion-spirituality","kabbalah"],"_links":{"self":"/articles/208741"}},{"articleId":230957,"title":"Nikon D3400 For Dummies Cheat Sheet","slug":"nikon-d3400-dummies-cheat-sheet","categoryList":["home-auto-hobbies","photography"],"_links":{"self":"/articles/230957"}},{"articleId":235851,"title":"Praying the Rosary and Meditating on the Mysteries","slug":"praying-rosary-meditating-mysteries","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/235851"}},{"articleId":284787,"title":"What Your Society Says About You","slug":"what-your-society-says-about-you","categoryList":["academics-the-arts","humanities"],"_links":{"self":"/articles/284787"}}],"inThisArticle":[{"label":"Referencing Python list items by position","target":"#tab1"},{"label":"Looping through a Python list","target":"#tab2"},{"label":"Seeing whether a Python list contains an item","target":"#tab3"},{"label":"Getting the length of a Python list","target":"#tab4"},{"label":"Appending an item to the end of a Python list","target":"#tab5"},{"label":"Inserting an item into a Python list","target":"#tab6"},{"label":"Changing an item in a Python list","target":"#tab7"},{"label":"Combining Python lists","target":"#tab8"},{"label":"Removing Python list items","target":"#tab9"},{"label":"Clearing out a Python list","target":"#tab10"},{"label":"Counting how many times an item appears in a Python list","target":"#tab11"},{"label":"Finding a Python list item's index","target":"#tab12"},{"label":"Alphabetizing and sorting Python lists","target":"#tab13"},{"label":"Reversing a Python list","target":"#tab14"},{"label":"Copying a Python list","target":"#tab15"}],"relatedArticles":{"fromBook":[{"articleId":264911,"title":"How to Use Lambda Functions in Python","slug":"how-to-use-lambda-functions-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264911"}},{"articleId":264906,"title":"Your Guide to the Python Standard Library","slug":"your-guide-to-the-python-standard-library","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264906"}},{"articleId":264894,"title":"A Beginner’s Guide to Python Versions","slug":"a-beginners-guide-to-python-versions","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264894"}},{"articleId":264888,"title":"How to Build a Simple Neural Network in Python","slug":"how-to-build-a-simple-neural-network-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264888"}},{"articleId":264872,"title":"The Raspberry Pi: The Perfect PC Platform for Python","slug":"the-raspberry-pi-the-perfect-platform-for-physical-computing-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264872"}}],"fromCategory":[{"articleId":264911,"title":"How to Use Lambda Functions in Python","slug":"how-to-use-lambda-functions-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264911"}},{"articleId":264906,"title":"Your Guide to the Python Standard Library","slug":"your-guide-to-the-python-standard-library","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264906"}},{"articleId":264894,"title":"A Beginner’s Guide to Python Versions","slug":"a-beginners-guide-to-python-versions","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264894"}},{"articleId":264888,"title":"How to Build a Simple Neural Network in Python","slug":"how-to-build-a-simple-neural-network-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264888"}},{"articleId":264872,"title":"The Raspberry Pi: The Perfect PC Platform for Python","slug":"the-raspberry-pi-the-perfect-platform-for-physical-computing-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264872"}}]},"hasRelatedBookFromSearch":false,"relatedBook":{"bookId":281833,"slug":"python-all-in-one-for-dummies","isbn":"9781394236152","categoryList":["technology","programming-web-design","python"],"amazon":{"default":"https://www.amazon.com/gp/product/1394236158/ref=as_li_tl?ie=UTF8&tag=wiley01-20","ca":"https://www.amazon.ca/gp/product/1394236158/ref=as_li_tl?ie=UTF8&tag=wiley01-20","indigo_ca":"http://www.tkqlhce.com/click-9208661-13710633?url=https://www.chapters.indigo.ca/en-ca/books/product/1394236158-item.html&cjsku=978111945484","gb":"https://www.amazon.co.uk/gp/product/1394236158/ref=as_li_tl?ie=UTF8&tag=wiley01-20","de":"https://www.amazon.de/gp/product/1394236158/ref=as_li_tl?ie=UTF8&tag=wiley01-20"},"image":{"src":"https://www.dummies.com/wp-content/uploads/python-all-in-one-for-dummies-cover-9781394236152-203x255.jpg","width":203,"height":255},"title":"Python All-in-One For Dummies","testBankPinActivationLink":"","bookOutOfPrint":true,"authorsInfo":"","authors":[{"authorId":35406,"name":"John C. Shovic","slug":"john-c-shovic","description":" <p> <b>John C. Shovic, PhD,</b> is a computer science faculty member specializing in robotics and artificial intelligence at the University of Idaho. <p><b>Alan Simpson</b> is a web development professional and prolific tech author with more than 100 publications to his credit. ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/35406"}},{"authorId":10199,"name":"Alan Simpson","slug":"alan-simpson","description":" <p> <b>John C. Shovic, PhD,</b> is a computer science faculty member specializing in robotics and artificial intelligence at the University of Idaho. <p><b>Alan Simpson</b> is a web development professional and prolific tech author with more than 100 publications to his credit. ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/10199"}},{"authorId":35433,"name":"","slug":"","description":" <p><b>Dr. Jill Schiefelbein</b> taught business communication at Arizona State University for 11 years before venturing into entrepreneurship. Jill’s business, The Dynamic Communicator<sup>®</sup>, helps organizations attract customers, increase sales, and retain clients. She is the author of <i>Dynamic Communication: 27 Strategies to Grow, Lead, and Manage Your Business.</i> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/35433"}}],"_links":{"self":"https://dummies-api.dummies.com/v2/books/"}},"collections":[],"articleAds":{"footerAd":"<div class=\"du-ad-region row\" id=\"article_page_adhesion_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_adhesion_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;python&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781394236152&quot;]}]\" id=\"du-slot-671ffba74cdb6\"></div></div>","rightAd":"<div class=\"du-ad-region row\" id=\"article_page_right_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_right_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;python&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781394236152&quot;]}]\" id=\"du-slot-671ffba74d873\"></div></div>"},"articleType":{"articleType":"Articles","articleList":null,"content":null,"videoInfo":{"videoId":null,"name":null,"accountId":null,"playerId":null,"thumbnailUrl":null,"description":null,"uploadDate":null}},"sponsorship":{"sponsorshipPage":false,"backgroundImage":{"src":null,"width":0,"height":0},"brandingLine":"","brandingLink":"","brandingLogo":{"src":null,"width":0,"height":0},"sponsorAd":"","sponsorEbookTitle":"","sponsorEbookLink":"","sponsorEbookImage":{"src":null,"width":0,"height":0}},"primaryLearningPath":"Advance","lifeExpectancy":"Two years","lifeExpectancySetFrom":"2024-10-28T00:00:00+00:00","dummiesForKids":"no","sponsoredContent":"no","adInfo":"","adPairKey":[]},"status":"publish","visibility":"public","articleId":264919},{"headers":{"creationTime":"2019-05-15T17:19:50+00:00","modifiedTime":"2024-04-12T14:02:57+00:00","timestamp":"2024-04-12T15:01:11+00:00"},"data":{"breadcrumbs":[{"name":"Technology","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33512"},"slug":"technology","categoryId":33512},{"name":"Programming & Web Design","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33592"},"slug":"programming-web-design","categoryId":33592},{"name":"Python","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33606"},"slug":"python","categoryId":33606}],"title":"Python All-in-One For Dummies Cheat Sheet","strippedTitle":"python all-in-one for dummies cheat sheet","slug":"python-all-in-one-for-dummies-cheat-sheet","canonicalUrl":"","seo":{"metaDescription":"Learn about Python operators, Python data types, and Python functions, which are all important parts of this flexible programming language.","noIndex":0,"noFollow":0},"content":"Python is a flexible programming language that has become increasingly popular in the past few years. This cheat sheet is designed to give you a handy resource for common Python data types, Python operators, and Python functions. It includes Python data types, operators, special characters, f-strings, and functions for working with robots.","description":"Python is a flexible programming language that has become increasingly popular in the past few years. This cheat sheet is designed to give you a handy resource for common Python data types, Python operators, and Python functions. It includes Python data types, operators, special characters, f-strings, and functions for working with robots.","blurb":"","authors":[{"authorId":26710,"name":"John Shovic","slug":"john-shovic","description":"John Shovic, PhD, is a computer science faculty member at the University of Idaho specializing in robotics and artificial intelligence.","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/26710"}},{"authorId":10199,"name":"Alan Simpson","slug":"alan-simpson","description":" <p><b>John Shovic, PhD,</b> is a computer science faculty member at the University of Idaho specializing in robotics and artificial intelligence.</p> <p><b>Alan Simpson</b> is a web development professional who has published more than 100 articles and books on technology.</p> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/10199"}}],"primaryCategoryTaxonomy":{"categoryId":33606,"title":"Python","slug":"python","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33606"}},"secondaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"tertiaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"trendingArticles":[{"articleId":192609,"title":"How to Pray the Rosary: A Comprehensive Guide","slug":"how-to-pray-the-rosary","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/192609"}},{"articleId":208741,"title":"Kabbalah For Dummies Cheat Sheet","slug":"kabbalah-for-dummies-cheat-sheet","categoryList":["body-mind-spirit","religion-spirituality","kabbalah"],"_links":{"self":"/articles/208741"}},{"articleId":230957,"title":"Nikon D3400 For Dummies Cheat Sheet","slug":"nikon-d3400-dummies-cheat-sheet","categoryList":["home-auto-hobbies","photography"],"_links":{"self":"/articles/230957"}},{"articleId":235851,"title":"Praying the Rosary and Meditating on the Mysteries","slug":"praying-rosary-meditating-mysteries","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/235851"}},{"articleId":284787,"title":"What Your Society Says About You","slug":"what-your-society-says-about-you","categoryList":["academics-the-arts","humanities"],"_links":{"self":"/articles/284787"}}],"inThisArticle":[],"relatedArticles":{"fromBook":[{"articleId":264919,"title":"How to Define and Use Python Lists","slug":"how-to-define-and-use-python-lists","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264919"}},{"articleId":264911,"title":"How to Use Lambda Functions in Python","slug":"how-to-use-lambda-functions-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264911"}},{"articleId":264906,"title":"Your Guide to the Python Standard Library","slug":"your-guide-to-the-python-standard-library","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264906"}},{"articleId":264894,"title":"A Beginner’s Guide to Python Versions","slug":"a-beginners-guide-to-python-versions","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264894"}},{"articleId":264888,"title":"How to Build a Simple Neural Network in Python","slug":"how-to-build-a-simple-neural-network-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264888"}}],"fromCategory":[{"articleId":264919,"title":"How to Define and Use Python Lists","slug":"how-to-define-and-use-python-lists","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264919"}},{"articleId":264911,"title":"How to Use Lambda Functions in Python","slug":"how-to-use-lambda-functions-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264911"}},{"articleId":264906,"title":"Your Guide to the Python Standard Library","slug":"your-guide-to-the-python-standard-library","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264906"}},{"articleId":264894,"title":"A Beginner’s Guide to Python Versions","slug":"a-beginners-guide-to-python-versions","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264894"}},{"articleId":264888,"title":"How to Build a Simple Neural Network in Python","slug":"how-to-build-a-simple-neural-network-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264888"}}]},"hasRelatedBookFromSearch":false,"relatedBook":{"bookId":281833,"slug":"python-all-in-one-for-dummies","isbn":"9781394236152","categoryList":["technology","programming-web-design","python"],"amazon":{"default":"https://www.amazon.com/gp/product/1394236158/ref=as_li_tl?ie=UTF8&tag=wiley01-20","ca":"https://www.amazon.ca/gp/product/1394236158/ref=as_li_tl?ie=UTF8&tag=wiley01-20","indigo_ca":"http://www.tkqlhce.com/click-9208661-13710633?url=https://www.chapters.indigo.ca/en-ca/books/product/1394236158-item.html&cjsku=978111945484","gb":"https://www.amazon.co.uk/gp/product/1394236158/ref=as_li_tl?ie=UTF8&tag=wiley01-20","de":"https://www.amazon.de/gp/product/1394236158/ref=as_li_tl?ie=UTF8&tag=wiley01-20"},"image":{"src":"https://www.dummies.com/wp-content/uploads/python-all-in-one-for-dummies-cover-9781394236152-203x255.jpg","width":203,"height":255},"title":"Python All-in-One For Dummies","testBankPinActivationLink":"","bookOutOfPrint":true,"authorsInfo":"","authors":[{"authorId":34775,"name":"John C. Shovic","slug":"john-c-shovic","description":" <p><b>John Shovic, PhD,</b> is a computer science faculty member at the University of Idaho specializing in robotics and artificial intelligence.</p> <p><b>Alan Simpson</b> is a web development professional who has published more than 100 articles and books on technology.</p> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/34775"}},{"authorId":10199,"name":"Alan Simpson","slug":"alan-simpson","description":" <p><b>John Shovic, PhD,</b> is a computer science faculty member at the University of Idaho specializing in robotics and artificial intelligence.</p> <p><b>Alan Simpson</b> is a web development professional who has published more than 100 articles and books on technology.</p> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/10199"}},{"authorId":34784,"name":"","slug":"","description":" <p><b>John Shovic, PhD,</b> is a computer science faculty member at the University of Idaho specializing in robotics and artificial intelligence.</p> <p><b>Alan Simpson</b> is a web development professional who has published more than 100 articles and books on technology.</p> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/34784"}}],"_links":{"self":"https://dummies-api.dummies.com/v2/books/"}},"collections":[{"title":"Pondering the Pi Possibilities","slug":"pondering-the-pi-possibilities","collectionId":297524}],"articleAds":{"footerAd":"<div class=\"du-ad-region row\" id=\"article_page_adhesion_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_adhesion_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;python&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781394236152&quot;]}]\" id=\"du-slot-66194cb7ec247\"></div></div>","rightAd":"<div class=\"du-ad-region row\" id=\"article_page_right_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_right_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;python&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781394236152&quot;]}]\" id=\"du-slot-66194cb7ecae6\"></div></div>"},"articleType":{"articleType":"Cheat Sheet","articleList":[{"articleId":261606,"title":"Python Data Types","slug":"","categoryList":[],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/261606"}},{"articleId":261610,"title":"Python Operators and Special Characters","slug":"","categoryList":[],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/261610"}},{"articleId":261613,"title":"Python Functions for Working with Robots","slug":"","categoryList":[],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/261613"}}],"content":[{"title":"Python data types","thumb":null,"image":null,"content":"<p>Python, like all programming languages, uses data types to classify types of information. The specific data type you use determines the values you can assign to it, how you can store it, and what you can do to it (including the operations you can perform on it).</p>\n<div class=\"figure-container\"><figure id=\"attachment_261607\" aria-labelledby=\"figcaption_attachment_261607\" class=\"wp-caption alignnone\" style=\"width: 545px\"><img loading=\"lazy\" class=\"size-full wp-image-261607\" src=\"https://www.dummies.com/wp-content/uploads/Python-3D.jpg\" alt=\"Python-3D\" width=\"535\" height=\"357\" /><figcaption id=\"figcaption_attachment_261607\" class=\"wp-caption-text\">Source: ©supimol kumying / Shutterstock</figcaption></figure></div><div class=\"clearfix\"></div>\n<p>You deal with written information all the time and probably don’t think about the difference between numbers and text (that is, letters and words). But there’s a big difference between numbers and text in a computer because with numbers, you can do arithmetic (add, subtract, multiple, divide). For example, everybody knows that 1+1 = 2. The same doesn’t apply to letters and words. The expression A+A doesn’t necessary equal B or AA or anything else because unlike numbers, letters and words aren’t quantities. You can buy <em>12 apples</em> at the store, because 12 is a quantity, a number — a <em>scalar value</em> in programming jargon. You can’t really buy a <em>snorkel apples</em> because a snorkel is a thing, it’s not a quantity, number, or scalar value.</p>\n<p>Strings are sort of the opposite of numbers. With numbers, you can add, subtract, multiply, and divide because the numbers represent quantities. Strings are for just about everything else. Names, addresses, and all other kinds of text you see every day would be a <em>string</em> in Python (and for computers in general). It’s called a <em>string</em> because it’s a string of characters (letters, spaces, punctuation marks, maybe some numbers). To us, a string usually has some meaning, like a person’s name or address, but computers don’t have eyes to see with or brains to think with or any awareness that humans even exist, so if it’s not something on which you can do arithmetic, it’s just a string of characters.</p>\n<p>The following list shows the seven most common Python data types:</p>\n<ul>\n<li><strong><code>integer</code>:</strong> These are whole numbers, positive or negative (including 0). Example: <code>100</code>.</li>\n<li><strong><code>float</code>:</strong> Floating-point numbers are real numbers, rational or irrational. In most cases, this means numbers with decimal fractions. Example: <code>123.45</code>.</li>\n<li><strong><code>string</code>:</strong> Strings are sequences of characters, or text, enclosed in quotes. Example: <code>\"any text\"</code>.</li>\n<li><strong><code>boolean</code>:</strong> Can be one of two values, true or false. Example: <code>True </code>or <code>False</code>.</li>\n<li><strong><code>list</code>:</strong> An ordered sequence of elements. With a list, the order of the elements can be changed. Example: [<em><code>value1</code></em>, <em><code>value2</code></em>, &#8230; ].</li>\n<li><strong><code>tuple</code>:</strong> An unchangeable ordered sequence of elements. Example: (<em><code>value1</code></em>, <em><code>value2</code></em>, &#8230;).</li>\n<li><strong><code>dictionary</code>:</strong> This is Python’s mapping data type. Dictionaries map keys to values as a means of storing information. Example: {<em><code>key1</code></em>:<em>value1</em>, <em><code>key2</code></em>:<em>value2</em>, &#8230;}.</li>\n</ul>\n"},{"title":"Python operators and special characters","thumb":null,"image":null,"content":"<p>With Python and for computers in general it helps to think of information as being one of the following data types: number, string, or Boolean. You also use computers to <em>operate</em> on that information, meaning to do any necessary math or comparisons or searches or whatever to help you find information and organize it in a way that makes sense to you.</p>\n<p>Python offers many <a href=\"https://dummies-wp-admin.dummies.com/programming/python/beginning-programming-python-dummies-cheat-sheet/\">different operators</a> and special characters for working with and comparing types of information. Here we just summarize them all for future reference, without going into great detail.</p>\n<h2>Special Characters</h2>\n<table>\n<tbody>\n<tr>\n<td width=\"266\"><strong><code>#</code></strong></td>\n<td width=\"266\">comment</td>\n</tr>\n<tr>\n<td width=\"266\"><strong><code>\"\"\"</code></strong></td>\n<td width=\"266\">string literal</td>\n</tr>\n<tr>\n<td width=\"266\"><strong><code>\\n</code></strong></td>\n<td width=\"266\">new line</td>\n</tr>\n<tr>\n<td width=\"266\"><strong><code>\\<em>char</em></code></strong></td>\n<td width=\"266\">escape character</td>\n</tr>\n</tbody>\n</table>\n<h2>Numeric Operators (in Order of Precedence)</h2>\n<table>\n<tbody>\n<tr>\n<td width=\"266\"><strong><code>()</code></strong></td>\n<td width=\"266\">grouping</td>\n</tr>\n<tr>\n<td width=\"266\"><strong><code>**</code></strong></td>\n<td width=\"266\">exponent</td>\n</tr>\n<tr>\n<td width=\"266\"><strong><code>–</code></strong></td>\n<td width=\"266\">negation</td>\n</tr>\n<tr>\n<td width=\"266\"><strong><code>*</code></strong></td>\n<td width=\"266\">multiplication</td>\n</tr>\n<tr>\n<td width=\"266\"><strong><code>/</code></strong></td>\n<td width=\"266\">division</td>\n</tr>\n<tr>\n<td width=\"266\"><strong><code>%</code></strong></td>\n<td width=\"266\">modulus</td>\n</tr>\n<tr>\n<td width=\"266\"><strong><code>//</code></strong></td>\n<td width=\"266\">floor division</td>\n</tr>\n<tr>\n<td width=\"266\"><strong><code>+</code></strong></td>\n<td width=\"266\">addition</td>\n</tr>\n<tr>\n<td width=\"266\"><strong><code>–</code></strong></td>\n<td width=\"266\">subtraction</td>\n</tr>\n</tbody>\n</table>\n<h2>Comparison Operators</h2>\n<table>\n<tbody>\n<tr>\n<td width=\"266\"><strong><code>==</code></strong></td>\n<td width=\"266\">equal</td>\n</tr>\n<tr>\n<td width=\"266\"><strong><code>!=</code></strong></td>\n<td width=\"266\">not equal</td>\n</tr>\n<tr>\n<td width=\"266\"><strong><code>&gt; </code></strong></td>\n<td width=\"266\">greater than</td>\n</tr>\n<tr>\n<td width=\"266\"><strong><code>&lt; </code></strong></td>\n<td width=\"266\">less than</td>\n</tr>\n<tr>\n<td width=\"266\"><strong><code>&gt;=</code></strong></td>\n<td width=\"266\">greater than or equal to</td>\n</tr>\n<tr>\n<td width=\"266\"><strong><code>&lt;=</code></strong></td>\n<td width=\"266\">less than or equal to</td>\n</tr>\n<tr>\n<td width=\"266\"><strong><code>and</code></strong></td>\n<td width=\"266\">logical and</td>\n</tr>\n<tr>\n<td width=\"266\"><strong><code>or</code></strong></td>\n<td width=\"266\">logical or</td>\n</tr>\n<tr>\n<td width=\"266\"><strong><code>not</code></strong></td>\n<td width=\"266\">logical not</td>\n</tr>\n</tbody>\n</table>\n<h2>f strings</h2>\n<table>\n<tbody>\n<tr>\n<td width=\"266\"><strong><em><code>number</code></em></strong></td>\n<td width=\"266\">width</td>\n</tr>\n<tr>\n<td width=\"266\"><strong><code>.2f</code></strong></td>\n<td width=\"266\">1234.56</td>\n</tr>\n<tr>\n<td width=\"266\"><strong><code>,.2f</code></strong></td>\n<td width=\"266\">1,234,56</td>\n</tr>\n<tr>\n<td width=\"266\"><strong><code>.1%</code></strong></td>\n<td width=\"266\">6.5%</td>\n</tr>\n<tr>\n<td width=\"266\"><strong><code>:</code></strong></td>\n<td width=\"266\">align left</td>\n</tr>\n<tr>\n<td width=\"266\"><code>^</code></td>\n<td width=\"266\">center</td>\n</tr>\n</tbody>\n</table>\n<p>&nbsp;</p>\n"},{"title":"Python functions for working robots","thumb":null,"image":null,"content":"<p>The basic components of robots can be controlled with Python functions and can work together to accomplish robotic tasks. One way to do so is through the use of a python class file called <code>RobotInterface.py</code>. Here is a list of the functions that are defined in the <code>RobotInterface.py</code> library:</p>\n<ul>\n<li><strong>Utilities</strong></li>\n</ul>\n<p style=\"padding-left: 30px;\"><code>Color( red, green, blue, white = 0)</code></p>\n<p style=\"padding-left: 30px;\">Converts the provided red, green, blue color to a 24-bit color value. Each color component should be a value 0–255, where 0 is the lowest intensity and 255 is the highest intensity.</p>\n<p style=\"padding-left: 30px;\"><code>allLEDSOff()</code></p>\n<p style=\"padding-left: 30px;\">Turns all the LEDs off on the robot.</p>\n<p style=\"padding-left: 30px;\"><code>centerAllServos()</code></p>\n<p style=\"padding-left: 30px;\">Moves all servos to their center position.</p>\n<ul>\n<li><strong>Front LEDs</strong></li>\n</ul>\n<p style=\"padding-left: 30px;\"><code>set_Front_LED_On(colorLED)</code></p>\n<p style=\"padding-left: 30px;\">One of these constants: <code>RobotInterface.left_R</code>, <code>RobotInterface.left_G</code>, <code>RobotInterface.left_B</code>, <code>RobotInterface.right_R</code>, <code>RobotInterface.right_G</code>, <code>RobotInterface.right_B</code>.</p>\n<p style=\"padding-left: 30px;\"><code>set_Front_LED_Off(colorLED)</code></p>\n<p style=\"padding-left: 30px;\">One of these constants: <code>RobotInterface.left_R</code>, <code>RobotInterface.left_G</code>, <code>RobotInterface.left_B</code>, <code>RobotInterface.right_R</code>, <code>RobotInterface.right_G</code>, <code>RobotInterface.right_B</code>.</p>\n<ul>\n<li><strong>Strip LEDs</strong></li>\n</ul>\n<p style=\"padding-left: 30px;\"><code>rainbowCycle( wait_ms = 20, iterations = 3)</code></p>\n<p style=\"padding-left: 30px;\">Cycles the Pixel LEDs through the rainbow for at least three iterations.</p>\n<p style=\"padding-left: 30px;\"><code>colorWipe</code>( color)</p>\n<p style=\"padding-left: 30px;\">Changes all the Pixel LEDs to the same color.</p>\n<p style=\"padding-left: 30px;\"><code>setPixelColor( pixel, color, brightness)</code></p>\n<p style=\"padding-left: 30px;\">Sets an individual Pixel to a specific color; brightness is for the whole string.</p>\n<ul>\n<li><strong>Ultrasonic Sensor</strong></li>\n</ul>\n<p style=\"padding-left: 30px;\"><code>fetchUltraDistance()</code></p>\n<p style=\"padding-left: 30px;\">Returns the distance in front of the sensor in centimeters (cm).</p>\n<p style=\"padding-left: 30px;\"><code>motorForward( speed, delay)</code></p>\n<p style=\"padding-left: 30px;\">Moves the robot forward at <code>speed</code> (0–100) for <code>delay</code> seconds.</p>\n<p style=\"padding-left: 30px;\"><code>motorBackward( speed, delay)</code></p>\n<p style=\"padding-left: 30px;\">Moves the robot backwards at <code>speed</code> (0–100) for <code>delay</code> seconds.</p>\n<p style=\"padding-left: 30px;\"><code>stopMotor()</code></p>\n<p style=\"padding-left: 30px;\">Immediately stops the drive motor.</p>\n<ul>\n<li><strong>Head Turn Servo</strong></li>\n</ul>\n<p style=\"padding-left: 30px;\"><code>headTurnLeft()</code></p>\n<p style=\"padding-left: 30px;\">Turns head all the way left.</p>\n<p style=\"padding-left: 30px;\"><code>headTurnRight()</code></p>\n<p style=\"padding-left: 30px;\">Turns head all the way right.</p>\n<p style=\"padding-left: 30px;\"><code>headTurnMiddle()</code></p>\n<p style=\"padding-left: 30px;\">Turns the head to the middle.</p>\n<p style=\"padding-left: 30px;\"><code>headTurnPercent( percent)</code></p>\n<p style=\"padding-left: 30px;\">Turns the head as a percent 0–100, where 0 is all the way left and 100 is all the way right.</p>\n<ul>\n<li><strong>Head Tilt Servo</strong></li>\n</ul>\n<p style=\"padding-left: 30px;\"><code>headTiltDown()</code></p>\n<p style=\"padding-left: 30px;\">Tilts the head all the way down.</p>\n<p style=\"padding-left: 30px;\"><code>headTiltUp()</code></p>\n<p style=\"padding-left: 30px;\">Tilts the head all the way up.</p>\n<p style=\"padding-left: 30px;\"><code>headTiltMiddle()</code></p>\n<p style=\"padding-left: 30px;\">Tilts the head to the middle.</p>\n<p style=\"padding-left: 30px;\"><code>headTiltPercent( percent)</code></p>\n<p style=\"padding-left: 30px;\">Tilts the head as a percent 0–100, where 0 is all the way up and 100 is all the way down.</p>\n<ul>\n<li><strong>Front Wheel Servo</strong></li>\n</ul>\n<p style=\"padding-left: 30px;\"><code>wheelsLeft()</code></p>\n<p style=\"padding-left: 30px;\">Turns the wheels all the way to the left.</p>\n<p style=\"padding-left: 30px;\"><code>wheelsRight()</code></p>\n<p style=\"padding-left: 30px;\">Turns the wheels all the way to the right.</p>\n<p style=\"padding-left: 30px;\"><code>wheelsMiddle()</code></p>\n<p style=\"padding-left: 30px;\">Turns the wheels to the middle.</p>\n<p style=\"padding-left: 30px;\"><code>wheelsPercent(percent)</code></p>\n<p style=\"padding-left: 30px;\">Turns the wheels as a percent 0–100, where 0 is all the way left and 100 is all the way right.</p>\n"}],"videoInfo":{"videoId":null,"name":null,"accountId":null,"playerId":null,"thumbnailUrl":null,"description":null,"uploadDate":null}},"sponsorship":{"sponsorshipPage":false,"backgroundImage":{"src":null,"width":0,"height":0},"brandingLine":"","brandingLink":"","brandingLogo":{"src":null,"width":0,"height":0},"sponsorAd":"","sponsorEbookTitle":"","sponsorEbookLink":"","sponsorEbookImage":{"src":null,"width":0,"height":0}},"primaryLearningPath":"Advance","lifeExpectancy":"One year","lifeExpectancySetFrom":"2024-04-12T00:00:00+00:00","dummiesForKids":"no","sponsoredContent":"no","adInfo":"","adPairKey":[]},"status":"publish","visibility":"public","articleId":261616},{"headers":{"creationTime":"2016-03-26T07:30:05+00:00","modifiedTime":"2023-10-04T12:49:14+00:00","timestamp":"2023-10-04T15:01:02+00:00"},"data":{"breadcrumbs":[{"name":"Technology","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33512"},"slug":"technology","categoryId":33512},{"name":"Programming & Web Design","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33592"},"slug":"programming-web-design","categoryId":33592},{"name":"Python","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33606"},"slug":"python","categoryId":33606}],"title":"Python 2.7 Keyword Subset and Examples","strippedTitle":"python 2.7 keyword subset and examples","slug":"python-2-7-keyword-subset-and-examples","canonicalUrl":"","seo":{"metaDescription":"Programming is an important skill. Python will serve you well for years to come. The tables here give you the core words, built-ins, standard library functions,","noIndex":0,"noFollow":0},"content":"<p>Programming is an important skill. Python will serve you well for years to come. The tables here give you the core words, built-ins, standard library functions, and operators that you'll use most when you're coding with Python.</p>\r\n<h2 id=\"tab1\" >Python Core Words</h2>\r\n<table>\r\n<tbody>\r\n<tr>\r\n<th>Keyword</th><th>Summary</th><th>Example</th>\r\n</tr>\r\n<tr>\r\n<td>and</td>\r\n<td>Logical operator to test whether two things are both <span class=\"code\">True</span>.</td>\r\n<td><span class=\"code\"><em><conditional expression> </em><span style=\"font-family: Verdana;\">and</span></span><br /><span class=\"code\"><em><conditional expression></em></span><br /><span class=\"code\">x>2 and x<10</span></td>\r\n</tr>\r\n<tr>\r\n<td>as</td>\r\n<td>Assign a file object to a variable. Used with <span class=\"code\">with</span>.<br />Let your code refer to a module under a different name (also called an <em>alias</em>). Used with <span class=\"code\">import</span>.</td>\r\n<td><span class=\"code\">with open(<</span><span class=\"code\"><em>name of file</em></span><span class=\"code\">>,<</span><span class=\"code\"><em>file mode</em></span><span class=\"code\">>) as <</span><span class=\"code\"><em>object name</em></span><span class=\"code\">>:</span><span class=\"code\"><br /></span><span class=\"code\">import cPickle as pickle</span></td>\r\n</tr>\r\n<tr>\r\n<td>break</td>\r\n<td>Stop execution of a loop.</td>\r\n<td><span class=\"code\">for i in range(10):</span><br /><span class=\"code\"> if i%2 ==0:</span><br /><span class=\"code\"> break</span></td>\r\n</tr>\r\n<tr>\r\n<td>class</td>\r\n<td>Define a custom object.</td>\r\n<td><span class=\"code\">class <</span><span class=\"code\"><em>name of class</em></span><span class=\"code\">>(object):</span><span class=\"code\"><br /></span><span class=\"code\"> \"\"<em>Your docstring</em>\"\"</span> <br /><span class=\"code\">class MyClass(object):</span><span class=\"code\"><br /></span><span class=\"code\"> \"\"A cool function.\"\"</span><br /></td>\r\n</tr>\r\n<tr>\r\n<td>continue</td>\r\n<td>Skip balance of loop and begin a new iteration.</td>\r\n<td><span class=\"code\">for i in range(10):</span><br /><span class=\"code\"> if i%2 ==0:</span><br /><span class=\"code\"> continue</span></td>\r\n</tr>\r\n<tr>\r\n<td>def</td>\r\n<td>Define a function.</td>\r\n<td><span class=\"code\">def <</span><span class=\"code\"><em>name of function</em></span><span class=\"code\">>(<argument list>):</span><span class=\"code\"><br /></span><span class=\"code\"> \"\"<em>Your docstring</em>\"\"</span> <span class=\"code\"><br /></span><span class=\"code\">def my_function():</span><span class=\"code\"><br /></span><span class=\"code\"> \"\"This does... \"\"</span></td>\r\n</tr>\r\n<tr>\r\n<td>elif</td>\r\n<td>Add conditional test to an <span class=\"code\">if</span> clause.</td>\r\n<td>See <span class=\"code\">if</span>.</td>\r\n</tr>\r\n<tr>\r\n<td>else</td>\r\n<td>Add an alternative code block.</td>\r\n<td>See <span class=\"code\">if</span>.</td>\r\n</tr>\r\n<tr>\r\n<td>for</td>\r\n<td>Create a loop which iterates through elements of a list (or other iterable).</td>\r\n<td><span class=\"code\">for <</span><span class=\"code\"><em>dummy variable name</em></span><span class=\"code\">> in <</span><span class=\"code\"><em>sequence</em></span><span class=\"code\">>:</span><span class=\"code\"><br /></span><span class=\"code\">for i in range(10):</span></td>\r\n</tr>\r\n<tr>\r\n<td>from</td>\r\n<td>Import specific functions from a module without importing the whole module.</td>\r\n<td><span class=\"code\">from <</span><span class=\"code\"><em>module name</em></span><span class=\"code\">> import <</span><span class=\"code\"><em>name of function or object</em></span><span class=\"code\">></span><span class=\"code\"><br /></span><span class=\"code\">from random import randint</span></td>\r\n</tr>\r\n<tr>\r\n<td>global</td>\r\n<td>Make a variable global in scope. (If a variable is defined in the main section, you can change its value within a function.)</td>\r\n<td><span class=\"code\">global x</span></td>\r\n</tr>\r\n<tr>\r\n<td>if</td>\r\n<td>Create a condition. If the condition is <span class=\"code\">True</span>, the associated code block is executed. Otherwise, any <span class=\"code\">elif</span> commands are processed. If there are none, or none are satisfied, execute the <span class=\"code\">else</span> block if there is one.</td>\r\n<td><span class=\"code\">if <em><conditional expression></em>:</span><br /><span class=\"code\"><em> <code block></em></span><br /><span class=\"code\">[elif <conditional expression>:</span><br /><span class=\"code\"> <code block>, ...]</span><br /><span class=\"code\">[else:</span><br /><span class=\"code\"> <code block>]</span><br /><span class=\"code\">if x == 1:</span><br /><span class=\"code\"> print(\"x is 1\")</span><br /><span class=\"code\">elif x == 2:</span><br /><span class=\"code\"> print(\"x is 2\")</span><br /><span class=\"code\">elif x > 3:</span><br /><span class=\"code\"> print(\"x is greater than 3\")</span><br /><span class=\"code\">else</span><br /><span class=\"code\"> print(\"x is not greater than 3, nor is it 1 one or 2\")</span></td>\r\n</tr>\r\n<tr>\r\n<td>import</td>\r\n<td>Use code defined in another file without retyping it.</td>\r\n<td><span class=\"code\">import <</span><span class=\"code\"><em>name of module</em></span><span class=\"code\">></span><span class=\"code\"><br /></span><span class=\"code\">import random</span></td>\r\n</tr>\r\n<tr>\r\n<td>in</td>\r\n<td>Used to test whether a given value is one of the elements of an object.</td>\r\n<td><span class=\"code\">1 in range(10)</span></td>\r\n</tr>\r\n<tr>\r\n<td>is</td>\r\n<td>Used to test whether names reference the same object.</td>\r\n<td><span class=\"code\">x = None</span><br /><span class=\"code\">x is None # faster than</span><br /><span class=\"code\">x == None</span></td>\r\n</tr>\r\n<tr>\r\n<td>lambda</td>\r\n<td>Shorthand function definition. Usually used where a function needs to be passed as an argument to another function.</td>\r\n<td><span class=\"code\">lamda <em><dummy variables></em>:</span><br /><span class=\"code\"><em><expression using dummy variables></em></span><br /><span class=\"code\">times = lambda x, y: x*y</span><br /><span class=\"code\">command=lambda x: self.draw_line(self.control_points)</span></td>\r\n</tr>\r\n<tr>\r\n<td>not</td>\r\n<td>Logical negation, used to negate a logical condition. Don't use for testing greater than, less than, or equal.</td>\r\n<td><span class=\"code\">10 not in range(10)</span></td>\r\n</tr>\r\n<tr>\r\n<td>or</td>\r\n<td>Logical operator to test whether at least one of two things is <span class=\"code\">True</span>.</td>\r\n<td><span class=\"code\"><em><conditional expression></em> <span style=\"font-family: Verdana;\">or</span></span><br /><span class=\"code\"><em><conditional expression></em></span><br /><span class=\"code\">x<2 or x>10</span></td>\r\n</tr>\r\n<tr>\r\n<td>pass</td>\r\n<td>Placeholder keyword. Does nothing but stop Python complaining that a code block is empty.</td>\r\n<td><span class=\"code\">for i in range (10):</span><span class=\"code\"><br /></span><span class=\"code\"> pass</span></td>\r\n</tr>\r\n<tr>\r\n<td>print</td>\r\n<td>Output text to a terminal.</td>\r\n<td><span class=\"code\">print(</span><span class=\"code\">\"</span><span class=\"code\">Hello World!</span><span class=\"code\">\"</span><span class=\"code\">)</span></td>\r\n</tr>\r\n<tr>\r\n<td>return</td>\r\n<td>Return from the execution of a function. If a value is specified, return that value, otherwise return <span class=\"code\">None</span>.</td>\r\n<td><span class=\"code\">return <value or expression></span><span class=\"code\"><br /></span><span class=\"code\">return x+2</span></td>\r\n</tr>\r\n<tr>\r\n<td>while</td>\r\n<td>Execute a code block while the associated condition is <span class=\"code\">True</span>.</td>\r\n<td><span class=\"code\">while <conditional expression>:</span><br /><span class=\"code\">while True:</span><br /><span class=\"code\"> pass</span></td>\r\n</tr>\r\n<tr>\r\n<td>with</td>\r\n<td>Get Python to manage a resource (like a file) for you.</td>\r\n<td><span class=\"code\">with open(<name of file>,<file mode>) as <object name>:</span></td>\r\n</tr>\r\n</tbody>\r\n</table>\r\n<p>Extend Python's core functionality with these built-ins.</p>\r\n<table border=\"0\">\r\n<caption>Python Built-ins </caption>\r\n<tbody>\r\n<tr>\r\n<th>Built-in</th><th>Notes</th><th>Example</th>\r\n</tr>\r\n<tr>\r\n<td>False</td>\r\n<td>Value, returned by a logical operation or directly assigned.</td>\r\n<td><span class=\"code\">ok_to_continue = False</span><br /><span class=\"code\">age = 16</span><br /><span class=\"code\">old_enough = age >=21</span><br />(evaluates comparison <span class=\"code\">age>=21</span> <br />and assigns the result to <span class=\"code\">old_enough)</span></td>\r\n</tr>\r\n<tr>\r\n<td>None</td>\r\n<td>Value used when representing the absence of a value or to initialise a variable which will be changed later. Returned by functions which do not explicitly return a value.</td>\r\n<td><span class=\"code\">x = None</span></td>\r\n</tr>\r\n<tr>\r\n<td>True</td>\r\n<td>Value, returned by a logical operation.</td>\r\n<td><span class=\"code\">ok_to_continue = True</span><br /><span class=\"code\">age = 16</span><br /><span class=\"code\">old_enough = age >=21</span><br />(evaluates comparison <span class=\"code\">age>=21</span> <br />and assigns the result to <span class=\"code\">old_enough)</span></td>\r\n</tr>\r\n<tr>\r\n<td>__name__</td>\r\n<td>Constant, shows module name. If it's not <span class=\"code\">\"</span><span class=\"code\">__</span><span class=\"code\">main</span><span class=\"code\">__</span><span class=\"code\">\"</span>, the code is being used in an import.</td>\r\n<td><span class=\"code\">if __name__==</span><span class=\"code\">\"</span><span class=\"code\">__main__</span><span class=\"code\">\"</span><span class=\"code\">:</span></td>\r\n</tr>\r\n<tr>\r\n<td>dir</td>\r\n<td>List attributes of an item.</td>\r\n<td><span class=\"code\">dir(<</span><span class=\"code\"><em>object name</em></span><span class=\"code\">>)</span></td>\r\n</tr>\r\n<tr>\r\n<td>enumerate</td>\r\n<td>Iterate through a sequence and number each item.</td>\r\n<td><span class=\"code\">enumerate(</span><span class=\"code\">'</span><span class=\"code\">Hello</span><span class=\"code\">'</span><span class=\"code\">)</span></td>\r\n</tr>\r\n<tr>\r\n<td>exit</td>\r\n<td>Exit Python (Command Line) interpreter.</td>\r\n<td><span class=\"code\">exit()</span></td>\r\n</tr>\r\n<tr>\r\n<td>float</td>\r\n<td>Convert a number into a decimal, usually so that division works properly.</td>\r\n<td><span class=\"code\">1/float(2)</span></td>\r\n</tr>\r\n<tr>\r\n<td>getattr</td>\r\n<td>Get an attribute of an object by a name. Useful for introspection.</td>\r\n<td><span class=\"code\">getattr(<</span><span class=\"code\"><em>name of object</em></span><span class=\"code\">>, <</span><span class=\"code\"><em>name of attribute</em></span><span class=\"code\">>)</span></td>\r\n</tr>\r\n<tr>\r\n<td>help</td>\r\n<td>Get Python docstring on object.</td>\r\n<td><span class=\"code\">help(<</span><span class=\"code\"><em>name of object</em></span><span class=\"code\">>)</span><span class=\"code\"><br /></span><span class=\"code\">help(getattr)</span></td>\r\n</tr>\r\n<tr>\r\n<td>id</td>\r\n<td>Show the location in the computer's RAM where an object is stored.</td>\r\n<td><span class=\"code\">id(<</span><span class=\"code\"><em>name of object</em></span><span class=\"code\">>)</span><span class=\"code\"><br /></span><span class=\"code\">id(help)</span></td>\r\n</tr>\r\n<tr>\r\n<td>int</td>\r\n<td>Convert a string into an integer number.</td>\r\n<td><span class=\"code\">int(</span><span class=\"code\">'</span><span class=\"code\">0</span><span class=\"code\">'</span><span class=\"code\">)</span></td>\r\n</tr>\r\n<tr>\r\n<td>len</td>\r\n<td>Get the number of elements in a sequence.</td>\r\n<td><span class=\"code\">len([0,1])</span></td>\r\n</tr>\r\n<tr>\r\n<td>object</td>\r\n<td>A base on which other classes can inherit from.</td>\r\n<td><span class=\"code\">class CustomObject(object):</span></td>\r\n</tr>\r\n<tr>\r\n<td>open</td>\r\n<td>Open a file on disk, return a file object.</td>\r\n<td><span class=\"code\">open(<path to file>, <mode>)</span><br /><span class=\"code\">open('mydatafile.txt', 'r') # read</span><br />(opens a file to read data from)<br /><span class=\"code\">open('mydatafile.txt', 'w') # write</span><br />(creates a new file to write to, destroys any existing file with the same name)<br /><span class=\"code\">open('mydatafile.txt', 'a') # append</span><br />(adds to an existing file if any, or creates<br />a new one if none existing already)</td>\r\n</tr>\r\n<tr>\r\n<td>print</td>\r\n<td>Reimplementation of <span class=\"code\">print</span> keyword, but as a function.<br />Need to import from the future to use it (srsly!)<br /></td>\r\n<td><span class=\"code\">from future import print_function</span><br /><span class=\"code\">print ('Hello World!</span><span class=\"code\">'</span><span class=\"code\">)</span></td>\r\n</tr>\r\n<tr>\r\n<td>range</td>\r\n<td>Gives numbers between the lower and upper limits specified (including the lower, but excluding the upper limit). A step may be specified.</td>\r\n<td><span class=\"code\">range(10)</span><span class=\"code\"><br /></span><span class=\"code\">range(5,10)</span><span class=\"code\"><br /></span><span class=\"code\">range(1,10,2)</span></td>\r\n</tr>\r\n<tr>\r\n<td>raw_input</td>\r\n<td>Get some text as a string from the user, with an optional prompt.</td>\r\n<td><span class=\"code\">prompt =</span> <span class=\"code\">'</span><span class=\"code\">What is your guess?</span> <span class=\"code\">'</span><span class=\"code\"><br />players_guess = raw_input(prompt)</span></td>\r\n</tr>\r\n<tr>\r\n<td>str</td>\r\n<td>Convert an object (usually a number) into a string (usually for printing).</td>\r\n<td><span class=\"code\">str(0)</span></td>\r\n</tr>\r\n<tr>\r\n<td>type</td>\r\n<td>Give the type of the specified object.</td>\r\n<td><span class=\"code\">type(0)<br />type(</span><span class=\"code\">'</span><span class=\"code\">0</span><span class=\"code\">'</span><span class=\"code\">)<br />type([])<br />type({})<br />type(())</span></td>\r\n</tr>\r\n</tbody>\r\n</table>\r\n<p>Use the work that others have already done. Try these modules from the Python standard library.</p>\r\n<table border=\"0\">\r\n<caption>Selected Functions from the Standard Library </caption>\r\n<tbody>\r\n<tr>\r\n<th>Module</th><th>What It Does</th><th>Sample Functions/Objects</th>\r\n</tr>\r\n<tr>\r\n<td>os.path</td>\r\n<td>Functions relating to files and file paths.</td>\r\n<td><span class=\"code\">os.path.exists(<path to file>)</span></td>\r\n</tr>\r\n<tr>\r\n<td>pickle, cPickle</td>\r\n<td>Save and load objects to/from a file.</td>\r\n<td><span class=\"code\">pickle.load(<file object to load from>),</span> <span class=\"code\">pickle.dump(<object to dump>, <file object to save to>)</span></td>\r\n</tr>\r\n<tr>\r\n<td>random</td>\r\n<td>Various functions relating to random numbers.</td>\r\n<td><span class=\"code\">random.choice(<sequence to choose from>), random.randint(<lower limit>, <upper limit>), random.shuffle(<name of list to shuffle>)</span></td>\r\n</tr>\r\n<tr>\r\n<td>String</td>\r\n<td>Stuff relating to strings.</td>\r\n<td><span class=\"code\">string.printable</span></td>\r\n</tr>\r\n<tr>\r\n<td>sys</td>\r\n<td>Various functions related to your computer system.</td>\r\n<td><span class=\"code\">sys.exit()</span></td>\r\n</tr>\r\n<tr>\r\n<td>Time</td>\r\n<td>Time-related functions.</td>\r\n<td><span class=\"code\">time.time()</span></td>\r\n</tr>\r\n<tr>\r\n<td>Tkinter</td>\r\n<td>User interface widgets and associated constants.</td>\r\n<td><span class=\"code\">Tkinter.ALL</span><br /><span class=\"code\">Tkinter.BOTH</span><br /><span class=\"code\">Tkinter.CENTER</span><br /><span class=\"code\">Tkinter.END</span><br /><span class=\"code\">Tkinter.HORIZONTAL</span><br /><span class=\"code\">Tkinter.LEFT</span><br /><span class=\"code\">Tkinter.NW</span><br /><span class=\"code\">Tkinter.RIGHT</span><br /><span class=\"code\">Tkinter.TOP</span><br /><span class=\"code\">Tkinter.Y</span><br /><span class=\"code\">Tkinter.Button(<parent widget>,</span><br /><span class=\"code\">text=<button text>)</span><br /><span class=\"code\">Tkinter.Canvas(<parent widget>,</span><br /><span class=\"code\"> width=<width>, height=<height>)</span><br /><span class=\"code\">Tkinter.Checkbutton(<parent widget>,</span><br /><span class=\"code\"> text=<checkbutton text>)</span><br /><span class=\"code\">Tkinter.Entry(<parent widget>,</span><br /><span class=\"code\"> width=<number of characters wide>),</span><br /><span class=\"code\">Tkinter.Frame(<parent widget>)</span><br /><span class=\"code\">Tkinter.IntVar()</span><br /><span class=\"code\">Tkinter.Label(<parent widget>,</span><br /><span class=\"code\"> text = <label text>)</span><br /><span class=\"code\">Tkinter.mainloop()</span><br /><span class=\"code\">Tkinter.Menu(<parent widget>)</span><br /><span class=\"code\">Tkinter.OptionMenu(<parent widget>,</span><br /><span class=\"code\"> None, None)</span><br /><span class=\"code\">Tkinter.Scale(<parent widget>,</span><br /><span class=\"code\"> from_=<lower limit>,</span><br /><span class=\"code\"> to=<upper limit>)</span><br /><span class=\"code\">Tkinter.Scrollbar(<parent widget>)</span><br /><span class=\"code\">Tkinter.StringVar()</span><br /><span class=\"code\">Tkinter.Tk()</span><br /></td>\r\n</tr>\r\n</tbody>\r\n</table>\r\n<p>Add, subtract, divide, multiply, and more using these operators.</p>\r\n<table border=\"0\">\r\n<caption>Python Operators </caption>\r\n<tbody>\r\n<tr>\r\n<th>Operator</th><th>Name</th><th>Effect</th><th>Examples</th>\r\n</tr>\r\n<tr>\r\n<td>+</td>\r\n<td>Plus</td>\r\n<td>Add two numbers.<br />Join two strings together.</td>\r\n<td>Add: <span class=\"code\">>>> 1+1</span><span class=\"code\"><br /></span><span class=\"code\">2</span><span class=\"code\"><br /></span>Join: <span class=\"code\">>>></span> <span class=\"code\">'</span><span class=\"code\">a</span><span class=\"code\">'</span><span class=\"code\">+</span><span class=\"code\">'</span><span class=\"code\">b</span><span class=\"code\">'</span><span class=\"code\"><br /></span><span class=\"code\">'</span><span class=\"code\">ab</span><span class=\"code\">'</span></td>\r\n</tr>\r\n<tr>\r\n<td>–</td>\r\n<td>Minus</td>\r\n<td>Subtract a number from another.<br />Can't use for strings.</td>\r\n<td><span class=\"code\">>>> 1-1</span><span class=\"code\"><br /></span><span class=\"code\">0</span></td>\r\n</tr>\r\n<tr>\r\n<td>*</td>\r\n<td>Times</td>\r\n<td>Multiply two numbers.<br />Make copies of a string.</td>\r\n<td>Multiply: <span class=\"code\">>>> 2*2</span><span class=\"code\"><br /></span><span class=\"code\">4</span><span class=\"code\"><br /></span>Copy: <span class=\"code\">>>></span> <span class=\"code\">'</span><span class=\"code\">a</span><span class=\"code\">'</span><span class=\"code\">*2</span><span class=\"code\"><br /></span><span class=\"code\">'</span><span class=\"code\">aa</span><span class=\"code\">'</span></td>\r\n</tr>\r\n<tr>\r\n<td>/</td>\r\n<td>Divide</td>\r\n<td>Divide one number by another.<br />Can't use for strings.</td>\r\n<td>1/2 # integer division:<br />Answer will be rounded down.<br />1/2.0 # decimal division<br />1/float(2) # decimal division<br /></td>\r\n</tr>\r\n<tr>\r\n<td>%</td>\r\n<td>Remainder (Modulo)</td>\r\n<td>Give the remainder when dividing the left number by the right number.<br />Formatting operator for strings.</td>\r\n<td><span class=\"code\">>>> 10%3</span><br /><span class=\"code\">1</span></td>\r\n</tr>\r\n<tr>\r\n<td>**</td>\r\n<td>Power</td>\r\n<td><span class=\"code\">x**y</span> means raise <span class=\"code\">x</span> to the power of <span class=\"code\">y</span>.<br />Can't use for strings.</td>\r\n<td><span class=\"code\">>>> 3**2</span><span class=\"code\"><br /></span><span class=\"code\">9</span></td>\r\n</tr>\r\n<tr>\r\n<td>=</td>\r\n<td>Assignment</td>\r\n<td>Assign the value on the right to the variable on the left.</td>\r\n<td><span class=\"code\">>>> a = 1</span></td>\r\n</tr>\r\n<tr>\r\n<td>==</td>\r\n<td>Equality</td>\r\n<td>Is the left side equal to the right side? Is <span class=\"code\">True</span> if so; is <span class=\"code\">False</span> otherwise.</td>\r\n<td><span class=\"code\">>>> 1 == 1</span><br /><span class=\"code\">True</span><br /><span class=\"code\">>>> 'a' == 'a'</span><br /><span class=\"code\">True</span></td>\r\n</tr>\r\n<tr>\r\n<td>!=</td>\r\n<td>Not equal</td>\r\n<td>Is the left side <em>not</em> equal to the right side? Is <span class=\"code\">True</span> if so; is False otherwise.</td>\r\n<td><span class=\"code\">>>> 1 != 1</span><br /><span class=\"code\">False</span><br /><span class=\"code\">>>> 1 != 2</span><br /><span class=\"code\">True</span><br /><span class=\"code\">>>> 'a' != 'a'</span><br /><span class=\"code\">True</span></td>\r\n</tr>\r\n<tr>\r\n<td>></td>\r\n<td>Greater than</td>\r\n<td>Is the left side greater than the right side?<br /><span class=\"code\">>=</span> means greater than or equal to</td>\r\n<td><span class=\"code\">>>> 2 > 1</span><span class=\"code\"><br /></span><span class=\"code\">True</span></td>\r\n</tr>\r\n<tr>\r\n<td><</td>\r\n<td>Less than</td>\r\n<td>Is the left side less than the right side?<br /><span class=\"code\"><=</span> means less than or equal to</td>\r\n<td><span class=\"code\">>>> 1 < 2</span><span class=\"code\"><br /></span><span class=\"code\">True</span></td>\r\n</tr>\r\n<tr>\r\n<td>& (or and)</td>\r\n<td>And</td>\r\n<td>Are both left and right <span class=\"code\">True</span>?<br />Typically used for complex conditions where you want to do something if everything is <span class=\"code\">True</span>:<br /><span class=\"code\">while im_hungry and you_have_food:</span></td>\r\n<td><span class=\"code\">>>> True & True</span><br /><span class=\"code\">True</span><br /><span class=\"code\">>>> True and False</span><br /><span class=\"code\">False </span><br /><span class=\"code\">>>> True & (1 == 2)</span><br /><span class=\"code\">False</span></td>\r\n</tr>\r\n<tr>\r\n<td>| (or or)</td>\r\n<td>Or</td>\r\n<td>Is either left or right <span class=\"code\">True</span>?<br />Typically used for complex conditions where you want at least one thing to be <span class=\"code\">True</span>:<br /><span class=\"code\">while im_bored or youre_bored:</span></td>\r\n<td><span class=\"code\">>>> True | False</span><br /><span class=\"code\">True</span><br /><span class=\"code\">>>> True or False</span><br /><span class=\"code\">True</span><br /><span class=\"code\">>>> False | False</span><br /><span class=\"code\">False</span><br /><span class=\"code\">>>> (1 == 1) | False</span><br /><span class=\"code\">True</span></td>\r\n</tr>\r\n</tbody>\r\n</table>","description":"<p>Programming is an important skill. Python will serve you well for years to come. The tables here give you the core words, built-ins, standard library functions, and operators that you'll use most when you're coding with Python.</p>\r\n<h2 id=\"tab1\" >Python Core Words</h2>\r\n<table>\r\n<tbody>\r\n<tr>\r\n<th>Keyword</th><th>Summary</th><th>Example</th>\r\n</tr>\r\n<tr>\r\n<td>and</td>\r\n<td>Logical operator to test whether two things are both <span class=\"code\">True</span>.</td>\r\n<td><span class=\"code\"><em><conditional expression> </em><span style=\"font-family: Verdana;\">and</span></span><br /><span class=\"code\"><em><conditional expression></em></span><br /><span class=\"code\">x>2 and x<10</span></td>\r\n</tr>\r\n<tr>\r\n<td>as</td>\r\n<td>Assign a file object to a variable. Used with <span class=\"code\">with</span>.<br />Let your code refer to a module under a different name (also called an <em>alias</em>). Used with <span class=\"code\">import</span>.</td>\r\n<td><span class=\"code\">with open(<</span><span class=\"code\"><em>name of file</em></span><span class=\"code\">>,<</span><span class=\"code\"><em>file mode</em></span><span class=\"code\">>) as <</span><span class=\"code\"><em>object name</em></span><span class=\"code\">>:</span><span class=\"code\"><br /></span><span class=\"code\">import cPickle as pickle</span></td>\r\n</tr>\r\n<tr>\r\n<td>break</td>\r\n<td>Stop execution of a loop.</td>\r\n<td><span class=\"code\">for i in range(10):</span><br /><span class=\"code\"> if i%2 ==0:</span><br /><span class=\"code\"> break</span></td>\r\n</tr>\r\n<tr>\r\n<td>class</td>\r\n<td>Define a custom object.</td>\r\n<td><span class=\"code\">class <</span><span class=\"code\"><em>name of class</em></span><span class=\"code\">>(object):</span><span class=\"code\"><br /></span><span class=\"code\"> \"\"<em>Your docstring</em>\"\"</span> <br /><span class=\"code\">class MyClass(object):</span><span class=\"code\"><br /></span><span class=\"code\"> \"\"A cool function.\"\"</span><br /></td>\r\n</tr>\r\n<tr>\r\n<td>continue</td>\r\n<td>Skip balance of loop and begin a new iteration.</td>\r\n<td><span class=\"code\">for i in range(10):</span><br /><span class=\"code\"> if i%2 ==0:</span><br /><span class=\"code\"> continue</span></td>\r\n</tr>\r\n<tr>\r\n<td>def</td>\r\n<td>Define a function.</td>\r\n<td><span class=\"code\">def <</span><span class=\"code\"><em>name of function</em></span><span class=\"code\">>(<argument list>):</span><span class=\"code\"><br /></span><span class=\"code\"> \"\"<em>Your docstring</em>\"\"</span> <span class=\"code\"><br /></span><span class=\"code\">def my_function():</span><span class=\"code\"><br /></span><span class=\"code\"> \"\"This does... \"\"</span></td>\r\n</tr>\r\n<tr>\r\n<td>elif</td>\r\n<td>Add conditional test to an <span class=\"code\">if</span> clause.</td>\r\n<td>See <span class=\"code\">if</span>.</td>\r\n</tr>\r\n<tr>\r\n<td>else</td>\r\n<td>Add an alternative code block.</td>\r\n<td>See <span class=\"code\">if</span>.</td>\r\n</tr>\r\n<tr>\r\n<td>for</td>\r\n<td>Create a loop which iterates through elements of a list (or other iterable).</td>\r\n<td><span class=\"code\">for <</span><span class=\"code\"><em>dummy variable name</em></span><span class=\"code\">> in <</span><span class=\"code\"><em>sequence</em></span><span class=\"code\">>:</span><span class=\"code\"><br /></span><span class=\"code\">for i in range(10):</span></td>\r\n</tr>\r\n<tr>\r\n<td>from</td>\r\n<td>Import specific functions from a module without importing the whole module.</td>\r\n<td><span class=\"code\">from <</span><span class=\"code\"><em>module name</em></span><span class=\"code\">> import <</span><span class=\"code\"><em>name of function or object</em></span><span class=\"code\">></span><span class=\"code\"><br /></span><span class=\"code\">from random import randint</span></td>\r\n</tr>\r\n<tr>\r\n<td>global</td>\r\n<td>Make a variable global in scope. (If a variable is defined in the main section, you can change its value within a function.)</td>\r\n<td><span class=\"code\">global x</span></td>\r\n</tr>\r\n<tr>\r\n<td>if</td>\r\n<td>Create a condition. If the condition is <span class=\"code\">True</span>, the associated code block is executed. Otherwise, any <span class=\"code\">elif</span> commands are processed. If there are none, or none are satisfied, execute the <span class=\"code\">else</span> block if there is one.</td>\r\n<td><span class=\"code\">if <em><conditional expression></em>:</span><br /><span class=\"code\"><em> <code block></em></span><br /><span class=\"code\">[elif <conditional expression>:</span><br /><span class=\"code\"> <code block>, ...]</span><br /><span class=\"code\">[else:</span><br /><span class=\"code\"> <code block>]</span><br /><span class=\"code\">if x == 1:</span><br /><span class=\"code\"> print(\"x is 1\")</span><br /><span class=\"code\">elif x == 2:</span><br /><span class=\"code\"> print(\"x is 2\")</span><br /><span class=\"code\">elif x > 3:</span><br /><span class=\"code\"> print(\"x is greater than 3\")</span><br /><span class=\"code\">else</span><br /><span class=\"code\"> print(\"x is not greater than 3, nor is it 1 one or 2\")</span></td>\r\n</tr>\r\n<tr>\r\n<td>import</td>\r\n<td>Use code defined in another file without retyping it.</td>\r\n<td><span class=\"code\">import <</span><span class=\"code\"><em>name of module</em></span><span class=\"code\">></span><span class=\"code\"><br /></span><span class=\"code\">import random</span></td>\r\n</tr>\r\n<tr>\r\n<td>in</td>\r\n<td>Used to test whether a given value is one of the elements of an object.</td>\r\n<td><span class=\"code\">1 in range(10)</span></td>\r\n</tr>\r\n<tr>\r\n<td>is</td>\r\n<td>Used to test whether names reference the same object.</td>\r\n<td><span class=\"code\">x = None</span><br /><span class=\"code\">x is None # faster than</span><br /><span class=\"code\">x == None</span></td>\r\n</tr>\r\n<tr>\r\n<td>lambda</td>\r\n<td>Shorthand function definition. Usually used where a function needs to be passed as an argument to another function.</td>\r\n<td><span class=\"code\">lamda <em><dummy variables></em>:</span><br /><span class=\"code\"><em><expression using dummy variables></em></span><br /><span class=\"code\">times = lambda x, y: x*y</span><br /><span class=\"code\">command=lambda x: self.draw_line(self.control_points)</span></td>\r\n</tr>\r\n<tr>\r\n<td>not</td>\r\n<td>Logical negation, used to negate a logical condition. Don't use for testing greater than, less than, or equal.</td>\r\n<td><span class=\"code\">10 not in range(10)</span></td>\r\n</tr>\r\n<tr>\r\n<td>or</td>\r\n<td>Logical operator to test whether at least one of two things is <span class=\"code\">True</span>.</td>\r\n<td><span class=\"code\"><em><conditional expression></em> <span style=\"font-family: Verdana;\">or</span></span><br /><span class=\"code\"><em><conditional expression></em></span><br /><span class=\"code\">x<2 or x>10</span></td>\r\n</tr>\r\n<tr>\r\n<td>pass</td>\r\n<td>Placeholder keyword. Does nothing but stop Python complaining that a code block is empty.</td>\r\n<td><span class=\"code\">for i in range (10):</span><span class=\"code\"><br /></span><span class=\"code\"> pass</span></td>\r\n</tr>\r\n<tr>\r\n<td>print</td>\r\n<td>Output text to a terminal.</td>\r\n<td><span class=\"code\">print(</span><span class=\"code\">\"</span><span class=\"code\">Hello World!</span><span class=\"code\">\"</span><span class=\"code\">)</span></td>\r\n</tr>\r\n<tr>\r\n<td>return</td>\r\n<td>Return from the execution of a function. If a value is specified, return that value, otherwise return <span class=\"code\">None</span>.</td>\r\n<td><span class=\"code\">return <value or expression></span><span class=\"code\"><br /></span><span class=\"code\">return x+2</span></td>\r\n</tr>\r\n<tr>\r\n<td>while</td>\r\n<td>Execute a code block while the associated condition is <span class=\"code\">True</span>.</td>\r\n<td><span class=\"code\">while <conditional expression>:</span><br /><span class=\"code\">while True:</span><br /><span class=\"code\"> pass</span></td>\r\n</tr>\r\n<tr>\r\n<td>with</td>\r\n<td>Get Python to manage a resource (like a file) for you.</td>\r\n<td><span class=\"code\">with open(<name of file>,<file mode>) as <object name>:</span></td>\r\n</tr>\r\n</tbody>\r\n</table>\r\n<p>Extend Python's core functionality with these built-ins.</p>\r\n<table border=\"0\">\r\n<caption>Python Built-ins </caption>\r\n<tbody>\r\n<tr>\r\n<th>Built-in</th><th>Notes</th><th>Example</th>\r\n</tr>\r\n<tr>\r\n<td>False</td>\r\n<td>Value, returned by a logical operation or directly assigned.</td>\r\n<td><span class=\"code\">ok_to_continue = False</span><br /><span class=\"code\">age = 16</span><br /><span class=\"code\">old_enough = age >=21</span><br />(evaluates comparison <span class=\"code\">age>=21</span> <br />and assigns the result to <span class=\"code\">old_enough)</span></td>\r\n</tr>\r\n<tr>\r\n<td>None</td>\r\n<td>Value used when representing the absence of a value or to initialise a variable which will be changed later. Returned by functions which do not explicitly return a value.</td>\r\n<td><span class=\"code\">x = None</span></td>\r\n</tr>\r\n<tr>\r\n<td>True</td>\r\n<td>Value, returned by a logical operation.</td>\r\n<td><span class=\"code\">ok_to_continue = True</span><br /><span class=\"code\">age = 16</span><br /><span class=\"code\">old_enough = age >=21</span><br />(evaluates comparison <span class=\"code\">age>=21</span> <br />and assigns the result to <span class=\"code\">old_enough)</span></td>\r\n</tr>\r\n<tr>\r\n<td>__name__</td>\r\n<td>Constant, shows module name. If it's not <span class=\"code\">\"</span><span class=\"code\">__</span><span class=\"code\">main</span><span class=\"code\">__</span><span class=\"code\">\"</span>, the code is being used in an import.</td>\r\n<td><span class=\"code\">if __name__==</span><span class=\"code\">\"</span><span class=\"code\">__main__</span><span class=\"code\">\"</span><span class=\"code\">:</span></td>\r\n</tr>\r\n<tr>\r\n<td>dir</td>\r\n<td>List attributes of an item.</td>\r\n<td><span class=\"code\">dir(<</span><span class=\"code\"><em>object name</em></span><span class=\"code\">>)</span></td>\r\n</tr>\r\n<tr>\r\n<td>enumerate</td>\r\n<td>Iterate through a sequence and number each item.</td>\r\n<td><span class=\"code\">enumerate(</span><span class=\"code\">'</span><span class=\"code\">Hello</span><span class=\"code\">'</span><span class=\"code\">)</span></td>\r\n</tr>\r\n<tr>\r\n<td>exit</td>\r\n<td>Exit Python (Command Line) interpreter.</td>\r\n<td><span class=\"code\">exit()</span></td>\r\n</tr>\r\n<tr>\r\n<td>float</td>\r\n<td>Convert a number into a decimal, usually so that division works properly.</td>\r\n<td><span class=\"code\">1/float(2)</span></td>\r\n</tr>\r\n<tr>\r\n<td>getattr</td>\r\n<td>Get an attribute of an object by a name. Useful for introspection.</td>\r\n<td><span class=\"code\">getattr(<</span><span class=\"code\"><em>name of object</em></span><span class=\"code\">>, <</span><span class=\"code\"><em>name of attribute</em></span><span class=\"code\">>)</span></td>\r\n</tr>\r\n<tr>\r\n<td>help</td>\r\n<td>Get Python docstring on object.</td>\r\n<td><span class=\"code\">help(<</span><span class=\"code\"><em>name of object</em></span><span class=\"code\">>)</span><span class=\"code\"><br /></span><span class=\"code\">help(getattr)</span></td>\r\n</tr>\r\n<tr>\r\n<td>id</td>\r\n<td>Show the location in the computer's RAM where an object is stored.</td>\r\n<td><span class=\"code\">id(<</span><span class=\"code\"><em>name of object</em></span><span class=\"code\">>)</span><span class=\"code\"><br /></span><span class=\"code\">id(help)</span></td>\r\n</tr>\r\n<tr>\r\n<td>int</td>\r\n<td>Convert a string into an integer number.</td>\r\n<td><span class=\"code\">int(</span><span class=\"code\">'</span><span class=\"code\">0</span><span class=\"code\">'</span><span class=\"code\">)</span></td>\r\n</tr>\r\n<tr>\r\n<td>len</td>\r\n<td>Get the number of elements in a sequence.</td>\r\n<td><span class=\"code\">len([0,1])</span></td>\r\n</tr>\r\n<tr>\r\n<td>object</td>\r\n<td>A base on which other classes can inherit from.</td>\r\n<td><span class=\"code\">class CustomObject(object):</span></td>\r\n</tr>\r\n<tr>\r\n<td>open</td>\r\n<td>Open a file on disk, return a file object.</td>\r\n<td><span class=\"code\">open(<path to file>, <mode>)</span><br /><span class=\"code\">open('mydatafile.txt', 'r') # read</span><br />(opens a file to read data from)<br /><span class=\"code\">open('mydatafile.txt', 'w') # write</span><br />(creates a new file to write to, destroys any existing file with the same name)<br /><span class=\"code\">open('mydatafile.txt', 'a') # append</span><br />(adds to an existing file if any, or creates<br />a new one if none existing already)</td>\r\n</tr>\r\n<tr>\r\n<td>print</td>\r\n<td>Reimplementation of <span class=\"code\">print</span> keyword, but as a function.<br />Need to import from the future to use it (srsly!)<br /></td>\r\n<td><span class=\"code\">from future import print_function</span><br /><span class=\"code\">print ('Hello World!</span><span class=\"code\">'</span><span class=\"code\">)</span></td>\r\n</tr>\r\n<tr>\r\n<td>range</td>\r\n<td>Gives numbers between the lower and upper limits specified (including the lower, but excluding the upper limit). A step may be specified.</td>\r\n<td><span class=\"code\">range(10)</span><span class=\"code\"><br /></span><span class=\"code\">range(5,10)</span><span class=\"code\"><br /></span><span class=\"code\">range(1,10,2)</span></td>\r\n</tr>\r\n<tr>\r\n<td>raw_input</td>\r\n<td>Get some text as a string from the user, with an optional prompt.</td>\r\n<td><span class=\"code\">prompt =</span> <span class=\"code\">'</span><span class=\"code\">What is your guess?</span> <span class=\"code\">'</span><span class=\"code\"><br />players_guess = raw_input(prompt)</span></td>\r\n</tr>\r\n<tr>\r\n<td>str</td>\r\n<td>Convert an object (usually a number) into a string (usually for printing).</td>\r\n<td><span class=\"code\">str(0)</span></td>\r\n</tr>\r\n<tr>\r\n<td>type</td>\r\n<td>Give the type of the specified object.</td>\r\n<td><span class=\"code\">type(0)<br />type(</span><span class=\"code\">'</span><span class=\"code\">0</span><span class=\"code\">'</span><span class=\"code\">)<br />type([])<br />type({})<br />type(())</span></td>\r\n</tr>\r\n</tbody>\r\n</table>\r\n<p>Use the work that others have already done. Try these modules from the Python standard library.</p>\r\n<table border=\"0\">\r\n<caption>Selected Functions from the Standard Library </caption>\r\n<tbody>\r\n<tr>\r\n<th>Module</th><th>What It Does</th><th>Sample Functions/Objects</th>\r\n</tr>\r\n<tr>\r\n<td>os.path</td>\r\n<td>Functions relating to files and file paths.</td>\r\n<td><span class=\"code\">os.path.exists(<path to file>)</span></td>\r\n</tr>\r\n<tr>\r\n<td>pickle, cPickle</td>\r\n<td>Save and load objects to/from a file.</td>\r\n<td><span class=\"code\">pickle.load(<file object to load from>),</span> <span class=\"code\">pickle.dump(<object to dump>, <file object to save to>)</span></td>\r\n</tr>\r\n<tr>\r\n<td>random</td>\r\n<td>Various functions relating to random numbers.</td>\r\n<td><span class=\"code\">random.choice(<sequence to choose from>), random.randint(<lower limit>, <upper limit>), random.shuffle(<name of list to shuffle>)</span></td>\r\n</tr>\r\n<tr>\r\n<td>String</td>\r\n<td>Stuff relating to strings.</td>\r\n<td><span class=\"code\">string.printable</span></td>\r\n</tr>\r\n<tr>\r\n<td>sys</td>\r\n<td>Various functions related to your computer system.</td>\r\n<td><span class=\"code\">sys.exit()</span></td>\r\n</tr>\r\n<tr>\r\n<td>Time</td>\r\n<td>Time-related functions.</td>\r\n<td><span class=\"code\">time.time()</span></td>\r\n</tr>\r\n<tr>\r\n<td>Tkinter</td>\r\n<td>User interface widgets and associated constants.</td>\r\n<td><span class=\"code\">Tkinter.ALL</span><br /><span class=\"code\">Tkinter.BOTH</span><br /><span class=\"code\">Tkinter.CENTER</span><br /><span class=\"code\">Tkinter.END</span><br /><span class=\"code\">Tkinter.HORIZONTAL</span><br /><span class=\"code\">Tkinter.LEFT</span><br /><span class=\"code\">Tkinter.NW</span><br /><span class=\"code\">Tkinter.RIGHT</span><br /><span class=\"code\">Tkinter.TOP</span><br /><span class=\"code\">Tkinter.Y</span><br /><span class=\"code\">Tkinter.Button(<parent widget>,</span><br /><span class=\"code\">text=<button text>)</span><br /><span class=\"code\">Tkinter.Canvas(<parent widget>,</span><br /><span class=\"code\"> width=<width>, height=<height>)</span><br /><span class=\"code\">Tkinter.Checkbutton(<parent widget>,</span><br /><span class=\"code\"> text=<checkbutton text>)</span><br /><span class=\"code\">Tkinter.Entry(<parent widget>,</span><br /><span class=\"code\"> width=<number of characters wide>),</span><br /><span class=\"code\">Tkinter.Frame(<parent widget>)</span><br /><span class=\"code\">Tkinter.IntVar()</span><br /><span class=\"code\">Tkinter.Label(<parent widget>,</span><br /><span class=\"code\"> text = <label text>)</span><br /><span class=\"code\">Tkinter.mainloop()</span><br /><span class=\"code\">Tkinter.Menu(<parent widget>)</span><br /><span class=\"code\">Tkinter.OptionMenu(<parent widget>,</span><br /><span class=\"code\"> None, None)</span><br /><span class=\"code\">Tkinter.Scale(<parent widget>,</span><br /><span class=\"code\"> from_=<lower limit>,</span><br /><span class=\"code\"> to=<upper limit>)</span><br /><span class=\"code\">Tkinter.Scrollbar(<parent widget>)</span><br /><span class=\"code\">Tkinter.StringVar()</span><br /><span class=\"code\">Tkinter.Tk()</span><br /></td>\r\n</tr>\r\n</tbody>\r\n</table>\r\n<p>Add, subtract, divide, multiply, and more using these operators.</p>\r\n<table border=\"0\">\r\n<caption>Python Operators </caption>\r\n<tbody>\r\n<tr>\r\n<th>Operator</th><th>Name</th><th>Effect</th><th>Examples</th>\r\n</tr>\r\n<tr>\r\n<td>+</td>\r\n<td>Plus</td>\r\n<td>Add two numbers.<br />Join two strings together.</td>\r\n<td>Add: <span class=\"code\">>>> 1+1</span><span class=\"code\"><br /></span><span class=\"code\">2</span><span class=\"code\"><br /></span>Join: <span class=\"code\">>>></span> <span class=\"code\">'</span><span class=\"code\">a</span><span class=\"code\">'</span><span class=\"code\">+</span><span class=\"code\">'</span><span class=\"code\">b</span><span class=\"code\">'</span><span class=\"code\"><br /></span><span class=\"code\">'</span><span class=\"code\">ab</span><span class=\"code\">'</span></td>\r\n</tr>\r\n<tr>\r\n<td>–</td>\r\n<td>Minus</td>\r\n<td>Subtract a number from another.<br />Can't use for strings.</td>\r\n<td><span class=\"code\">>>> 1-1</span><span class=\"code\"><br /></span><span class=\"code\">0</span></td>\r\n</tr>\r\n<tr>\r\n<td>*</td>\r\n<td>Times</td>\r\n<td>Multiply two numbers.<br />Make copies of a string.</td>\r\n<td>Multiply: <span class=\"code\">>>> 2*2</span><span class=\"code\"><br /></span><span class=\"code\">4</span><span class=\"code\"><br /></span>Copy: <span class=\"code\">>>></span> <span class=\"code\">'</span><span class=\"code\">a</span><span class=\"code\">'</span><span class=\"code\">*2</span><span class=\"code\"><br /></span><span class=\"code\">'</span><span class=\"code\">aa</span><span class=\"code\">'</span></td>\r\n</tr>\r\n<tr>\r\n<td>/</td>\r\n<td>Divide</td>\r\n<td>Divide one number by another.<br />Can't use for strings.</td>\r\n<td>1/2 # integer division:<br />Answer will be rounded down.<br />1/2.0 # decimal division<br />1/float(2) # decimal division<br /></td>\r\n</tr>\r\n<tr>\r\n<td>%</td>\r\n<td>Remainder (Modulo)</td>\r\n<td>Give the remainder when dividing the left number by the right number.<br />Formatting operator for strings.</td>\r\n<td><span class=\"code\">>>> 10%3</span><br /><span class=\"code\">1</span></td>\r\n</tr>\r\n<tr>\r\n<td>**</td>\r\n<td>Power</td>\r\n<td><span class=\"code\">x**y</span> means raise <span class=\"code\">x</span> to the power of <span class=\"code\">y</span>.<br />Can't use for strings.</td>\r\n<td><span class=\"code\">>>> 3**2</span><span class=\"code\"><br /></span><span class=\"code\">9</span></td>\r\n</tr>\r\n<tr>\r\n<td>=</td>\r\n<td>Assignment</td>\r\n<td>Assign the value on the right to the variable on the left.</td>\r\n<td><span class=\"code\">>>> a = 1</span></td>\r\n</tr>\r\n<tr>\r\n<td>==</td>\r\n<td>Equality</td>\r\n<td>Is the left side equal to the right side? Is <span class=\"code\">True</span> if so; is <span class=\"code\">False</span> otherwise.</td>\r\n<td><span class=\"code\">>>> 1 == 1</span><br /><span class=\"code\">True</span><br /><span class=\"code\">>>> 'a' == 'a'</span><br /><span class=\"code\">True</span></td>\r\n</tr>\r\n<tr>\r\n<td>!=</td>\r\n<td>Not equal</td>\r\n<td>Is the left side <em>not</em> equal to the right side? Is <span class=\"code\">True</span> if so; is False otherwise.</td>\r\n<td><span class=\"code\">>>> 1 != 1</span><br /><span class=\"code\">False</span><br /><span class=\"code\">>>> 1 != 2</span><br /><span class=\"code\">True</span><br /><span class=\"code\">>>> 'a' != 'a'</span><br /><span class=\"code\">True</span></td>\r\n</tr>\r\n<tr>\r\n<td>></td>\r\n<td>Greater than</td>\r\n<td>Is the left side greater than the right side?<br /><span class=\"code\">>=</span> means greater than or equal to</td>\r\n<td><span class=\"code\">>>> 2 > 1</span><span class=\"code\"><br /></span><span class=\"code\">True</span></td>\r\n</tr>\r\n<tr>\r\n<td><</td>\r\n<td>Less than</td>\r\n<td>Is the left side less than the right side?<br /><span class=\"code\"><=</span> means less than or equal to</td>\r\n<td><span class=\"code\">>>> 1 < 2</span><span class=\"code\"><br /></span><span class=\"code\">True</span></td>\r\n</tr>\r\n<tr>\r\n<td>& (or and)</td>\r\n<td>And</td>\r\n<td>Are both left and right <span class=\"code\">True</span>?<br />Typically used for complex conditions where you want to do something if everything is <span class=\"code\">True</span>:<br /><span class=\"code\">while im_hungry and you_have_food:</span></td>\r\n<td><span class=\"code\">>>> True & True</span><br /><span class=\"code\">True</span><br /><span class=\"code\">>>> True and False</span><br /><span class=\"code\">False </span><br /><span class=\"code\">>>> True & (1 == 2)</span><br /><span class=\"code\">False</span></td>\r\n</tr>\r\n<tr>\r\n<td>| (or or)</td>\r\n<td>Or</td>\r\n<td>Is either left or right <span class=\"code\">True</span>?<br />Typically used for complex conditions where you want at least one thing to be <span class=\"code\">True</span>:<br /><span class=\"code\">while im_bored or youre_bored:</span></td>\r\n<td><span class=\"code\">>>> True | False</span><br /><span class=\"code\">True</span><br /><span class=\"code\">>>> True or False</span><br /><span class=\"code\">True</span><br /><span class=\"code\">>>> False | False</span><br /><span class=\"code\">False</span><br /><span class=\"code\">>>> (1 == 1) | False</span><br /><span class=\"code\">True</span></td>\r\n</tr>\r\n</tbody>\r\n</table>","blurb":"","authors":[{"authorId":9026,"name":"Brendan Scott","slug":"brendan-scott","description":" <p>Brendan Scott is a dad who loves Python and wants kids to get some of its magic too. He started pythonforkids.brendanscott.com to help teach his oldest child to code. He maintains it to help other young people learn Python.</p> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/9026"}}],"primaryCategoryTaxonomy":{"categoryId":33606,"title":"Python","slug":"python","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33606"}},"secondaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"tertiaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"trendingArticles":[{"articleId":192609,"title":"How to Pray the Rosary: A Comprehensive Guide","slug":"how-to-pray-the-rosary","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/192609"}},{"articleId":208741,"title":"Kabbalah For Dummies Cheat Sheet","slug":"kabbalah-for-dummies-cheat-sheet","categoryList":["body-mind-spirit","religion-spirituality","kabbalah"],"_links":{"self":"/articles/208741"}},{"articleId":230957,"title":"Nikon D3400 For Dummies Cheat Sheet","slug":"nikon-d3400-dummies-cheat-sheet","categoryList":["home-auto-hobbies","photography"],"_links":{"self":"/articles/230957"}},{"articleId":235851,"title":"Praying the Rosary and Meditating on the Mysteries","slug":"praying-rosary-meditating-mysteries","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/235851"}},{"articleId":284787,"title":"What Your Society Says About You","slug":"what-your-society-says-about-you","categoryList":["academics-the-arts","humanities"],"_links":{"self":"/articles/284787"}}],"inThisArticle":[{"label":"Python Core Words","target":"#tab1"}],"relatedArticles":{"fromBook":[{"articleId":207407,"title":"Python For Kids For Dummies Cheat Sheet","slug":"python-for-kids-for-dummies-cheat-sheet","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/207407"}},{"articleId":141581,"title":"Use Python to Help with Your Math Homework","slug":"use-python-to-help-with-your-math-homework","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/141581"}},{"articleId":141443,"title":"Using Tkinter Widgets in Python","slug":"using-tkinter-widgets-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/141443"}},{"articleId":139551,"title":"How to Interrupt a Program in Python","slug":"how-to-interrupt-a-program-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/139551"}},{"articleId":139550,"title":"How to Name Functions in Python","slug":"how-to-name-functions-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/139550"}}],"fromCategory":[{"articleId":264919,"title":"How to Define and Use Python Lists","slug":"how-to-define-and-use-python-lists","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264919"}},{"articleId":264911,"title":"How to Use Lambda Functions in Python","slug":"how-to-use-lambda-functions-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264911"}},{"articleId":264906,"title":"Your Guide to the Python Standard Library","slug":"your-guide-to-the-python-standard-library","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264906"}},{"articleId":264894,"title":"A Beginner’s Guide to Python Versions","slug":"a-beginners-guide-to-python-versions","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264894"}},{"articleId":264888,"title":"How to Build a Simple Neural Network in Python","slug":"how-to-build-a-simple-neural-network-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264888"}}]},"hasRelatedBookFromSearch":false,"relatedBook":{"bookId":281835,"slug":"python-for-kids-for-dummies","isbn":"9781119093107","categoryList":["technology","programming-web-design","python"],"amazon":{"default":"https://www.amazon.com/gp/product/1119093104/ref=as_li_tl?ie=UTF8&tag=wiley01-20","ca":"https://www.amazon.ca/gp/product/1119093104/ref=as_li_tl?ie=UTF8&tag=wiley01-20","indigo_ca":"http://www.tkqlhce.com/click-9208661-13710633?url=https://www.chapters.indigo.ca/en-ca/books/product/1119093104-item.html&cjsku=978111945484","gb":"https://www.amazon.co.uk/gp/product/1119093104/ref=as_li_tl?ie=UTF8&tag=wiley01-20","de":"https://www.amazon.de/gp/product/1119093104/ref=as_li_tl?ie=UTF8&tag=wiley01-20"},"image":{"src":"https://www.dummies.com/wp-content/uploads/python-for-kids-for-dummies-cover-9781119093107-203x255.jpg","width":203,"height":255},"title":"Python For Kids For Dummies","testBankPinActivationLink":"","bookOutOfPrint":false,"authorsInfo":"<p>Brendan Scott is a dad who loves Python and wants kids to get some of its magic too. He started pythonforkids.brendanscott.com to help teach his oldest child to code. He maintains it to help other young people learn Python.</p>","authors":[{"authorId":9026,"name":"Brendan Scott","slug":"brendan-scott","description":" <p>Brendan Scott is a dad who loves Python and wants kids to get some of its magic too. He started pythonforkids.brendanscott.com to help teach his oldest child to code. He maintains it to help other young people learn Python.</p> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/9026"}}],"_links":{"self":"https://dummies-api.dummies.com/v2/books/"}},"collections":[],"articleAds":{"footerAd":"<div class=\"du-ad-region row\" id=\"article_page_adhesion_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_adhesion_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;python&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119093107&quot;]},{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;For Kids&quot;]}]\" id=\"du-slot-651d7e2ed9089\"></div></div>","rightAd":"<div class=\"du-ad-region row\" id=\"article_page_right_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_right_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;python&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119093107&quot;]},{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;For Kids&quot;]}]\" id=\"du-slot-651d7e2eda216\"></div></div>"},"articleType":{"articleType":"Articles","articleList":null,"content":null,"videoInfo":{"videoId":null,"name":null,"accountId":null,"playerId":null,"thumbnailUrl":null,"description":null,"uploadDate":null}},"sponsorship":{"sponsorshipPage":false,"backgroundImage":{"src":null,"width":0,"height":0},"brandingLine":"","brandingLink":"","brandingLogo":{"src":null,"width":0,"height":0},"sponsorAd":"","sponsorEbookTitle":"","sponsorEbookLink":"","sponsorEbookImage":{"src":null,"width":0,"height":0}},"primaryLearningPath":"Advance","lifeExpectancy":"Two years","lifeExpectancySetFrom":"2023-10-04T00:00:00+00:00","dummiesForKids":"yes","sponsoredContent":"no","adInfo":"","adPairKey":[{"adPairKey":"cat","adPairValue":"For Kids"}]},"status":"publish","visibility":"public","articleId":141474},{"headers":{"creationTime":"2016-03-27T16:47:06+00:00","modifiedTime":"2023-10-03T17:18:35+00:00","timestamp":"2023-10-03T18:01:03+00:00"},"data":{"breadcrumbs":[{"name":"Technology","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33512"},"slug":"technology","categoryId":33512},{"name":"Programming & Web Design","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33592"},"slug":"programming-web-design","categoryId":33592},{"name":"Python","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33606"},"slug":"python","categoryId":33606}],"title":"Python for Data Science For Dummies Cheat Sheet","strippedTitle":"python for data science for dummies cheat sheet","slug":"python-for-data-science-for-dummies-cheat-sheet","canonicalUrl":"","seo":{"metaDescription":"Perform data science tasks with minimum effort by using Python. Learn line plot styles, common programming errors, and more.","noIndex":0,"noFollow":0},"content":"Python is an incredible programming language that you can use to perform data science tasks with a minimum of effort. The huge number of available libraries means that the low-level code you normally need to write is likely already available from some other source.\r\n\r\nAll you need to focus on is getting the job done. With that in mind, this Cheat Sheet helps you access the most commonly needed reminders for making your programming experience fast and easy.","description":"Python is an incredible programming language that you can use to perform data science tasks with a minimum of effort. The huge number of available libraries means that the low-level code you normally need to write is likely already available from some other source.\r\n\r\nAll you need to focus on is getting the job done. With that in mind, this Cheat Sheet helps you access the most commonly needed reminders for making your programming experience fast and easy.","blurb":"","authors":[{"authorId":9109,"name":"John Paul Mueller","slug":"john-paul-mueller","description":"<b> John Mueller</b> has published more than 100 books on technology, data, and programming. John has a website and blog where he writes articles on technology and offers assistance alongside his published books.","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/9109"}},{"authorId":9110,"name":"Luca Massaron","slug":"luca-massaron","description":"<b>Luca Massaron</b> is a data scientist specializing in insurance and finance. A Google Developer Expert in machine learning, he has been involved in quantitative analysis and algorithms since 2000.","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/9110"}}],"primaryCategoryTaxonomy":{"categoryId":33606,"title":"Python","slug":"python","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33606"}},"secondaryCategoryTaxonomy":{"categoryId":33580,"title":"General Data Science","slug":"general-data-science","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33580"}},"tertiaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"trendingArticles":[{"articleId":192609,"title":"How to Pray the Rosary: A Comprehensive Guide","slug":"how-to-pray-the-rosary","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/192609"}},{"articleId":208741,"title":"Kabbalah For Dummies Cheat Sheet","slug":"kabbalah-for-dummies-cheat-sheet","categoryList":["body-mind-spirit","religion-spirituality","kabbalah"],"_links":{"self":"/articles/208741"}},{"articleId":230957,"title":"Nikon D3400 For Dummies Cheat Sheet","slug":"nikon-d3400-dummies-cheat-sheet","categoryList":["home-auto-hobbies","photography"],"_links":{"self":"/articles/230957"}},{"articleId":235851,"title":"Praying the Rosary and Meditating on the Mysteries","slug":"praying-rosary-meditating-mysteries","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/235851"}},{"articleId":284787,"title":"What Your Society Says About You","slug":"what-your-society-says-about-you","categoryList":["academics-the-arts","humanities"],"_links":{"self":"/articles/284787"}}],"inThisArticle":[],"relatedArticles":{"fromBook":[{"articleId":262687,"title":"Working with Google Colaboratory Notebooks","slug":"working-with-google-colaboratory-notebooks","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/262687"}},{"articleId":262680,"title":"Python Programming: Making Machine Learning Accessible with the Random Forest Algorithm","slug":"python-programming-making-machine-learning-accessible-with-the-random-forest-algorithm","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/262680"}},{"articleId":262675,"title":"What is Google Colaboratory?","slug":"what-is-google-colaboratory","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/262675"}},{"articleId":262651,"title":"Playing with Scikit-Learn and Neural Networks","slug":"playing-with-scikit-learn-and-neural-networks","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/262651"}},{"articleId":262643,"title":"Tips for Using Jupyter Notebook for Python Programming","slug":"tips-for-using-jupyter-notebook-for-python-programming","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/262643"}}],"fromCategory":[{"articleId":264919,"title":"How to Define and Use Python Lists","slug":"how-to-define-and-use-python-lists","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264919"}},{"articleId":264911,"title":"How to Use Lambda Functions in Python","slug":"how-to-use-lambda-functions-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264911"}},{"articleId":264906,"title":"Your Guide to the Python Standard Library","slug":"your-guide-to-the-python-standard-library","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264906"}},{"articleId":264894,"title":"A Beginner’s Guide to Python Versions","slug":"a-beginners-guide-to-python-versions","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264894"}},{"articleId":264888,"title":"How to Build a Simple Neural Network in Python","slug":"how-to-build-a-simple-neural-network-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264888"}}]},"hasRelatedBookFromSearch":false,"relatedBook":{"bookId":281834,"slug":"python-for-data-science-for-dummies-2nd-edition","isbn":"9781394213146","categoryList":["technology","programming-web-design","python"],"amazon":{"default":"https://www.amazon.com/gp/product/139421314X/ref=as_li_tl?ie=UTF8&tag=wiley01-20","ca":"https://www.amazon.ca/gp/product/139421314X/ref=as_li_tl?ie=UTF8&tag=wiley01-20","indigo_ca":"http://www.tkqlhce.com/click-9208661-13710633?url=https://www.chapters.indigo.ca/en-ca/books/product/139421314X-item.html&cjsku=978111945484","gb":"https://www.amazon.co.uk/gp/product/139421314X/ref=as_li_tl?ie=UTF8&tag=wiley01-20","de":"https://www.amazon.de/gp/product/139421314X/ref=as_li_tl?ie=UTF8&tag=wiley01-20"},"image":{"src":"https://www.dummies.com/wp-content/uploads/python-for-data-science-for-dummies-3rd-edition-cover-9781394213146-203x255.jpg","width":203,"height":255},"title":"Python for Data Science For Dummies","testBankPinActivationLink":"","bookOutOfPrint":true,"authorsInfo":"<p><b> John Mueller</b> has published more than 100 books on technology, data, and programming. John has a website and blog where he writes articles on technology and offers assistance alongside his published books. <b><b data-author-id=\"9110\">Luca Massaron</b></b> is a data scientist specializing in insurance and finance. A Google Developer Expert in machine learning, he has been involved in quantitative analysis and algorithms since 2000.</p>","authors":[{"authorId":9109,"name":"John Paul Mueller","slug":"john-paul-mueller","description":"<b> John Mueller</b> has published more than 100 books on technology, data, and programming. John has a website and blog where he writes articles on technology and offers assistance alongside his published books.","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/9109"}},{"authorId":9110,"name":"Luca Massaron","slug":"luca-massaron","description":"<b>Luca Massaron</b> is a data scientist specializing in insurance and finance. A Google Developer Expert in machine learning, he has been involved in quantitative analysis and algorithms since 2000.","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/9110"}}],"_links":{"self":"https://dummies-api.dummies.com/v2/books/"}},"collections":[],"articleAds":{"footerAd":"<div class=\"du-ad-region row\" id=\"article_page_adhesion_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_adhesion_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;python&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781394213146&quot;]}]\" id=\"du-slot-651c56df11374\"></div></div>","rightAd":"<div class=\"du-ad-region row\" id=\"article_page_right_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_right_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;python&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781394213146&quot;]}]\" id=\"du-slot-651c56df11cbd\"></div></div>"},"articleType":{"articleType":"Cheat Sheet","articleList":[{"articleId":142841,"title":"The 8 Most Common Python Programming Errors","slug":"the-8-most-common-python-programming-errors","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/142841"}},{"articleId":142839,"title":"Line Plot Styles","slug":"line-plot-styles","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/142839"}},{"articleId":142840,"title":"Common IPython Magic Functions","slug":"common-ipython-magic-functions","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/142840"}},{"articleId":142686,"title":"Scikit-Learn Method Summary","slug":"scikit-learn-method-summary","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/142686"}}],"content":[{"title":"The 8 most common Python programming errors","thumb":null,"image":null,"content":"<p>Every developer on the planet makes mistakes. However, knowing about common mistakes will save you time and effort later. The following list tells you about the most common errors that developers experience when working with Python:</p>\n<ul class=\"level-one\">\n<li>\n<p class=\"first-para\"><strong>Using the incorrect indentation:</strong> Many Python features rely on indentation. For example, when you create a new class, everything in that class is indented under the class declaration. The same is true for decision, loop, and other structural statements. If you find that your code is executing a task when it really shouldn’t be, start reviewing the indentation you’re using.</p>\n</li>\n<li>\n<p class=\"first-para\"><strong>Relying on the assignment operator instead of the equality operator:</strong> When performing a comparison between two objects or value, you just use the equality operator (==), not the assignment operator (=). The assignment operator places an object or value within a variable and doesn’t compare anything.</p>\n</li>\n<li>\n<p class=\"first-para\"><strong>Placing function calls in the wrong order when creating complex statements:</strong> Python always executes functions from left to right. So the statement <code>MyString.strip().center(21, \"*\")</code> produces a different result than <code>MyString.center(21, \"*\").strip()</code>. When you encounter a situation in which the output of a series of concatenated functions is different from what you expected, you need to check function order to ensure that each function is in the correct place.</p>\n</li>\n<li>\n<p class=\"first-para\"><strong>Misplacing punctuation:</strong> You can put punctuation in the wrong place and create an entirely different result. Remember that you must include a colon at the end of each structural statement. In addition, the placement of parentheses is critical. For example, <code>(1 + 2) * (3 + 4), 1 + ((2 * 3) + 4)</code>, and <code>1 + (2 * (3 + 4))</code> all produce different results.</p>\n</li>\n<li>\n<p class=\"first-para\"><strong>Using the incorrect logical operator:</strong> Most of the operators don’t present developers with problems, but the logical operators do. Remember to use <code>and </code>to determine when both operands must be <code>True </code>and <code>or </code>when either of the operands can be <code>True</code>.</p>\n</li>\n<li>\n<p class=\"first-para\"><strong>Creating count-by-one errors on loops:</strong> Remember that a loop doesn’t count the last number you specify in a range. So, if you specify the range <code>[1:11]</code>, you actually get output for values between 1 and 10.</p>\n</li>\n<li>\n<p class=\"first-para\"><strong>Using the wrong capitalization:</strong> Python is case sensitive, so MyVar is different from myvar and MYVAR. Always check capitalization when you find that you can’t access a value you expected to access.</p>\n</li>\n<li>\n<p class=\"first-para\"><strong>Making a spelling mistake:</strong> Even seasoned developers suffer from spelling errors at times. Ensuring that you use a common approach to naming variables, classes, and functions does help. However, even a consistent naming scheme won’t always prevent you from typing MyVer when you meant to type MyVar.</p>\n</li>\n<li><strong>Misunderstanding how function defaults work:</strong> A function’s default value is set at the time it’s first evaluated, rather than each time you call it. Consequently, a function declaration like this:def myFunc(list=[]):list.append(&#8220;value&#8221;)\n<p>return list</p>\n<p>will only provide an empty list the first time you call it, rather than every time you call it without providing a value for list. Subsequent calls will simply add &#8220;value&#8221; to an ever growing list. So if you call myFunc() three times, <span style=\"text-decoration: line-through;\">list</span> will actually equal [&#8220;value&#8221;, &#8220;value&#8221;, &#8220;value&#8221;]. The workaround for this issue is to check the input value every time in the code and act accordingly, such as:</p>\n<p>def myFunc(list=None):</p>\n<p>if list is None:</p>\n<p>list = []</p>\n<p>list.append(&#8220;value&#8221;)</p>\n<p>return list</li>\n<li><strong>Modifying a list while iterating over it:</strong> If a developer is lucky, this particular mistake results in an index out-of-range error. At least there is some indication of where to look. However, when working with some data science problems that don’t use the entire list, but simply iterate over parts of it, the mistake can introduce all sorts of data skewing and analysis problems that can be extremely difficult to locate (assuming that you know there is a problem at all). Using list comprehensions is a common method of avoiding this problem.</li>\n<li><strong>Creating a module name that clashes with a Python standard library module:</strong> If you create a module that has the same name as an existing Python module, Python may import your module instead of the one you wanted, leading to some difficult-to-find errors. The best way to avoid this issue is to ensure that you use module names that are guaranteed to be unique, such as prepending your organization name to the module name.</li>\n</ul>\n"},{"title":"Line plot styles","thumb":null,"image":null,"content":"<p>Whenever you create a plot, you need to identify the sources of information using more than just the lines. Creating a plot that uses differing line types and data point symbols makes the plot much easier for other people to use. The following table lists the line plot styles.</p>\n<table>\n<tbody>\n<tr>\n<td colspan=\"2\"><strong>Color</strong></td>\n<td colspan=\"2\"><strong>Marker</strong></td>\n<td colspan=\"2\"><strong>Style</strong></td>\n</tr>\n<tr>\n<td><strong>Code</strong></td>\n<td><strong>Line Color</strong></td>\n<td><strong>Code</strong></td>\n<td><strong>Marker Style</strong></td>\n<td><strong>Code</strong></td>\n<td><strong>Line Style</strong></td>\n</tr>\n<tr>\n<td>b</td>\n<td>blue</td>\n<td>.</td>\n<td>point</td>\n<td>&#8211;</td>\n<td>Solid</td>\n</tr>\n<tr>\n<td>g</td>\n<td>green</td>\n<td>o</td>\n<td>circle</td>\n<td>:</td>\n<td>Dotted</td>\n</tr>\n<tr>\n<td>r</td>\n<td>red</td>\n<td>x</td>\n<td>x-mark</td>\n<td>-.</td>\n<td>dash dot</td>\n</tr>\n<tr>\n<td>c</td>\n<td>cyan</td>\n<td>+</td>\n<td>plus</td>\n<td>&#8212;</td>\n<td>Dashed</td>\n</tr>\n<tr>\n<td>m</td>\n<td>magenta</td>\n<td>*</td>\n<td>star</td>\n<td>(none)</td>\n<td>no line</td>\n</tr>\n<tr>\n<td>y</td>\n<td>yellow</td>\n<td>s</td>\n<td>square</td>\n<td></td>\n<td></td>\n</tr>\n<tr>\n<td>k</td>\n<td>black</td>\n<td>d</td>\n<td>diamond</td>\n<td></td>\n<td></td>\n</tr>\n<tr>\n<td>w</td>\n<td>white</td>\n<td>v</td>\n<td>down triangle</td>\n<td></td>\n<td></td>\n</tr>\n<tr>\n<td></td>\n<td></td>\n<td>^</td>\n<td>up triangle</td>\n<td></td>\n<td></td>\n</tr>\n<tr>\n<td></td>\n<td></td>\n<td>&lt;</td>\n<td>left triangle</td>\n<td></td>\n<td></td>\n</tr>\n<tr>\n<td></td>\n<td></td>\n<td>&gt;</td>\n<td>right triangle</td>\n<td></td>\n<td></td>\n</tr>\n<tr>\n<td></td>\n<td></td>\n<td>p</td>\n<td>5-point star</td>\n<td></td>\n<td></td>\n</tr>\n<tr>\n<td></td>\n<td></td>\n<td>h</td>\n<td>6-point star</td>\n<td></td>\n<td></td>\n</tr>\n</tbody>\n</table>\n<p class=\"Tip\">Remember that you can also use these styles with other kinds of plots. For example, a scatter plot can use these styles to define each of the data points. When in doubt, try the styles to see whether they’ll work with your particular plot.</p>\n"},{"title":"Common IPython Magic Functions","thumb":null,"image":null,"content":"<p>It’s kind of amazing to think that IPython provides you with magic, but that’s precisely what you get with the magic functions. Most magic functions begin with either a % or %% sign. Those with a % sign work within the environment, and those with a %% sign work at the cell level.</p>\n<p>There are a few specialized functions, such as the system command escape (!), that require a special symbol or technique. Of these, the system command escape is the most essential to know. Another useful alternative is variable expansion ($), which is used like $(myVar), to provide a value without retyping it.</p>\n<p>Note that the magic functions work best with Jupyter Notebook. People using alternatives, such as Google Colab, may find that some magic functions fail to provide the desired result.</p>\n<p>The following list gives you a few of the most common magic functions and their purposes. To obtain a full list, type <strong>%quickref</strong> and press Enter in Jupyter Notebook or Google Colab, or <a href=\"https://damontallen.github.io/IPython-quick-ref-sheets/\" target=\"_blank\" rel=\"noopener\">check out the full list</a>.</p>\n<table>\n<tbody>\n<tr>\n<td width=\"97\"><strong>Magic Function</strong></td>\n<td width=\"84\"><strong>Type Alone Provides Status?</strong></td>\n<td width=\"351\"><strong>Description</strong></td>\n</tr>\n<tr>\n<td width=\"97\">%%timeit or %%prun</td>\n<td width=\"84\">No</td>\n<td width=\"351\">Calculates the best time performance for all the instructions in a cell, apart from the one placed on the same cell line as the cell magic (which could therefore be an initialization instruction). The %%prun variant provides more detailed information because it relies on the Python profiler output.</td>\n</tr>\n<tr>\n<td width=\"97\">%%writefile</td>\n<td width=\"84\">No</td>\n<td width=\"351\">Writes the contents of a cell to the specified file.</td>\n</tr>\n<tr>\n<td width=\"97\">%alias</td>\n<td width=\"84\">Yes</td>\n<td width=\"351\">Assigns or displays an alias for a system command.</td>\n</tr>\n<tr>\n<td width=\"97\">%autocall</td>\n<td width=\"84\">Yes</td>\n<td width=\"351\">Enables you to call functions without including the parentheses. The settings are Off, Smart (default), and Full. The Smart setting applies the parentheses only if you include an argument with the call.</td>\n</tr>\n<tr>\n<td width=\"97\">%automagic</td>\n<td width=\"84\">Yes</td>\n<td width=\"351\">Enables you to call the line magic functions without including the % sign. The settings are False (default) and True.</td>\n</tr>\n<tr>\n<td width=\"97\">%bookmark</td>\n<td width=\"84\">No</td>\n<td width=\"351\">Sets, lists, or clears bookmarks used to track the current location within a drive’s directory system. <a href=\"https://ipythonbook.com/magic/bookmark.html\" target=\"_blank\" rel=\"noopener\">This article</a> provides additional information on using this magic.</td>\n</tr>\n<tr>\n<td width=\"97\">%cd</td>\n<td width=\"84\">Yes</td>\n<td width=\"351\">Changes directory to a new storage location. You can also use this command to move through the directory history or to change directories to a bookmark.</td>\n</tr>\n<tr>\n<td width=\"97\">%cls or %clear</td>\n<td width=\"84\">No</td>\n<td width=\"351\">Clears the screen.</td>\n</tr>\n<tr>\n<td width=\"97\">%colors</td>\n<td width=\"84\">No</td>\n<td width=\"351\">Specifies the colors used to display text associated with prompts, the information system, and exception handlers. You can choose between NoColor (black and white), Linux (default), and LightBG.</td>\n</tr>\n<tr>\n<td width=\"97\">%config</td>\n<td width=\"84\">Yes</td>\n<td width=\"351\">Enables you to configure IPython.</td>\n</tr>\n<tr>\n<td width=\"97\">%debug or %%debug</td>\n<td width=\"84\">Yes</td>\n<td width=\"351\">Starts the Python interactive debugger so that it’s possible to debug an application within the Notebook environment.</td>\n</tr>\n<tr>\n<td width=\"97\">%dhist</td>\n<td width=\"84\">Yes</td>\n<td width=\"351\">Displays a list of directories visited during the current session.</td>\n</tr>\n<tr>\n<td width=\"97\">%env</td>\n<td width=\"84\">Yes</td>\n<td width=\"351\">Gets, sets, or lists environment variables.</td>\n</tr>\n<tr>\n<td width=\"97\">%file</td>\n<td width=\"84\">No</td>\n<td width=\"351\">Outputs the name of the file that contains the source code for the object.</td>\n</tr>\n<tr>\n<td width=\"97\">%hist</td>\n<td width=\"84\">Yes</td>\n<td width=\"351\">Displays a list of magic function commands issued during the current session.</td>\n</tr>\n<tr>\n<td width=\"97\">%install_ext</td>\n<td width=\"84\">No</td>\n<td width=\"351\">Installs the specified extension.</td>\n</tr>\n<tr>\n<td width=\"97\">%load</td>\n<td width=\"84\">No</td>\n<td width=\"351\">Loads application code from another source, such as an online example.</td>\n</tr>\n<tr>\n<td width=\"97\">%load_ext</td>\n<td width=\"84\">No</td>\n<td width=\"351\">Loads a Python extension using its module name.</td>\n</tr>\n<tr>\n<td width=\"97\">%lsmagic</td>\n<td width=\"84\">Yes</td>\n<td width=\"351\">Displays a list of the currently available magic functions.</td>\n</tr>\n<tr>\n<td width=\"97\">%matplotlib</td>\n<td width=\"84\">Yes</td>\n<td width=\"351\">Sets the backend processor used for plots. Using the inline value displays the plot within the cell for an IPython Notebook file. The possible values are ‘gtk’, ‘gtk3’, ‘inline’, ‘nbagg’, ‘osx’, ‘qt’, ‘qt4’, ‘qt5’, ‘tk’, and ‘wx’.</td>\n</tr>\n<tr>\n<td width=\"97\">%more</td>\n<td width=\"84\">No</td>\n<td width=\"351\">Displays a file through the pager so that it’s possible to scan a data file while working in it in code.</td>\n</tr>\n<tr>\n<td width=\"97\">%paste</td>\n<td width=\"84\">No</td>\n<td width=\"351\">Pastes the content of the clipboard into the IPython environment.</td>\n</tr>\n<tr>\n<td width=\"97\">%pdef</td>\n<td width=\"84\">No</td>\n<td width=\"351\">Shows how to call the object (assuming that the object is callable).</td>\n</tr>\n<tr>\n<td width=\"97\">%pdoc</td>\n<td width=\"84\">No</td>\n<td width=\"351\">Displays the docstring for an object.</td>\n</tr>\n<tr>\n<td width=\"97\">%pinfo</td>\n<td width=\"84\">No</td>\n<td width=\"351\">Displays detailed information about the object (often more than provided by help alone).</td>\n</tr>\n<tr>\n<td width=\"97\">%pinfo2</td>\n<td width=\"84\">No</td>\n<td width=\"351\">Displays extra detailed information about the object (when available).</td>\n</tr>\n<tr>\n<td width=\"97\">%psource</td>\n<td width=\"84\">No</td>\n<td width=\"351\">Displays the source code for the object (assuming that the source is available).</td>\n</tr>\n<tr>\n<td width=\"97\">%reload_ext</td>\n<td width=\"84\">No</td>\n<td width=\"351\">Reloads a previously installed extension.</td>\n</tr>\n<tr>\n<td width=\"97\">%timeit or %prun</td>\n<td width=\"84\">No</td>\n<td width=\"351\">Calculates the best performance time for an instruction. The %prun variant provides more detailed information because it relies on the Python profiler output.</td>\n</tr>\n<tr>\n<td width=\"97\">%unalias</td>\n<td width=\"84\">No</td>\n<td width=\"351\">Removes a previously created alias from the list.</td>\n</tr>\n<tr>\n<td width=\"97\">%unload_ext</td>\n<td width=\"84\">No</td>\n<td width=\"351\">Unloads the specified extension.</td>\n</tr>\n</tbody>\n</table>\n<p>&nbsp;</p>\n"}],"videoInfo":{"videoId":null,"name":null,"accountId":null,"playerId":null,"thumbnailUrl":null,"description":null,"uploadDate":null}},"sponsorship":{"sponsorshipPage":false,"backgroundImage":{"src":null,"width":0,"height":0},"brandingLine":"","brandingLink":"","brandingLogo":{"src":null,"width":0,"height":0},"sponsorAd":"","sponsorEbookTitle":"","sponsorEbookLink":"","sponsorEbookImage":{"src":null,"width":0,"height":0}},"primaryLearningPath":"Advance","lifeExpectancy":"Two years","lifeExpectancySetFrom":"2023-10-02T00:00:00+00:00","dummiesForKids":"no","sponsoredContent":"no","adInfo":"","adPairKey":[]},"status":"publish","visibility":"public","articleId":207489},{"headers":{"creationTime":"2016-03-26T10:52:17+00:00","modifiedTime":"2023-09-13T18:43:31+00:00","timestamp":"2023-09-13T21:01:03+00:00"},"data":{"breadcrumbs":[{"name":"Technology","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33512"},"slug":"technology","categoryId":33512},{"name":"Programming & Web Design","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33592"},"slug":"programming-web-design","categoryId":33592},{"name":"Python","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33606"},"slug":"python","categoryId":33606}],"title":"8 Major Uses of Python","strippedTitle":"8 major uses of python","slug":"10-major-uses-of-python","canonicalUrl":"","seo":{"metaDescription":"Python programming language continues to play an important role in many companies' technology systems and applications.","noIndex":0,"noFollow":0},"content":"Many organizations are using Python these days to perform major tasks. You don't necessarily hear about them because organizations are usually reserved about giving out their trade secrets. However, Python is still there making a big difference in the way organizations work and toward keeping the bottom line from bottoming out.\r\n\r\nFollowing, are some major ways in which Python is used commercially that will make it easier to argue for using Python in your own organization. (Or you can read about some <a href=\"https://www.python.org/about/success/\" target=\"_blank\" rel=\"noopener\">Python success stories</a>.)\r\n<ul class=\"level-one\">\r\n \t<li>\r\n<p class=\"first-para\"><a href=\"http://www.paintshoppro.com/en/\" target=\"_blank\" rel=\"noopener\">Corel</a>: PaintShop Pro is a product that many people have used over the years to grab screenshots, modify their pictures, draw new images, and perform a lot of other graphics-oriented tasks. The amazing thing about this product is that it relies heavily on Python scripting. In other words, to automate tasks in PaintShop Pro, you need to know Python.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\"><a href=\"https://us.dlink.com/en/consumer\" target=\"_blank\" rel=\"noopener\">D-Link</a>: Upgrading firmware over a network connection can be problematic, and D-Link was encountering a situation in which each upgrade was tying up a machine — a poor use of resources. In addition, some upgrades required additional work because of problems with the target device. Using Python to create a multithreaded application to drive updates to the devices allows one machine to service multiple devices, and a new methodology allowed by Python reduces the number of reboots to just one after that new firmware is installed. D-Link chose Python over other languages, such as Java, because it provides an easier-to-use serial communication code.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\"><a href=\"http://www.eveonline.com/\" target=\"_blank\" rel=\"noopener\">Eve-Online</a>: Games are a major business because so many people enjoy playing them. Eve-Online is a Massively Multiplayer Online Role Playing Game (MMORPG) that relies heavily on Python for both the client and server ends of the game. It actually relies on a Python variant named <a href=\"https://wiki.python.org/moin/StacklessPython\" target=\"_blank\" rel=\"noopener\">StacklessPython</a>, which is important because you encounter these variants all the time when working with Python. Think of them as Python on steroids. These variants have all the advantages of Python, plus a few extra perks. The thing to take away from this particular company is that running an MMORPG takes major horsepower, and the company wouldn't have chosen Python unless it were actually up to the task.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\"><a href=\"http://www.forecastwatch.com/\" target=\"_blank\" rel=\"noopener\">ForecastWatch.com</a>: If you have ever wondered whether someone reviews the performance of your weatherman, look no further than ForecastWatch.com. This company compares the forecasts produced by thousands of weather forecasters each day against actual climatological data to determine their accuracy. The resulting reports are used to help improve weather forecasts. In this case, the software used to make the comparisons is written in pure Python because it comes with standard libraries useful in collecting, parsing, and storing data from online sources. In addition, Python's enhanced multithreading capabilities makes it possible to collect the forecasts from around 5,000 online sources each day. Most important of all, the code is much smaller than would have been needed by other languages such as Java or PHP.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\"><a href=\"http://www.frequentis.com/\" target=\"_blank\" rel=\"noopener\">Frequentis</a>: The next time you fly somewhere, you might be relying on Python to get you to the ground safely again. It turns out that Frequentis is the originator of TAPTools, a software product that is used for air traffic control in many airports. This particular tool provides updates on the weather and runway conditions to air traffic controllers.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\"><a href=\"http://honeywell.com/Pages/Home.aspx\">Honeywell</a>: Documenting large systems is expensive and error prone. Honeywell uses Python to perform automated testing of applications, but it also uses Python to control a cooperative environment between applications used to generate documentation for the applications. The result is that Python helps generate the reports that form the documentation for the setup.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\"><a href=\"http://www.ilm.com/\" target=\"_blank\" rel=\"noopener\">Industrial Light & Magic</a>: In this case, you find Python used in the production process for scripting complex, computer graphic-intensive films. Originally, Industrial Light & Magic relied on Unix shell scripting, but it was found that this solution just couldn't do the job. Python was compared to other languages, such as Tcl and Perl, and chosen because it's an easier-to-learn language that the organization can implement incrementally. In addition, Python can be embedded within a larger software system as a scripting language, even if the system is written in a language such as C/C++. It turns out that Python can successfully interact with these other languages in situations in which some languages can't.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\"><a href=\"http://www.usa.philips.com/\" target=\"_blank\" rel=\"noopener\">Philips</a>: Automation is essential in the semiconductor industry, so imagine trying to coordinate the effort of thousands of robots. After a number of solutions, Philips decided to go with Python for the sequencing language (the language that tells what steps each robot should take). The low-level code is written in C++, which is another reason to use Python, because Python works well with C++.</p>\r\n</li>\r\n</ul>","description":"Many organizations are using Python these days to perform major tasks. You don't necessarily hear about them because organizations are usually reserved about giving out their trade secrets. However, Python is still there making a big difference in the way organizations work and toward keeping the bottom line from bottoming out.\r\n\r\nFollowing, are some major ways in which Python is used commercially that will make it easier to argue for using Python in your own organization. (Or you can read about some <a href=\"https://www.python.org/about/success/\" target=\"_blank\" rel=\"noopener\">Python success stories</a>.)\r\n<ul class=\"level-one\">\r\n \t<li>\r\n<p class=\"first-para\"><a href=\"http://www.paintshoppro.com/en/\" target=\"_blank\" rel=\"noopener\">Corel</a>: PaintShop Pro is a product that many people have used over the years to grab screenshots, modify their pictures, draw new images, and perform a lot of other graphics-oriented tasks. The amazing thing about this product is that it relies heavily on Python scripting. In other words, to automate tasks in PaintShop Pro, you need to know Python.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\"><a href=\"https://us.dlink.com/en/consumer\" target=\"_blank\" rel=\"noopener\">D-Link</a>: Upgrading firmware over a network connection can be problematic, and D-Link was encountering a situation in which each upgrade was tying up a machine — a poor use of resources. In addition, some upgrades required additional work because of problems with the target device. Using Python to create a multithreaded application to drive updates to the devices allows one machine to service multiple devices, and a new methodology allowed by Python reduces the number of reboots to just one after that new firmware is installed. D-Link chose Python over other languages, such as Java, because it provides an easier-to-use serial communication code.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\"><a href=\"http://www.eveonline.com/\" target=\"_blank\" rel=\"noopener\">Eve-Online</a>: Games are a major business because so many people enjoy playing them. Eve-Online is a Massively Multiplayer Online Role Playing Game (MMORPG) that relies heavily on Python for both the client and server ends of the game. It actually relies on a Python variant named <a href=\"https://wiki.python.org/moin/StacklessPython\" target=\"_blank\" rel=\"noopener\">StacklessPython</a>, which is important because you encounter these variants all the time when working with Python. Think of them as Python on steroids. These variants have all the advantages of Python, plus a few extra perks. The thing to take away from this particular company is that running an MMORPG takes major horsepower, and the company wouldn't have chosen Python unless it were actually up to the task.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\"><a href=\"http://www.forecastwatch.com/\" target=\"_blank\" rel=\"noopener\">ForecastWatch.com</a>: If you have ever wondered whether someone reviews the performance of your weatherman, look no further than ForecastWatch.com. This company compares the forecasts produced by thousands of weather forecasters each day against actual climatological data to determine their accuracy. The resulting reports are used to help improve weather forecasts. In this case, the software used to make the comparisons is written in pure Python because it comes with standard libraries useful in collecting, parsing, and storing data from online sources. In addition, Python's enhanced multithreading capabilities makes it possible to collect the forecasts from around 5,000 online sources each day. Most important of all, the code is much smaller than would have been needed by other languages such as Java or PHP.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\"><a href=\"http://www.frequentis.com/\" target=\"_blank\" rel=\"noopener\">Frequentis</a>: The next time you fly somewhere, you might be relying on Python to get you to the ground safely again. It turns out that Frequentis is the originator of TAPTools, a software product that is used for air traffic control in many airports. This particular tool provides updates on the weather and runway conditions to air traffic controllers.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\"><a href=\"http://honeywell.com/Pages/Home.aspx\">Honeywell</a>: Documenting large systems is expensive and error prone. Honeywell uses Python to perform automated testing of applications, but it also uses Python to control a cooperative environment between applications used to generate documentation for the applications. The result is that Python helps generate the reports that form the documentation for the setup.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\"><a href=\"http://www.ilm.com/\" target=\"_blank\" rel=\"noopener\">Industrial Light & Magic</a>: In this case, you find Python used in the production process for scripting complex, computer graphic-intensive films. Originally, Industrial Light & Magic relied on Unix shell scripting, but it was found that this solution just couldn't do the job. Python was compared to other languages, such as Tcl and Perl, and chosen because it's an easier-to-learn language that the organization can implement incrementally. In addition, Python can be embedded within a larger software system as a scripting language, even if the system is written in a language such as C/C++. It turns out that Python can successfully interact with these other languages in situations in which some languages can't.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\"><a href=\"http://www.usa.philips.com/\" target=\"_blank\" rel=\"noopener\">Philips</a>: Automation is essential in the semiconductor industry, so imagine trying to coordinate the effort of thousands of robots. After a number of solutions, Philips decided to go with Python for the sequencing language (the language that tells what steps each robot should take). The low-level code is written in C++, which is another reason to use Python, because Python works well with C++.</p>\r\n</li>\r\n</ul>","blurb":"","authors":[{"authorId":9109,"name":"John Paul Mueller","slug":"john-paul-mueller","description":" <p><b> John Mueller</b> has published more than 100 books on technology, data, and programming. John has a website and blog where he writes articles on technology and offers assistance alongside his published books.</p> <p><b>Luca Massaron</b> is a data scientist specializing in insurance and finance. A Google Developer Expert in machine learning, he has been involved in quantitative analysis and algorithms since 2000. ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/9109"}}],"primaryCategoryTaxonomy":{"categoryId":33606,"title":"Python","slug":"python","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33606"}},"secondaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"tertiaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"trendingArticles":[{"articleId":192609,"title":"How to Pray the Rosary: A Comprehensive Guide","slug":"how-to-pray-the-rosary","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/192609"}},{"articleId":208741,"title":"Kabbalah For Dummies Cheat Sheet","slug":"kabbalah-for-dummies-cheat-sheet","categoryList":["body-mind-spirit","religion-spirituality","kabbalah"],"_links":{"self":"/articles/208741"}},{"articleId":230957,"title":"Nikon D3400 For Dummies Cheat Sheet","slug":"nikon-d3400-dummies-cheat-sheet","categoryList":["home-auto-hobbies","photography"],"_links":{"self":"/articles/230957"}},{"articleId":235851,"title":"Praying the Rosary and Meditating on the Mysteries","slug":"praying-rosary-meditating-mysteries","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/235851"}},{"articleId":284787,"title":"What Your Society Says About You","slug":"what-your-society-says-about-you","categoryList":["academics-the-arts","humanities"],"_links":{"self":"/articles/284787"}}],"inThisArticle":[],"relatedArticles":{"fromBook":[{"articleId":250588,"title":"How to Get Additional Python Libraries","slug":"get-additional-python-libraries","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/250588"}},{"articleId":250582,"title":"Printing Lists Using Python","slug":"printing-lists-using-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/250582"}},{"articleId":250578,"title":"How Permanent Storage Works for Python Programming","slug":"understanding-permanent-storage-works-python-programming","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/250578"}},{"articleId":250575,"title":"Extending Python Classes to Make New Classes","slug":"extending-python-classes-make-new-classes","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/250575"}},{"articleId":250571,"title":"Understanding the Python Class as a Packaging Method","slug":"understanding-python-class-packaging-method","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/250571"}}],"fromCategory":[{"articleId":264919,"title":"How to Define and Use Python Lists","slug":"how-to-define-and-use-python-lists","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264919"}},{"articleId":264911,"title":"How to Use Lambda Functions in Python","slug":"how-to-use-lambda-functions-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264911"}},{"articleId":264906,"title":"Your Guide to the Python Standard Library","slug":"your-guide-to-the-python-standard-library","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264906"}},{"articleId":264894,"title":"A Beginner’s Guide to Python Versions","slug":"a-beginners-guide-to-python-versions","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264894"}},{"articleId":264888,"title":"How to Build a Simple Neural Network in Python","slug":"how-to-build-a-simple-neural-network-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264888"}}]},"hasRelatedBookFromSearch":false,"relatedBook":{"bookId":281830,"slug":"beginning-programming-with-python-for-dummies-2nd-edition","isbn":"9781119913771","categoryList":["technology","programming-web-design","python"],"amazon":{"default":"https://www.amazon.com/gp/product/1119913772/ref=as_li_tl?ie=UTF8&tag=wiley01-20","ca":"https://www.amazon.ca/gp/product/1119913772/ref=as_li_tl?ie=UTF8&tag=wiley01-20","indigo_ca":"http://www.tkqlhce.com/click-9208661-13710633?url=https://www.chapters.indigo.ca/en-ca/books/product/1119913772-item.html&cjsku=978111945484","gb":"https://www.amazon.co.uk/gp/product/1119913772/ref=as_li_tl?ie=UTF8&tag=wiley01-20","de":"https://www.amazon.de/gp/product/1119913772/ref=as_li_tl?ie=UTF8&tag=wiley01-20"},"image":{"src":"https://www.dummies.com/wp-content/uploads/beginning-programming-with-python-for-dummies-3rd-edition-cover-9781119913771-203x255.jpg","width":203,"height":255},"title":"Beginning Programming with Python For Dummies","testBankPinActivationLink":"","bookOutOfPrint":true,"authorsInfo":"<p><p><b> John Mueller</b> has published more than 100 books on technology, data, and programming. John has a website and blog where he writes articles on technology and offers assistance alongside his published books.</p> <p><b>Luca Massaron</b> is a data scientist specializing in insurance and finance. A Google Developer Expert in machine learning, he has been involved in quantitative analysis and algorithms since 2000.</p>","authors":[{"authorId":9109,"name":"John Paul Mueller","slug":"john-paul-mueller","description":" <p><b> John Mueller</b> has published more than 100 books on technology, data, and programming. John has a website and blog where he writes articles on technology and offers assistance alongside his published books.</p> <p><b>Luca Massaron</b> is a data scientist specializing in insurance and finance. A Google Developer Expert in machine learning, he has been involved in quantitative analysis and algorithms since 2000. ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/9109"}}],"_links":{"self":"https://dummies-api.dummies.com/v2/books/"}},"collections":[{"title":"Pondering the Pi Possibilities","slug":"pondering-the-pi-possibilities","collectionId":297524}],"articleAds":{"footerAd":"<div class=\"du-ad-region row\" id=\"article_page_adhesion_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_adhesion_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;python&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119913771&quot;]}]\" id=\"du-slot-6502230f39d23\"></div></div>","rightAd":"<div class=\"du-ad-region row\" id=\"article_page_right_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_right_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;python&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119913771&quot;]}]\" id=\"du-slot-6502230f3a26b\"></div></div>"},"articleType":{"articleType":"Articles","articleList":null,"content":null,"videoInfo":{"videoId":null,"name":null,"accountId":null,"playerId":null,"thumbnailUrl":null,"description":null,"uploadDate":null}},"sponsorship":{"sponsorshipPage":false,"backgroundImage":{"src":null,"width":0,"height":0},"brandingLine":"","brandingLink":"","brandingLogo":{"src":null,"width":0,"height":0},"sponsorAd":"","sponsorEbookTitle":"","sponsorEbookLink":"","sponsorEbookImage":{"src":null,"width":0,"height":0}},"primaryLearningPath":"Advance","lifeExpectancy":"Six months","lifeExpectancySetFrom":"2021-12-27T00:00:00+00:00","dummiesForKids":"no","sponsoredContent":"no","adInfo":"","adPairKey":[]},"status":"publish","visibility":"public","articleId":148755},{"headers":{"creationTime":"2016-03-26T07:16:01+00:00","modifiedTime":"2023-08-10T16:10:30+00:00","timestamp":"2023-08-10T18:01:03+00:00"},"data":{"breadcrumbs":[{"name":"Technology","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33512"},"slug":"technology","categoryId":33512},{"name":"Programming & Web Design","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33592"},"slug":"programming-web-design","categoryId":33592},{"name":"Python","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33606"},"slug":"python","categoryId":33606}],"title":"Write a Simple Program in Python","strippedTitle":"write a simple program in python","slug":"write-a-simple-program-in-python","canonicalUrl":"","seo":{"metaDescription":"Just getting started with Python? Learn how to write your first program and follow in the footsteps of many great programmers.","noIndex":0,"noFollow":0},"content":"Tradition dictates that Hello World! be the first program that you write when you're learning a <a href=\"https://www.dummies.com/article/technology/programming-web-design/python/10-major-uses-of-python-148755/\" target=\"_blank\" rel=\"noopener\">new programming language like Python</a>. You're following in the footsteps of many great programmers when you create this project.\r\n\r\nTo create your Hello World! program, follow these steps:\r\n<ol class=\"level-one\">\r\n \t<li>\r\n<p class=\"first-para\">Open your Start menu and choose Python (command line).</p>\r\n<p class=\"child-para\">You should get a prompt that looks like <span class=\"code\">>>></span>.</p>\r\n<p class=\"child-para\">At the moment, you're doing everything in interactive mode in the Python interpreter. That's where the <span class=\"code\">>>></span> comes in. Python shows you <span class=\"code\">>>></span> when you're supposed to type something.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\">At the prompt, type the following. Use a single quote at the start and the end — it's beside the Enter key:</p>\r\n\r\n<pre class=\"code\">print('Hello World!')</pre>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\">Press the Enter key.</p>\r\n<p class=\"child-para\">Python runs the code you typed.</p>\r\n</li>\r\n</ol>\r\nYou see the output shown in Figure 1. Congratulations — you've written your first program. Welcome to the <a href=\"https://www.dummies.com/article/technology/programming-web-design/python/how-to-install-python-on-your-computer-139548/\" target=\"_blank\" rel=\"noopener\">Python</a>-programmers-in-training club.\r\n<div class=\"imageBlock\" style=\"width: 535px;\">\r\n\r\n[caption id=\"\" align=\"alignnone\" width=\"535\"]<img src=\"https://www.dummies.com/wp-content/uploads/497387.image0.png\" alt=\"<b>Figure </b><b>1:</b> Your Hello World! program is ready for more instructions.\" width=\"535\" height=\"267\" /> Figure 1: Your Hello World! program is ready for more instructions.[/caption]\r\n\r\n<div></div>\r\n<div class=\"imageCaption\">If you don't see what's in Figure 1, check that you typed in the text from Step 2 exactly as it's written:</div>\r\n</div>\r\n<ul class=\"level-one\">\r\n \t<li>\r\n<p class=\"first-para\">Check that the parentheses and single quotes are in the right places.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\">Check that for each opening parenthesis there is a closing parenthesis. (Otherwise, you're left hanging.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\">Check that for each opening quote there's a closing quote.</p>\r\n</li>\r\n</ul>\r\n<p class=\"Remember\">Programming languages have their own grammar and punctuation rules. These rules are the language's <i>syntax</i>. Humans, can work most stuff out even if perfect not you're is grammar (See? You figured out what that sentence was trying to say), but Python pretty much freaks out if you get the syntax wrong.</p>","description":"Tradition dictates that Hello World! be the first program that you write when you're learning a <a href=\"https://www.dummies.com/article/technology/programming-web-design/python/10-major-uses-of-python-148755/\" target=\"_blank\" rel=\"noopener\">new programming language like Python</a>. You're following in the footsteps of many great programmers when you create this project.\r\n\r\nTo create your Hello World! program, follow these steps:\r\n<ol class=\"level-one\">\r\n \t<li>\r\n<p class=\"first-para\">Open your Start menu and choose Python (command line).</p>\r\n<p class=\"child-para\">You should get a prompt that looks like <span class=\"code\">>>></span>.</p>\r\n<p class=\"child-para\">At the moment, you're doing everything in interactive mode in the Python interpreter. That's where the <span class=\"code\">>>></span> comes in. Python shows you <span class=\"code\">>>></span> when you're supposed to type something.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\">At the prompt, type the following. Use a single quote at the start and the end — it's beside the Enter key:</p>\r\n\r\n<pre class=\"code\">print('Hello World!')</pre>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\">Press the Enter key.</p>\r\n<p class=\"child-para\">Python runs the code you typed.</p>\r\n</li>\r\n</ol>\r\nYou see the output shown in Figure 1. Congratulations — you've written your first program. Welcome to the <a href=\"https://www.dummies.com/article/technology/programming-web-design/python/how-to-install-python-on-your-computer-139548/\" target=\"_blank\" rel=\"noopener\">Python</a>-programmers-in-training club.\r\n<div class=\"imageBlock\" style=\"width: 535px;\">\r\n\r\n[caption id=\"\" align=\"alignnone\" width=\"535\"]<img src=\"https://www.dummies.com/wp-content/uploads/497387.image0.png\" alt=\"<b>Figure </b><b>1:</b> Your Hello World! program is ready for more instructions.\" width=\"535\" height=\"267\" /> Figure 1: Your Hello World! program is ready for more instructions.[/caption]\r\n\r\n<div></div>\r\n<div class=\"imageCaption\">If you don't see what's in Figure 1, check that you typed in the text from Step 2 exactly as it's written:</div>\r\n</div>\r\n<ul class=\"level-one\">\r\n \t<li>\r\n<p class=\"first-para\">Check that the parentheses and single quotes are in the right places.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\">Check that for each opening parenthesis there is a closing parenthesis. (Otherwise, you're left hanging.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\">Check that for each opening quote there's a closing quote.</p>\r\n</li>\r\n</ul>\r\n<p class=\"Remember\">Programming languages have their own grammar and punctuation rules. These rules are the language's <i>syntax</i>. Humans, can work most stuff out even if perfect not you're is grammar (See? You figured out what that sentence was trying to say), but Python pretty much freaks out if you get the syntax wrong.</p>","blurb":"","authors":[{"authorId":9026,"name":"Brendan Scott","slug":"brendan-scott","description":" <p>Brendan Scott is a dad who loves Python and wants kids to get some of its magic too. He started pythonforkids.brendanscott.com to help teach his oldest child to code. He maintains it to help other young people learn Python.</p> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/9026"}}],"primaryCategoryTaxonomy":{"categoryId":33606,"title":"Python","slug":"python","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33606"}},"secondaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"tertiaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"trendingArticles":[{"articleId":192609,"title":"How to Pray the Rosary: A Comprehensive Guide","slug":"how-to-pray-the-rosary","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/192609"}},{"articleId":208741,"title":"Kabbalah For Dummies Cheat Sheet","slug":"kabbalah-for-dummies-cheat-sheet","categoryList":["body-mind-spirit","religion-spirituality","kabbalah"],"_links":{"self":"/articles/208741"}},{"articleId":230957,"title":"Nikon D3400 For Dummies Cheat Sheet","slug":"nikon-d3400-dummies-cheat-sheet","categoryList":["home-auto-hobbies","photography"],"_links":{"self":"/articles/230957"}},{"articleId":235851,"title":"Praying the Rosary and Meditating on the Mysteries","slug":"praying-rosary-meditating-mysteries","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/235851"}},{"articleId":284787,"title":"What Your Society Says About You","slug":"what-your-society-says-about-you","categoryList":["academics-the-arts","humanities"],"_links":{"self":"/articles/284787"}}],"inThisArticle":[],"relatedArticles":{"fromBook":[{"articleId":207407,"title":"Python For Kids For Dummies Cheat Sheet","slug":"python-for-kids-for-dummies-cheat-sheet","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/207407"}},{"articleId":141581,"title":"Use Python to Help with Your Math Homework","slug":"use-python-to-help-with-your-math-homework","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/141581"}},{"articleId":141474,"title":"Python 2.7 Keyword Subset and Examples","slug":"python-2-7-keyword-subset-and-examples","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/141474"}},{"articleId":141443,"title":"Using Tkinter Widgets in Python","slug":"using-tkinter-widgets-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/141443"}},{"articleId":139551,"title":"How to Interrupt a Program in Python","slug":"how-to-interrupt-a-program-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/139551"}}],"fromCategory":[{"articleId":264919,"title":"How to Define and Use Python Lists","slug":"how-to-define-and-use-python-lists","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264919"}},{"articleId":264911,"title":"How to Use Lambda Functions in Python","slug":"how-to-use-lambda-functions-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264911"}},{"articleId":264906,"title":"Your Guide to the Python Standard Library","slug":"your-guide-to-the-python-standard-library","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264906"}},{"articleId":264894,"title":"A Beginner’s Guide to Python Versions","slug":"a-beginners-guide-to-python-versions","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264894"}},{"articleId":264888,"title":"How to Build a Simple Neural Network in Python","slug":"how-to-build-a-simple-neural-network-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264888"}}]},"hasRelatedBookFromSearch":false,"relatedBook":{"bookId":281835,"slug":"python-for-kids-for-dummies","isbn":"9781119093107","categoryList":["technology","programming-web-design","python"],"amazon":{"default":"https://www.amazon.com/gp/product/1119093104/ref=as_li_tl?ie=UTF8&tag=wiley01-20","ca":"https://www.amazon.ca/gp/product/1119093104/ref=as_li_tl?ie=UTF8&tag=wiley01-20","indigo_ca":"http://www.tkqlhce.com/click-9208661-13710633?url=https://www.chapters.indigo.ca/en-ca/books/product/1119093104-item.html&cjsku=978111945484","gb":"https://www.amazon.co.uk/gp/product/1119093104/ref=as_li_tl?ie=UTF8&tag=wiley01-20","de":"https://www.amazon.de/gp/product/1119093104/ref=as_li_tl?ie=UTF8&tag=wiley01-20"},"image":{"src":"https://www.dummies.com/wp-content/uploads/python-for-kids-for-dummies-cover-9781119093107-203x255.jpg","width":203,"height":255},"title":"Python For Kids For Dummies","testBankPinActivationLink":"","bookOutOfPrint":false,"authorsInfo":"<p>Brendan Scott is a dad who loves Python and wants kids to get some of its magic too. He started pythonforkids.brendanscott.com to help teach his oldest child to code. He maintains it to help other young people learn Python.</p>","authors":[{"authorId":9026,"name":"Brendan Scott","slug":"brendan-scott","description":" <p>Brendan Scott is a dad who loves Python and wants kids to get some of its magic too. He started pythonforkids.brendanscott.com to help teach his oldest child to code. He maintains it to help other young people learn Python.</p> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/9026"}}],"_links":{"self":"https://dummies-api.dummies.com/v2/books/"}},"collections":[],"articleAds":{"footerAd":"<div class=\"du-ad-region row\" id=\"article_page_adhesion_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_adhesion_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;python&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119093107&quot;]},{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;For Kids&quot;]}]\" id=\"du-slot-64d525df11adc\"></div></div>","rightAd":"<div class=\"du-ad-region row\" id=\"article_page_right_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_right_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;python&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119093107&quot;]},{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;For Kids&quot;]}]\" id=\"du-slot-64d525df1208d\"></div></div>"},"articleType":{"articleType":"Articles","articleList":null,"content":null,"videoInfo":{"videoId":null,"name":null,"accountId":null,"playerId":null,"thumbnailUrl":null,"description":null,"uploadDate":null}},"sponsorship":{"sponsorshipPage":false,"backgroundImage":{"src":null,"width":0,"height":0},"brandingLine":"","brandingLink":"","brandingLogo":{"src":null,"width":0,"height":0},"sponsorAd":"","sponsorEbookTitle":"","sponsorEbookLink":"","sponsorEbookImage":{"src":null,"width":0,"height":0}},"primaryLearningPath":"Explore","lifeExpectancy":"One year","lifeExpectancySetFrom":"2022-01-25T00:00:00+00:00","dummiesForKids":"yes","sponsoredContent":"no","adInfo":"","adPairKey":[{"adPairKey":"cat","adPairValue":"For Kids"}]},"status":"publish","visibility":"public","articleId":139547},{"headers":{"creationTime":"2016-03-26T07:15:31+00:00","modifiedTime":"2023-08-10T16:08:09+00:00","timestamp":"2023-08-10T18:01:02+00:00"},"data":{"breadcrumbs":[{"name":"Technology","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33512"},"slug":"technology","categoryId":33512},{"name":"Programming & Web Design","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33592"},"slug":"programming-web-design","categoryId":33592},{"name":"Python","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33606"},"slug":"python","categoryId":33606}],"title":"How to Spot and Fix Errors in Python","strippedTitle":"how to spot and fix errors in python","slug":"how-to-spot-and-fix-errors-in-python","canonicalUrl":"","seo":{"metaDescription":"The Python interpreter takes in each line and operates on it immediately (more or less) after you press the Enter key. In Hello World! you use Python's print fe","noIndex":0,"noFollow":0},"content":"<p>The Python interpreter takes in each line and operates on it immediately (more or less) after you press the Enter key. In <a href=\"https://www.dummies.com/article/technology/programming-web-design/python/write-a-simple-program-in-python-139547/\">Hello World!</a> you use Python's print feature. print takes what's inside the parentheses and outputs it to the command line (also called the <i>console</i>).</p>\r\n<p>Python is sensitive to both the grammar and punctuation. If you misspell something, the program won't work. If Python is expecting special characters and you don't put them in, then Python will fail. Some Python issues are shown here. Can you work out how you would fix them?</p>\r\n<pre class=\"code\"> &gt;&gt;&gt; pritn('Hello World!')\r\n Traceback (most recent call last):\r\n File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\r\n NameError: name 'pritn' is not defined</pre>\r\n<p>Here's another:</p>\r\n<pre class=\"code\"> &gt;&gt;&gt; print('Hello World!)\r\n File \"&lt;stdin&gt;\", line 1\r\n print('Hello World!)\r\n SyntaxError: EOL while scanning string literal</pre>\r\n<p>Here's another:</p>\r\n<pre class=\"code\"> &gt;&gt;&gt; print 'Hello World!')\r\n File \"&lt;stdin&gt;\", line 1\r\n print 'Hello World!')\r\n ^\r\n SyntaxError: invalid syntax</pre>\r\n<p>Python tries to give you the reason it failed (that is, <span class=\"code\">NameError</span> and <span class=\"code\">SyntaxError</span>).</p>\r\n<p>Check each of these things:</p>\r\n<ul class=\"level-one\">\r\n <li><p class=\"first-para\">Opening parenthesis has a closing parenthesis</p>\r\n </li>\r\n <li><p class=\"first-para\">Every opening quote mark has a matching closing quote mark</p>\r\n </li>\r\n <li><p class=\"first-para\">All commands are correctly spelled</p>\r\n </li>\r\n</ul>","description":"<p>The Python interpreter takes in each line and operates on it immediately (more or less) after you press the Enter key. In <a href=\"https://www.dummies.com/article/technology/programming-web-design/python/write-a-simple-program-in-python-139547/\">Hello World!</a> you use Python's print feature. print takes what's inside the parentheses and outputs it to the command line (also called the <i>console</i>).</p>\r\n<p>Python is sensitive to both the grammar and punctuation. If you misspell something, the program won't work. If Python is expecting special characters and you don't put them in, then Python will fail. Some Python issues are shown here. Can you work out how you would fix them?</p>\r\n<pre class=\"code\"> &gt;&gt;&gt; pritn('Hello World!')\r\n Traceback (most recent call last):\r\n File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\r\n NameError: name 'pritn' is not defined</pre>\r\n<p>Here's another:</p>\r\n<pre class=\"code\"> &gt;&gt;&gt; print('Hello World!)\r\n File \"&lt;stdin&gt;\", line 1\r\n print('Hello World!)\r\n SyntaxError: EOL while scanning string literal</pre>\r\n<p>Here's another:</p>\r\n<pre class=\"code\"> &gt;&gt;&gt; print 'Hello World!')\r\n File \"&lt;stdin&gt;\", line 1\r\n print 'Hello World!')\r\n ^\r\n SyntaxError: invalid syntax</pre>\r\n<p>Python tries to give you the reason it failed (that is, <span class=\"code\">NameError</span> and <span class=\"code\">SyntaxError</span>).</p>\r\n<p>Check each of these things:</p>\r\n<ul class=\"level-one\">\r\n <li><p class=\"first-para\">Opening parenthesis has a closing parenthesis</p>\r\n </li>\r\n <li><p class=\"first-para\">Every opening quote mark has a matching closing quote mark</p>\r\n </li>\r\n <li><p class=\"first-para\">All commands are correctly spelled</p>\r\n </li>\r\n</ul>","blurb":"","authors":[{"authorId":9026,"name":"Brendan Scott","slug":"brendan-scott","description":" <p>Brendan Scott is a dad who loves Python and wants kids to get some of its magic too. He started pythonforkids.brendanscott.com to help teach his oldest child to code. He maintains it to help other young people learn Python.</p> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/9026"}}],"primaryCategoryTaxonomy":{"categoryId":33606,"title":"Python","slug":"python","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33606"}},"secondaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"tertiaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"trendingArticles":[{"articleId":192609,"title":"How to Pray the Rosary: A Comprehensive Guide","slug":"how-to-pray-the-rosary","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/192609"}},{"articleId":208741,"title":"Kabbalah For Dummies Cheat Sheet","slug":"kabbalah-for-dummies-cheat-sheet","categoryList":["body-mind-spirit","religion-spirituality","kabbalah"],"_links":{"self":"/articles/208741"}},{"articleId":230957,"title":"Nikon D3400 For Dummies Cheat Sheet","slug":"nikon-d3400-dummies-cheat-sheet","categoryList":["home-auto-hobbies","photography"],"_links":{"self":"/articles/230957"}},{"articleId":235851,"title":"Praying the Rosary and Meditating on the Mysteries","slug":"praying-rosary-meditating-mysteries","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/235851"}},{"articleId":284787,"title":"What Your Society Says About You","slug":"what-your-society-says-about-you","categoryList":["academics-the-arts","humanities"],"_links":{"self":"/articles/284787"}}],"inThisArticle":[],"relatedArticles":{"fromBook":[{"articleId":207407,"title":"Python For Kids For Dummies Cheat Sheet","slug":"python-for-kids-for-dummies-cheat-sheet","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/207407"}},{"articleId":141581,"title":"Use Python to Help with Your Math Homework","slug":"use-python-to-help-with-your-math-homework","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/141581"}},{"articleId":141474,"title":"Python 2.7 Keyword Subset and Examples","slug":"python-2-7-keyword-subset-and-examples","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/141474"}},{"articleId":141443,"title":"Using Tkinter Widgets in Python","slug":"using-tkinter-widgets-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/141443"}},{"articleId":139551,"title":"How to Interrupt a Program in Python","slug":"how-to-interrupt-a-program-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/139551"}}],"fromCategory":[{"articleId":264919,"title":"How to Define and Use Python Lists","slug":"how-to-define-and-use-python-lists","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264919"}},{"articleId":264911,"title":"How to Use Lambda Functions in Python","slug":"how-to-use-lambda-functions-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264911"}},{"articleId":264906,"title":"Your Guide to the Python Standard Library","slug":"your-guide-to-the-python-standard-library","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264906"}},{"articleId":264894,"title":"A Beginner’s Guide to Python Versions","slug":"a-beginners-guide-to-python-versions","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264894"}},{"articleId":264888,"title":"How to Build a Simple Neural Network in Python","slug":"how-to-build-a-simple-neural-network-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264888"}}]},"hasRelatedBookFromSearch":false,"relatedBook":{"bookId":281835,"slug":"python-for-kids-for-dummies","isbn":"9781119093107","categoryList":["technology","programming-web-design","python"],"amazon":{"default":"https://www.amazon.com/gp/product/1119093104/ref=as_li_tl?ie=UTF8&tag=wiley01-20","ca":"https://www.amazon.ca/gp/product/1119093104/ref=as_li_tl?ie=UTF8&tag=wiley01-20","indigo_ca":"http://www.tkqlhce.com/click-9208661-13710633?url=https://www.chapters.indigo.ca/en-ca/books/product/1119093104-item.html&cjsku=978111945484","gb":"https://www.amazon.co.uk/gp/product/1119093104/ref=as_li_tl?ie=UTF8&tag=wiley01-20","de":"https://www.amazon.de/gp/product/1119093104/ref=as_li_tl?ie=UTF8&tag=wiley01-20"},"image":{"src":"https://www.dummies.com/wp-content/uploads/python-for-kids-for-dummies-cover-9781119093107-203x255.jpg","width":203,"height":255},"title":"Python For Kids For Dummies","testBankPinActivationLink":"","bookOutOfPrint":false,"authorsInfo":"<p>Brendan Scott is a dad who loves Python and wants kids to get some of its magic too. He started pythonforkids.brendanscott.com to help teach his oldest child to code. He maintains it to help other young people learn Python.</p>","authors":[{"authorId":9026,"name":"Brendan Scott","slug":"brendan-scott","description":" <p>Brendan Scott is a dad who loves Python and wants kids to get some of its magic too. He started pythonforkids.brendanscott.com to help teach his oldest child to code. He maintains it to help other young people learn Python.</p> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/9026"}}],"_links":{"self":"https://dummies-api.dummies.com/v2/books/"}},"collections":[],"articleAds":{"footerAd":"<div class=\"du-ad-region row\" id=\"article_page_adhesion_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_adhesion_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;python&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119093107&quot;]},{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;For Kids&quot;]}]\" id=\"du-slot-64d525debf9ba\"></div></div>","rightAd":"<div class=\"du-ad-region row\" id=\"article_page_right_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_right_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;python&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119093107&quot;]},{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;For Kids&quot;]}]\" id=\"du-slot-64d525dec0400\"></div></div>"},"articleType":{"articleType":"Articles","articleList":null,"content":null,"videoInfo":{"videoId":null,"name":null,"accountId":null,"playerId":null,"thumbnailUrl":null,"description":null,"uploadDate":null}},"sponsorship":{"sponsorshipPage":false,"backgroundImage":{"src":null,"width":0,"height":0},"brandingLine":"","brandingLink":"","brandingLogo":{"src":null,"width":0,"height":0},"sponsorAd":"","sponsorEbookTitle":"","sponsorEbookLink":"","sponsorEbookImage":{"src":null,"width":0,"height":0}},"primaryLearningPath":"Advance","lifeExpectancy":"Five years","lifeExpectancySetFrom":"2023-08-10T00:00:00+00:00","dummiesForKids":"yes","sponsoredContent":"no","adInfo":"","adPairKey":[{"adPairKey":"cat","adPairValue":"For Kids"}]},"status":"publish","visibility":"public","articleId":139493},{"headers":{"creationTime":"2019-10-08T21:11:13+00:00","modifiedTime":"2023-07-10T15:33:58+00:00","timestamp":"2023-07-10T18:01:04+00:00"},"data":{"breadcrumbs":[{"name":"Technology","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33512"},"slug":"technology","categoryId":33512},{"name":"Programming & Web Design","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33592"},"slug":"programming-web-design","categoryId":33592},{"name":"Python","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33606"},"slug":"python","categoryId":33606}],"title":"The Raspberry Pi: The Perfect PC Platform for Python","strippedTitle":"the raspberry pi: the perfect pc platform for python","slug":"the-raspberry-pi-the-perfect-platform-for-physical-computing-in-python","canonicalUrl":"","seo":{"metaDescription":"Find out why the Python language and the Raspberry Pi make the perfect combination for physical computing with this guide from Dummies.com.","noIndex":0,"noFollow":0},"content":"Before you can get going here, make sure you have your <a href=\"https://www.dummies.com/computers/raspberry-pi/set-raspberry-pi/\">Raspberry Pi computer set up</a> and running on your monitor, keyboard, and mouse. If not, go do that now The next few paragraphs are going to be lots more fun with a computer to work with!\r\n\r\nThe <a href=\"http://www.raspberrypi.org/\">Raspberry Pi</a> is the perfect platform to do physical computing with Python because it has a multiscreen environment, lots of RAM and storage to play with and all the tools to build fun projects.\r\n\r\nA huge and powerful feature of the Raspberry Pi is the row of GPIO (general purpose input-output) pins along the top of the Raspberry Pi. It is a 40-pin header into which you can plug a large number of sensors and controllers to do amazing things to expand your Raspberry Pi.\r\n<h2 id=\"tab1\" >GPIO pins on the Raspberry Pi</h2>\r\n<a href=\"https://www.dummies.com/computers/raspberry-pi/how-to-control-gpio-pins-on-your-raspberry-pi/\">GPIO pins</a> can be designated (using Python software) as input or output pins and used for many different purposes. There are two 5V power pins, two 3.3V power pins and a number of ground pins that have fixed uses.\r\n\r\n[caption id=\"attachment_264873\" align=\"aligncenter\" width=\"535\"]<img class=\"wp-image-264873 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-raspberry-pi-gpio.png\" alt=\"Raspberry Pi GPIO pins\" width=\"535\" height=\"154\" /> The functions of the Raspberry Pi GPIO pins.[/caption]\r\n\r\n \r\n\r\nAn GPIO pin output pin “outputs” a 1 or a 0 from the computer to the pin. Basically, A “1” is 3.3V and a “0” is 0V. You can think of them just as 1s and 0s.\r\n<h2 id=\"tab2\" >GPIO Python libraries</h2>\r\nThere are a number of GPIO Python libraries that are usable for building projects. A good one to use is the gpiozero library that is installed on all Raspberry Pi desktop software releases. Check out the <a href=\"https://gpiozero.readthedocs.io/en/stable/\">library documentation and installation instructions</a> (if needed).\r\n\r\nNow let’s jump into the “Hello World” physical computing project with our Raspberry Pi.\r\n<h2 id=\"tab3\" >The hardware for “Hello World” on the Raspberry Pi</h2>\r\nTo do this project, you’ll need some hardware. Because these instructions involve using Grove connectors, let's get the two pieces of Grove hardware that you need for this project:\r\n<ul>\r\n \t<li><strong>Pi2Grover:</strong> This converts the Raspberry Pi <a href=\"https://www.dummies.com/computers/raspberry-pi/use-python-access-gpio-pins-raspberry-pi/\">GPIO pin</a> header to Grove connectors (ease of use and can’t reverse the power pins!). You can buy this either at shop.switchdoc.com or at Amazon.com. You can get $5.00 off the Pi2Grover board at shop.switchdoc.com by using the discount code PI2DUMMIES at checkout.\r\n\r\n[caption id=\"attachment_264874\" align=\"aligncenter\" width=\"535\"]<img class=\"wp-image-264874 size-full\" src=\"https://www.dummies.com/wp-content/uploads/pthon-pi2grover-board.jpg\" alt=\"Pi2Grover board\" width=\"535\" height=\"286\" /> The Pi2Grover board.[/caption]</li>\r\n</ul>\r\n<ul>\r\n \t<li><strong>Grove blue LED:</strong> A Grove blue LED module including Grove cable. You can buy this on shop.switchdoc.com or on amazon.com.\r\n\r\n[caption id=\"attachment_264875\" align=\"aligncenter\" width=\"535\"]<img class=\"wp-image-264875 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-grove-blue-led.jpg\" alt=\"Grove blue LED\" width=\"535\" height=\"401\" /> The Grove blue LED.[/caption]</li>\r\n</ul>\r\n[caption id=\"attachment_264876\" align=\"aligncenter\" width=\"535\"]<img class=\"wp-image-264876 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-grove-cable.jpg\" alt=\"Grove cable\" width=\"535\" height=\"547\" /> The Grove cable (included with the LED).[/caption]\r\n<h2 id=\"tab4\" >How to assemble the Raspberry Pi’s hardware</h2>\r\nFor a number of you readers, this will be the first time you have ever assembled a physical computer-based product. because of this, we’ll give you the step-by-step process:\r\n<ol>\r\n \t<li>Identify the Pi2Grover board.</li>\r\n \t<li>Making sure you align the pins correctly gently press the Pi2Grover Board (Part A) onto the 40 pin GPIO connector on the Raspberry Pi.\r\n\r\n[caption id=\"attachment_264877\" align=\"aligncenter\" width=\"535\"]<img class=\"wp-image-264877 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-aligning-pi2grover.jpg\" alt=\"aligning Pi2Grover board\" width=\"535\" height=\"401\" /> Aligning the Pi2Grover board on the Raspberry Pi.[/caption]</li>\r\n \t<li>Gently finish pushing the Pi2Grover (Part A) onto the Raspberry Pi GPIO pins, making sure the pins are aligned. There will be no pins showing on either end and make sure no pins on the Raspberry Pi are bent.\r\n\r\n[caption id=\"attachment_264878\" align=\"aligncenter\" width=\"535\"]<img class=\"wp-image-264878 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-installed-pi2grover-board.jpg\" alt=\"installed Pi2Grover board\" width=\"535\" height=\"403\" /> The installed Pi2Grover board.[/caption]</li>\r\n \t<li>Plug one end of the Grove cable into the Grove blue LED board.\r\n\r\n[caption id=\"attachment_264879\" align=\"aligncenter\" width=\"535\"]<img class=\"wp-image-264879 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-raspberry-pi-grove-cable.jpg\" alt=\"Grove cable\" width=\"535\" height=\"438\" /> A Grove cable plugged into the Grove blue LED board.[/caption]</li>\r\n \t<li>If your blue LED is not plugged into the Grove blue LED board, then plug in the LED with the flat side aligned with the flat side of the outline on the board.\r\n\r\n[caption id=\"attachment_264880\" align=\"aligncenter\" width=\"409\"]<img class=\"wp-image-264880 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-raspberry-pi-led.png\" alt=\"Raspberry Pi LED algined on Raspberry Pi board\" width=\"409\" height=\"450\" /> The LED aligned with the outline on the board.[/caption]</li>\r\n \t<li>Plug the other end of the Grove cable into the slot marked D12/D13 on the Pi2Grover board.You are now finished assembling the hardware. Now it’s time for the Python software.\r\n\r\n[caption id=\"attachment_264881\" align=\"aligncenter\" width=\"535\"]<img class=\"wp-image-264881 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-hello-world.jpg\" alt=\"Hello World Python\" width=\"535\" height=\"477\" /> The completed “Hello World” project.[/caption]</li>\r\n</ol>","description":"Before you can get going here, make sure you have your <a href=\"https://www.dummies.com/computers/raspberry-pi/set-raspberry-pi/\">Raspberry Pi computer set up</a> and running on your monitor, keyboard, and mouse. If not, go do that now The next few paragraphs are going to be lots more fun with a computer to work with!\r\n\r\nThe <a href=\"http://www.raspberrypi.org/\">Raspberry Pi</a> is the perfect platform to do physical computing with Python because it has a multiscreen environment, lots of RAM and storage to play with and all the tools to build fun projects.\r\n\r\nA huge and powerful feature of the Raspberry Pi is the row of GPIO (general purpose input-output) pins along the top of the Raspberry Pi. It is a 40-pin header into which you can plug a large number of sensors and controllers to do amazing things to expand your Raspberry Pi.\r\n<h2 id=\"tab1\" >GPIO pins on the Raspberry Pi</h2>\r\n<a href=\"https://www.dummies.com/computers/raspberry-pi/how-to-control-gpio-pins-on-your-raspberry-pi/\">GPIO pins</a> can be designated (using Python software) as input or output pins and used for many different purposes. There are two 5V power pins, two 3.3V power pins and a number of ground pins that have fixed uses.\r\n\r\n[caption id=\"attachment_264873\" align=\"aligncenter\" width=\"535\"]<img class=\"wp-image-264873 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-raspberry-pi-gpio.png\" alt=\"Raspberry Pi GPIO pins\" width=\"535\" height=\"154\" /> The functions of the Raspberry Pi GPIO pins.[/caption]\r\n\r\n \r\n\r\nAn GPIO pin output pin “outputs” a 1 or a 0 from the computer to the pin. Basically, A “1” is 3.3V and a “0” is 0V. You can think of them just as 1s and 0s.\r\n<h2 id=\"tab2\" >GPIO Python libraries</h2>\r\nThere are a number of GPIO Python libraries that are usable for building projects. A good one to use is the gpiozero library that is installed on all Raspberry Pi desktop software releases. Check out the <a href=\"https://gpiozero.readthedocs.io/en/stable/\">library documentation and installation instructions</a> (if needed).\r\n\r\nNow let’s jump into the “Hello World” physical computing project with our Raspberry Pi.\r\n<h2 id=\"tab3\" >The hardware for “Hello World” on the Raspberry Pi</h2>\r\nTo do this project, you’ll need some hardware. Because these instructions involve using Grove connectors, let's get the two pieces of Grove hardware that you need for this project:\r\n<ul>\r\n \t<li><strong>Pi2Grover:</strong> This converts the Raspberry Pi <a href=\"https://www.dummies.com/computers/raspberry-pi/use-python-access-gpio-pins-raspberry-pi/\">GPIO pin</a> header to Grove connectors (ease of use and can’t reverse the power pins!). You can buy this either at shop.switchdoc.com or at Amazon.com. You can get $5.00 off the Pi2Grover board at shop.switchdoc.com by using the discount code PI2DUMMIES at checkout.\r\n\r\n[caption id=\"attachment_264874\" align=\"aligncenter\" width=\"535\"]<img class=\"wp-image-264874 size-full\" src=\"https://www.dummies.com/wp-content/uploads/pthon-pi2grover-board.jpg\" alt=\"Pi2Grover board\" width=\"535\" height=\"286\" /> The Pi2Grover board.[/caption]</li>\r\n</ul>\r\n<ul>\r\n \t<li><strong>Grove blue LED:</strong> A Grove blue LED module including Grove cable. You can buy this on shop.switchdoc.com or on amazon.com.\r\n\r\n[caption id=\"attachment_264875\" align=\"aligncenter\" width=\"535\"]<img class=\"wp-image-264875 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-grove-blue-led.jpg\" alt=\"Grove blue LED\" width=\"535\" height=\"401\" /> The Grove blue LED.[/caption]</li>\r\n</ul>\r\n[caption id=\"attachment_264876\" align=\"aligncenter\" width=\"535\"]<img class=\"wp-image-264876 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-grove-cable.jpg\" alt=\"Grove cable\" width=\"535\" height=\"547\" /> The Grove cable (included with the LED).[/caption]\r\n<h2 id=\"tab4\" >How to assemble the Raspberry Pi’s hardware</h2>\r\nFor a number of you readers, this will be the first time you have ever assembled a physical computer-based product. because of this, we’ll give you the step-by-step process:\r\n<ol>\r\n \t<li>Identify the Pi2Grover board.</li>\r\n \t<li>Making sure you align the pins correctly gently press the Pi2Grover Board (Part A) onto the 40 pin GPIO connector on the Raspberry Pi.\r\n\r\n[caption id=\"attachment_264877\" align=\"aligncenter\" width=\"535\"]<img class=\"wp-image-264877 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-aligning-pi2grover.jpg\" alt=\"aligning Pi2Grover board\" width=\"535\" height=\"401\" /> Aligning the Pi2Grover board on the Raspberry Pi.[/caption]</li>\r\n \t<li>Gently finish pushing the Pi2Grover (Part A) onto the Raspberry Pi GPIO pins, making sure the pins are aligned. There will be no pins showing on either end and make sure no pins on the Raspberry Pi are bent.\r\n\r\n[caption id=\"attachment_264878\" align=\"aligncenter\" width=\"535\"]<img class=\"wp-image-264878 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-installed-pi2grover-board.jpg\" alt=\"installed Pi2Grover board\" width=\"535\" height=\"403\" /> The installed Pi2Grover board.[/caption]</li>\r\n \t<li>Plug one end of the Grove cable into the Grove blue LED board.\r\n\r\n[caption id=\"attachment_264879\" align=\"aligncenter\" width=\"535\"]<img class=\"wp-image-264879 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-raspberry-pi-grove-cable.jpg\" alt=\"Grove cable\" width=\"535\" height=\"438\" /> A Grove cable plugged into the Grove blue LED board.[/caption]</li>\r\n \t<li>If your blue LED is not plugged into the Grove blue LED board, then plug in the LED with the flat side aligned with the flat side of the outline on the board.\r\n\r\n[caption id=\"attachment_264880\" align=\"aligncenter\" width=\"409\"]<img class=\"wp-image-264880 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-raspberry-pi-led.png\" alt=\"Raspberry Pi LED algined on Raspberry Pi board\" width=\"409\" height=\"450\" /> The LED aligned with the outline on the board.[/caption]</li>\r\n \t<li>Plug the other end of the Grove cable into the slot marked D12/D13 on the Pi2Grover board.You are now finished assembling the hardware. Now it’s time for the Python software.\r\n\r\n[caption id=\"attachment_264881\" align=\"aligncenter\" width=\"535\"]<img class=\"wp-image-264881 size-full\" src=\"https://www.dummies.com/wp-content/uploads/python-hello-world.jpg\" alt=\"Hello World Python\" width=\"535\" height=\"477\" /> The completed “Hello World” project.[/caption]</li>\r\n</ol>","blurb":"","authors":[{"authorId":26709,"name":"Alan Shovic","slug":"alan-shovic","description":"","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/26709"}},{"authorId":26710,"name":"John Shovic","slug":"john-shovic","description":"John Shovic, PhD, is a computer science faculty member at the University of Idaho specializing in robotics and artificial intelligence.","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/26710"}}],"primaryCategoryTaxonomy":{"categoryId":33606,"title":"Python","slug":"python","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33606"}},"secondaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"tertiaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"trendingArticles":[{"articleId":192609,"title":"How to Pray the Rosary: A Comprehensive Guide","slug":"how-to-pray-the-rosary","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/192609"}},{"articleId":208741,"title":"Kabbalah For Dummies Cheat Sheet","slug":"kabbalah-for-dummies-cheat-sheet","categoryList":["body-mind-spirit","religion-spirituality","kabbalah"],"_links":{"self":"/articles/208741"}},{"articleId":230957,"title":"Nikon D3400 For Dummies Cheat Sheet","slug":"nikon-d3400-dummies-cheat-sheet","categoryList":["home-auto-hobbies","photography"],"_links":{"self":"/articles/230957"}},{"articleId":235851,"title":"Praying the Rosary and Meditating on the Mysteries","slug":"praying-rosary-meditating-mysteries","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/235851"}},{"articleId":284787,"title":"What Your Society Says About You","slug":"what-your-society-says-about-you","categoryList":["academics-the-arts","humanities"],"_links":{"self":"/articles/284787"}}],"inThisArticle":[{"label":"GPIO pins on the Raspberry Pi","target":"#tab1"},{"label":"GPIO Python libraries","target":"#tab2"},{"label":"The hardware for “Hello World” on the Raspberry Pi","target":"#tab3"},{"label":"How to assemble the Raspberry Pi’s hardware","target":"#tab4"}],"relatedArticles":{"fromBook":[{"articleId":264919,"title":"How to Define and Use Python Lists","slug":"how-to-define-and-use-python-lists","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264919"}},{"articleId":264911,"title":"How to Use Lambda Functions in Python","slug":"how-to-use-lambda-functions-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264911"}},{"articleId":264906,"title":"Your Guide to the Python Standard Library","slug":"your-guide-to-the-python-standard-library","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264906"}},{"articleId":264894,"title":"A Beginner’s Guide to Python Versions","slug":"a-beginners-guide-to-python-versions","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264894"}},{"articleId":264888,"title":"How to Build a Simple Neural Network in Python","slug":"how-to-build-a-simple-neural-network-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264888"}}],"fromCategory":[{"articleId":264919,"title":"How to Define and Use Python Lists","slug":"how-to-define-and-use-python-lists","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264919"}},{"articleId":264911,"title":"How to Use Lambda Functions in Python","slug":"how-to-use-lambda-functions-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264911"}},{"articleId":264906,"title":"Your Guide to the Python Standard Library","slug":"your-guide-to-the-python-standard-library","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264906"}},{"articleId":264894,"title":"A Beginner’s Guide to Python Versions","slug":"a-beginners-guide-to-python-versions","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264894"}},{"articleId":264888,"title":"How to Build a Simple Neural Network in Python","slug":"how-to-build-a-simple-neural-network-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264888"}}]},"hasRelatedBookFromSearch":false,"relatedBook":{"bookId":281833,"slug":"python-all-in-one-for-dummies","isbn":"9781119787600","categoryList":["technology","programming-web-design","python"],"amazon":{"default":"https://www.amazon.com/gp/product/1119787602/ref=as_li_tl?ie=UTF8&tag=wiley01-20","ca":"https://www.amazon.ca/gp/product/1119787602/ref=as_li_tl?ie=UTF8&tag=wiley01-20","indigo_ca":"http://www.tkqlhce.com/click-9208661-13710633?url=https://www.chapters.indigo.ca/en-ca/books/product/1119787602-item.html&cjsku=978111945484","gb":"https://www.amazon.co.uk/gp/product/1119787602/ref=as_li_tl?ie=UTF8&tag=wiley01-20","de":"https://www.amazon.de/gp/product/1119787602/ref=as_li_tl?ie=UTF8&tag=wiley01-20"},"image":{"src":"https://www.dummies.com/wp-content/uploads/python-all-in-one-for-dummies-2e-cover-9781119787600-203x255.jpg","width":203,"height":255},"title":"Python All-in-One For Dummies","testBankPinActivationLink":"","bookOutOfPrint":true,"authorsInfo":"<p><b>John Shovic, PhD,</b> is a computer science faculty member at the University of Idaho specializing in robotics and artificial intelligence.</p> <p><b>Alan Simpson</b> is a web development professional who has published more than 100 articles and books on technology.</p> <p><b>John Shovic, PhD,</b> is a computer science faculty member at the University of Idaho specializing in robotics and artificial intelligence.</p> <p><b><b data-author-id=\"10199\">Alan Simpson</b></b> is a web development professional who has published more than 100 articles and books on technology.</p>","authors":[{"authorId":34775,"name":"John C. Shovic","slug":"john-c-shovic","description":" <p><b>John Shovic, PhD,</b> is a computer science faculty member at the University of Idaho specializing in robotics and artificial intelligence.</p> <p><b>Alan Simpson</b> is a web development professional who has published more than 100 articles and books on technology.</p> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/34775"}},{"authorId":10199,"name":"Alan Simpson","slug":"alan-simpson","description":" <p><b>John Shovic, PhD,</b> is a computer science faculty member at the University of Idaho specializing in robotics and artificial intelligence.</p> <p><b>Alan Simpson</b> is a web development professional who has published more than 100 articles and books on technology.</p> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/10199"}}],"_links":{"self":"https://dummies-api.dummies.com/v2/books/"}},"collections":[],"articleAds":{"footerAd":"<div class=\"du-ad-region row\" id=\"article_page_adhesion_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_adhesion_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;python&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119787600&quot;]}]\" id=\"du-slot-64ac4760ad979\"></div></div>","rightAd":"<div class=\"du-ad-region row\" id=\"article_page_right_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_right_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;python&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119787600&quot;]}]\" id=\"du-slot-64ac4760ae26c\"></div></div>"},"articleType":{"articleType":"Articles","articleList":null,"content":null,"videoInfo":{"videoId":null,"name":null,"accountId":null,"playerId":null,"thumbnailUrl":null,"description":null,"uploadDate":null}},"sponsorship":{"sponsorshipPage":false,"backgroundImage":{"src":null,"width":0,"height":0},"brandingLine":"","brandingLink":"","brandingLogo":{"src":null,"width":0,"height":0},"sponsorAd":"","sponsorEbookTitle":"","sponsorEbookLink":"","sponsorEbookImage":{"src":null,"width":0,"height":0}},"primaryLearningPath":"Advance","lifeExpectancy":"Five years","lifeExpectancySetFrom":"2023-07-10T00:00:00+00:00","dummiesForKids":"no","sponsoredContent":"no","adInfo":"","adPairKey":[]},"status":"publish","visibility":"public","articleId":264872},{"headers":{"creationTime":"2018-03-06T13:13:43+00:00","modifiedTime":"2023-07-07T15:21:06+00:00","timestamp":"2023-07-07T18:01:05+00:00"},"data":{"breadcrumbs":[{"name":"Technology","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33512"},"slug":"technology","categoryId":33512},{"name":"Programming & Web Design","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33592"},"slug":"programming-web-design","categoryId":33592},{"name":"Python","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33606"},"slug":"python","categoryId":33606}],"title":"How Permanent Storage Works for Python Programming","strippedTitle":"how permanent storage works for python programming","slug":"understanding-permanent-storage-works-python-programming","canonicalUrl":"","seo":{"metaDescription":"You don’t need to understand absolutely every detail about how permanent storage works with Python in order to use it. For example, just how the drive spins (as","noIndex":0,"noFollow":0},"content":"You don’t need to understand absolutely every detail about how permanent storage works with Python in order to use it. For example, just how the drive spins (assuming that it spins at all) is unimportant. However, most platforms adhere to a basic set of principles when it comes to permanent storage. These principles have developed over a period of time, starting with mainframe systems in the earliest days of computing.\r\n\r\nData is generally stored in <em>files</em> (with pure data representing application state information), but you could also find it stored as <em>objects</em> (a method of storing serialized class instances)<em>.</em> probably know about files already because almost every useful application out there relies on them. For example, when you open a document in your word processor, you’re actually opening a data file containing the words that you or someone else has typed.\r\n\r\nFiles typically have an <em>extension</em> associated with them that defines the file type. The extension is generally standardized for any given application and is separated from the filename by a period, such as <code>MyData.txt</code>. In this case, <code>.txt</code> is the file extension, and you probably have an application on your machine for opening such files. In fact, you can likely choose from a number of applications to perform the task because the <code>.txt</code> file extension is relatively common.\r\n\r\nInternally, files structure the data in some specific manner to make it easy to write and read data to and from the file. Any application you write must know about the file structure in order to interact with the data the file contains. File structures can become quite complex.\r\n<p class=\"article-tips remember\">Files would be nearly impossible to find if you placed them all in the same location on the hard drive. Consequently, files are organized into directories. Many newer computer systems also use the term folder for this organizational feature of permanent storage. No matter what you call it, permanent storage relies on directories to help organize the data and make individual files significantly easier to find. To find a particular file so that you can open it and interact with the data it contains, you must know which directory holds the file.</p>\r\nDirectories are arranged in hierarchies that begin at the uppermost level of the hard drive. For example, when working with the downloadable source code for this book, you find the code for the entire book in the <code>BPPD</code> directory within the user folder on your system. On a Windows system, that directory hierarchy is <code>C:\\Users\\John\\BPPD</code>. However, other Mac and Linux systems have a different directory hierarchy to reach the same <code>BPPD</code> directory, and the directory hierarchy on your system will be different as well.\r\n\r\nNotice that you use a backslash (\\) to separate the directory levels. <a href=\"http://blog.johnmuellerbooks.com/2014/03/10/backslash-versus-forward-slash/\">Some platforms use the forward slash (/); others use the backslash</a>. The book uses backslashes when appropriate and assumes that you'll make any required changes for your platform.\r\n\r\nA final consideration for Python developers (at least for this book) is that the hierarchy of directories is called a <em>path.</em> You see the term <em>path</em> in a few places in this book because Python must be able to find any resources you want to use based on the path you provide. For example, <code>C:\\Users\\John\\BPPD</code> is the complete path to the source code on a Windows system. A path that traces the entire route that Python must search is called an <em>absolute path.</em> An incomplete path that traces the route to a resource using the current directory as a starting point is called a <em>relative path</em>.\r\n<p class=\"article-tips tech\">To find a location using a relative path, you commonly use the current directory as the starting point. For example, <code>BPPD\\__pycache__</code> would be the relative path to the Python cache. Note that it has no drive letter or beginning backslash. However, sometimes you must add to the starting point in specific ways to define a relative path. Most platforms define these special relative path character sets:</p>\r\n\r\n<ul>\r\n \t<li><code>\\</code>: The root directory of the current drive. The drive is relative, but the path begins at the root, the uppermost part, of that drive.</li>\r\n \t<li><code>.\\</code>: The current directory. You use this shorthand for the current directory when the current directory name isn't known. For example, you could also define the location of the Python cache as <code>.\\__pycache__</code>.</li>\r\n \t<li><code>..\\</code>: The parent directory. You use this shorthand when the parent directory name isn't known.</li>\r\n \t<li><code>..\\..\\</code>: The parent of the parent directory. You can proceed up the hierarchy of directories as far as necessary to locate a particular starting point before you drill back down the hierarchy to a new location.</li>\r\n</ul>","description":"You don’t need to understand absolutely every detail about how permanent storage works with Python in order to use it. For example, just how the drive spins (assuming that it spins at all) is unimportant. However, most platforms adhere to a basic set of principles when it comes to permanent storage. These principles have developed over a period of time, starting with mainframe systems in the earliest days of computing.\r\n\r\nData is generally stored in <em>files</em> (with pure data representing application state information), but you could also find it stored as <em>objects</em> (a method of storing serialized class instances)<em>.</em> probably know about files already because almost every useful application out there relies on them. For example, when you open a document in your word processor, you’re actually opening a data file containing the words that you or someone else has typed.\r\n\r\nFiles typically have an <em>extension</em> associated with them that defines the file type. The extension is generally standardized for any given application and is separated from the filename by a period, such as <code>MyData.txt</code>. In this case, <code>.txt</code> is the file extension, and you probably have an application on your machine for opening such files. In fact, you can likely choose from a number of applications to perform the task because the <code>.txt</code> file extension is relatively common.\r\n\r\nInternally, files structure the data in some specific manner to make it easy to write and read data to and from the file. Any application you write must know about the file structure in order to interact with the data the file contains. File structures can become quite complex.\r\n<p class=\"article-tips remember\">Files would be nearly impossible to find if you placed them all in the same location on the hard drive. Consequently, files are organized into directories. Many newer computer systems also use the term folder for this organizational feature of permanent storage. No matter what you call it, permanent storage relies on directories to help organize the data and make individual files significantly easier to find. To find a particular file so that you can open it and interact with the data it contains, you must know which directory holds the file.</p>\r\nDirectories are arranged in hierarchies that begin at the uppermost level of the hard drive. For example, when working with the downloadable source code for this book, you find the code for the entire book in the <code>BPPD</code> directory within the user folder on your system. On a Windows system, that directory hierarchy is <code>C:\\Users\\John\\BPPD</code>. However, other Mac and Linux systems have a different directory hierarchy to reach the same <code>BPPD</code> directory, and the directory hierarchy on your system will be different as well.\r\n\r\nNotice that you use a backslash (\\) to separate the directory levels. <a href=\"http://blog.johnmuellerbooks.com/2014/03/10/backslash-versus-forward-slash/\">Some platforms use the forward slash (/); others use the backslash</a>. The book uses backslashes when appropriate and assumes that you'll make any required changes for your platform.\r\n\r\nA final consideration for Python developers (at least for this book) is that the hierarchy of directories is called a <em>path.</em> You see the term <em>path</em> in a few places in this book because Python must be able to find any resources you want to use based on the path you provide. For example, <code>C:\\Users\\John\\BPPD</code> is the complete path to the source code on a Windows system. A path that traces the entire route that Python must search is called an <em>absolute path.</em> An incomplete path that traces the route to a resource using the current directory as a starting point is called a <em>relative path</em>.\r\n<p class=\"article-tips tech\">To find a location using a relative path, you commonly use the current directory as the starting point. For example, <code>BPPD\\__pycache__</code> would be the relative path to the Python cache. Note that it has no drive letter or beginning backslash. However, sometimes you must add to the starting point in specific ways to define a relative path. Most platforms define these special relative path character sets:</p>\r\n\r\n<ul>\r\n \t<li><code>\\</code>: The root directory of the current drive. The drive is relative, but the path begins at the root, the uppermost part, of that drive.</li>\r\n \t<li><code>.\\</code>: The current directory. You use this shorthand for the current directory when the current directory name isn't known. For example, you could also define the location of the Python cache as <code>.\\__pycache__</code>.</li>\r\n \t<li><code>..\\</code>: The parent directory. You use this shorthand when the parent directory name isn't known.</li>\r\n \t<li><code>..\\..\\</code>: The parent of the parent directory. You can proceed up the hierarchy of directories as far as necessary to locate a particular starting point before you drill back down the hierarchy to a new location.</li>\r\n</ul>","blurb":"","authors":[{"authorId":9109,"name":"John Paul Mueller","slug":"john-paul-mueller","description":" <p><b> John Mueller</b> has published more than 100 books on technology, data, and programming. John has a website and blog where he writes articles on technology and offers assistance alongside his published books.</p> <p><b>Luca Massaron</b> is a data scientist specializing in insurance and finance. A Google Developer Expert in machine learning, he has been involved in quantitative analysis and algorithms since 2000. ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/9109"}}],"primaryCategoryTaxonomy":{"categoryId":33606,"title":"Python","slug":"python","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33606"}},"secondaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"tertiaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"trendingArticles":[{"articleId":192609,"title":"How to Pray the Rosary: A Comprehensive Guide","slug":"how-to-pray-the-rosary","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/192609"}},{"articleId":208741,"title":"Kabbalah For Dummies Cheat Sheet","slug":"kabbalah-for-dummies-cheat-sheet","categoryList":["body-mind-spirit","religion-spirituality","kabbalah"],"_links":{"self":"/articles/208741"}},{"articleId":230957,"title":"Nikon D3400 For Dummies Cheat Sheet","slug":"nikon-d3400-dummies-cheat-sheet","categoryList":["home-auto-hobbies","photography"],"_links":{"self":"/articles/230957"}},{"articleId":235851,"title":"Praying the Rosary and Meditating on the Mysteries","slug":"praying-rosary-meditating-mysteries","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/235851"}},{"articleId":284787,"title":"What Your Society Says About You","slug":"what-your-society-says-about-you","categoryList":["academics-the-arts","humanities"],"_links":{"self":"/articles/284787"}}],"inThisArticle":[],"relatedArticles":{"fromBook":[{"articleId":250588,"title":"How to Get Additional Python Libraries","slug":"get-additional-python-libraries","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/250588"}},{"articleId":250582,"title":"Printing Lists Using Python","slug":"printing-lists-using-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/250582"}},{"articleId":250575,"title":"Extending Python Classes to Make New Classes","slug":"extending-python-classes-make-new-classes","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/250575"}},{"articleId":250571,"title":"Understanding the Python Class as a Packaging Method","slug":"understanding-python-class-packaging-method","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/250571"}},{"articleId":250567,"title":"Working with Deques in Python","slug":"working-deques-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/250567"}}],"fromCategory":[{"articleId":264919,"title":"How to Define and Use Python Lists","slug":"how-to-define-and-use-python-lists","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264919"}},{"articleId":264911,"title":"How to Use Lambda Functions in Python","slug":"how-to-use-lambda-functions-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264911"}},{"articleId":264906,"title":"Your Guide to the Python Standard Library","slug":"your-guide-to-the-python-standard-library","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264906"}},{"articleId":264894,"title":"A Beginner’s Guide to Python Versions","slug":"a-beginners-guide-to-python-versions","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264894"}},{"articleId":264888,"title":"How to Build a Simple Neural Network in Python","slug":"how-to-build-a-simple-neural-network-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264888"}}]},"hasRelatedBookFromSearch":false,"relatedBook":{"bookId":281830,"slug":"beginning-programming-with-python-for-dummies-2nd-edition","isbn":"9781119913771","categoryList":["technology","programming-web-design","python"],"amazon":{"default":"https://www.amazon.com/gp/product/1119913772/ref=as_li_tl?ie=UTF8&tag=wiley01-20","ca":"https://www.amazon.ca/gp/product/1119913772/ref=as_li_tl?ie=UTF8&tag=wiley01-20","indigo_ca":"http://www.tkqlhce.com/click-9208661-13710633?url=https://www.chapters.indigo.ca/en-ca/books/product/1119913772-item.html&cjsku=978111945484","gb":"https://www.amazon.co.uk/gp/product/1119913772/ref=as_li_tl?ie=UTF8&tag=wiley01-20","de":"https://www.amazon.de/gp/product/1119913772/ref=as_li_tl?ie=UTF8&tag=wiley01-20"},"image":{"src":"https://www.dummies.com/wp-content/uploads/beginning-programming-with-python-for-dummies-3rd-edition-cover-9781119913771-203x255.jpg","width":203,"height":255},"title":"Beginning Programming with Python For Dummies","testBankPinActivationLink":"","bookOutOfPrint":true,"authorsInfo":"<p><p><b> John Mueller</b> has published more than 100 books on technology, data, and programming. John has a website and blog where he writes articles on technology and offers assistance alongside his published books.</p> <p><b>Luca Massaron</b> is a data scientist specializing in insurance and finance. A Google Developer Expert in machine learning, he has been involved in quantitative analysis and algorithms since 2000.</p>","authors":[{"authorId":9109,"name":"John Paul Mueller","slug":"john-paul-mueller","description":" <p><b> John Mueller</b> has published more than 100 books on technology, data, and programming. John has a website and blog where he writes articles on technology and offers assistance alongside his published books.</p> <p><b>Luca Massaron</b> is a data scientist specializing in insurance and finance. A Google Developer Expert in machine learning, he has been involved in quantitative analysis and algorithms since 2000. ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/9109"}}],"_links":{"self":"https://dummies-api.dummies.com/v2/books/"}},"collections":[],"articleAds":{"footerAd":"<div class=\"du-ad-region row\" id=\"article_page_adhesion_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_adhesion_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;python&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119913771&quot;]}]\" id=\"du-slot-64a852e143a9e\"></div></div>","rightAd":"<div class=\"du-ad-region row\" id=\"article_page_right_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_right_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;python&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119913771&quot;]}]\" id=\"du-slot-64a852e144363\"></div></div>"},"articleType":{"articleType":"Articles","articleList":null,"content":null,"videoInfo":{"videoId":null,"name":null,"accountId":null,"playerId":null,"thumbnailUrl":null,"description":null,"uploadDate":null}},"sponsorship":{"sponsorshipPage":false,"backgroundImage":{"src":null,"width":0,"height":0},"brandingLine":"","brandingLink":"","brandingLogo":{"src":null,"width":0,"height":0},"sponsorAd":"","sponsorEbookTitle":"","sponsorEbookLink":"","sponsorEbookImage":{"src":null,"width":0,"height":0}},"primaryLearningPath":"Advance","lifeExpectancy":"Two years","lifeExpectancySetFrom":"2023-07-07T00:00:00+00:00","dummiesForKids":"no","sponsoredContent":"no","adInfo":"","adPairKey":[]},"status":"publish","visibility":"public","articleId":250578},{"headers":{"creationTime":"2016-03-26T07:16:02+00:00","modifiedTime":"2022-10-19T14:16:44+00:00","timestamp":"2022-10-19T15:01:03+00:00"},"data":{"breadcrumbs":[{"name":"Technology","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33512"},"slug":"technology","categoryId":33512},{"name":"Programming & Web Design","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33592"},"slug":"programming-web-design","categoryId":33592},{"name":"Python","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33606"},"slug":"python","categoryId":33606}],"title":"How to Install Python on Your Computer","strippedTitle":"how to install python on your computer","slug":"how-to-install-python-on-your-computer","canonicalUrl":"","seo":{"metaDescription":"Whether you use a Mac, Windows, or Linux OS (operating system), you can find and install Python on your computer. The following sections give you instructions f","noIndex":0,"noFollow":0},"content":"Whether you use a Mac, Windows, or Linux OS (operating system), you can find and install <a href=\"https://www.dummies.com/article/technology/programming-web-design/python/write-a-simple-program-in-python-139547/\">Python </a>on your computer. The following sections give you instructions for each OS.\r\n<h2 id=\"tab1\" >How to install Python on Mac OSX</h2>\r\nTo find and start Python on Mac OSX computers, follow these steps:\r\n<ol class=\"level-one\">\r\n \t<li>\r\n<p class=\"first-para\">Press Cmd+spacebar to open Spotlight.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\">Type the word <span class=\"code\">terminal</span>.</p>\r\n<p class=\"child-para\">Or, from the Finder, select Finder→Go→Utilities→Terminal.</p>\r\n<p class=\"child-para\">The Terminal window opens.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\">In the terminal, type <span class=\"code\">python</span>.</p>\r\n<p class=\"child-para\">The Python interpreter that's built in to Mac OSX opens.</p>\r\n</li>\r\n</ol>\r\n<h2 id=\"tab2\" >How to install Python on Windows</h2>\r\nUnfortunately, Python doesn't come on Windows. If you're running Windows, then you need to download and install Python by following the instructions here. Installing Python on Windows isn't difficult. If you can download a file from a website, you have the skills to install Python.\r\n\r\nFortunately, the Python Foundation (the peeps who guide the development of Python) makes installable files available from its website.\r\n<p class=\"Tip\">Firefox and Internet Explorer responded differently to the Python download website, so the instructions are based on which of these browsers you use. If you use a whole other browser altogether, try the Internet Explorer instructions.</p>\r\n\r\n<h3>Installing with Firefox</h3>\r\nTo install Python on a Windows machine with Firefox, follow these steps:\r\n<ol class=\"level-one\">\r\n \t<li>\r\n<p class=\"first-para\">Visit <a href=\"http://www.python.org/downloads\" target=\"_blank\" rel=\"noopener\">www.python.org/downloads</a>.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\">Click the button that says Download Python 2.7.9.</p>\r\n<p class=\"child-para\">Or, if it's there, click a more recent version number that starts with 2.7.</p>\r\n<p class=\"child-para\">Clicking this button automatically downloads and saves an <span class=\"code\">msi</span> file for you. If not, try the instructions for Internet Explorer. See Figure 1.</p>\r\n\r\n<div class=\"imageBlock\" style=\"width: 535px;\">\r\n\r\n<img src=\"https://www.dummies.com/wp-content/uploads/497374.image0.png\" alt=\"<b>Figure 1</b><b>:</b> Download Python with Firefox.\" width=\"535\" height=\"448\" />\r\n<div class=\"imageCaption\"><b>Figure 1</b><b>:</b> Download Python with Firefox.</div>\r\n</div></li>\r\n \t<li>\r\n<p class=\"first-para\">When the download's complete, click the icon for Firefox's download tool.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\">Click the file called <span class=\"code\">python-2.7.9.msi</span> (or the more recent version, if you downloaded one).</p>\r\n<p class=\"child-para\">Python 2.7.9 installs on your computer.</p>\r\n</li>\r\n</ol>\r\n<h3>Installing with Internet Explorer</h3>\r\nTo install Python on a Windows machine with Internet Explorer, follow these steps:\r\n<ol class=\"level-one\">\r\n \t<li>\r\n<p class=\"first-para\">Visit <a href=\"http://www.python.org/downloads\" target=\"_blank\" rel=\"noopener\">www.python.org/downloads</a>.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\">From the menu bar, select Downloads→Windows.</p>\r\n<p class=\"child-para\">You can see the menu options in Figure 2.</p>\r\n\r\n<div class=\"imageBlock\" style=\"width: 535px;\">\r\n\r\n<img src=\"https://www.dummies.com/wp-content/uploads/497375.image1.png\" alt=\"<b>Figure </b><b>2:</b> Download Python with Internet Explorer.\" width=\"535\" height=\"304\" />\r\n<div class=\"imageCaption\"><b>Figure </b><b>2:</b> Download Python with Internet Explorer.</div>\r\n</div></li>\r\n \t<li>\r\n<p class=\"first-para\">Scroll down to the heading Python 2.7.9-2014-12-10.</p>\r\n<p class=\"child-para\">Or scroll to a more recent version, which starts with Python 2.7, if one is available.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\">Under this heading, click the link titled <span class=\"code\">Download Windows x86 MSI Installer</span>.</p>\r\n<p class=\"child-para\">See Figure 3. This is a link for a 32-bit installation, which makes things work better with third-party libraries. Use the 32-bit installer even if you have a 64-bit machine and even if you have no idea what this paragraph is talking about.</p>\r\n\r\n<div class=\"imageBlock\" style=\"width: 535px;\">\r\n\r\n<img src=\"https://www.dummies.com/wp-content/uploads/497376.image2.png\" alt=\"<b>Figure </b><b>3:</b> Python x86 MSI Installer.\" width=\"535\" height=\"464\" />\r\n<div class=\"imageCaption\"><b>Figure </b><b>3:</b> Python x86 MSI Installer.</div>\r\n</div></li>\r\n</ol>\r\n<ol class=\"level-one\">\r\n \t<li>\r\n<p class=\"first-para\">If you're asked to choose whether to run or save the file, choose Run.</p>\r\n<p class=\"child-para\">This downloads <span class=\"code\">python2.7.9.msi</span> and starts running the installer.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\">If you get a security warning when the installer begins (or at random times during the installation), choose Run.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\">Accept the default installation options that the installer provides.</p>\r\n</li>\r\n</ol>\r\n<h2 id=\"tab3\" >How to install Python for Linux</h2>\r\n<p class=\"Warning\">If you're running Linux, confirm that you have version 2.7.9 of Python installed, rather than version 3. This shouldn't be a problem because Python 2.7 is installed by default in recent versions of OpenSuSE, Ubuntu, and Red Hat Fedora.</p>\r\nIn the nutty odd case when someone has Python 3 but not Python 2.7, read your distribution's documentation for how to use the package manager and get Python 2.7 and IDLE.","description":"Whether you use a Mac, Windows, or Linux OS (operating system), you can find and install <a href=\"https://www.dummies.com/article/technology/programming-web-design/python/write-a-simple-program-in-python-139547/\">Python </a>on your computer. The following sections give you instructions for each OS.\r\n<h2 id=\"tab1\" >How to install Python on Mac OSX</h2>\r\nTo find and start Python on Mac OSX computers, follow these steps:\r\n<ol class=\"level-one\">\r\n \t<li>\r\n<p class=\"first-para\">Press Cmd+spacebar to open Spotlight.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\">Type the word <span class=\"code\">terminal</span>.</p>\r\n<p class=\"child-para\">Or, from the Finder, select Finder→Go→Utilities→Terminal.</p>\r\n<p class=\"child-para\">The Terminal window opens.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\">In the terminal, type <span class=\"code\">python</span>.</p>\r\n<p class=\"child-para\">The Python interpreter that's built in to Mac OSX opens.</p>\r\n</li>\r\n</ol>\r\n<h2 id=\"tab2\" >How to install Python on Windows</h2>\r\nUnfortunately, Python doesn't come on Windows. If you're running Windows, then you need to download and install Python by following the instructions here. Installing Python on Windows isn't difficult. If you can download a file from a website, you have the skills to install Python.\r\n\r\nFortunately, the Python Foundation (the peeps who guide the development of Python) makes installable files available from its website.\r\n<p class=\"Tip\">Firefox and Internet Explorer responded differently to the Python download website, so the instructions are based on which of these browsers you use. If you use a whole other browser altogether, try the Internet Explorer instructions.</p>\r\n\r\n<h3>Installing with Firefox</h3>\r\nTo install Python on a Windows machine with Firefox, follow these steps:\r\n<ol class=\"level-one\">\r\n \t<li>\r\n<p class=\"first-para\">Visit <a href=\"http://www.python.org/downloads\" target=\"_blank\" rel=\"noopener\">www.python.org/downloads</a>.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\">Click the button that says Download Python 2.7.9.</p>\r\n<p class=\"child-para\">Or, if it's there, click a more recent version number that starts with 2.7.</p>\r\n<p class=\"child-para\">Clicking this button automatically downloads and saves an <span class=\"code\">msi</span> file for you. If not, try the instructions for Internet Explorer. See Figure 1.</p>\r\n\r\n<div class=\"imageBlock\" style=\"width: 535px;\">\r\n\r\n<img src=\"https://www.dummies.com/wp-content/uploads/497374.image0.png\" alt=\"<b>Figure 1</b><b>:</b> Download Python with Firefox.\" width=\"535\" height=\"448\" />\r\n<div class=\"imageCaption\"><b>Figure 1</b><b>:</b> Download Python with Firefox.</div>\r\n</div></li>\r\n \t<li>\r\n<p class=\"first-para\">When the download's complete, click the icon for Firefox's download tool.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\">Click the file called <span class=\"code\">python-2.7.9.msi</span> (or the more recent version, if you downloaded one).</p>\r\n<p class=\"child-para\">Python 2.7.9 installs on your computer.</p>\r\n</li>\r\n</ol>\r\n<h3>Installing with Internet Explorer</h3>\r\nTo install Python on a Windows machine with Internet Explorer, follow these steps:\r\n<ol class=\"level-one\">\r\n \t<li>\r\n<p class=\"first-para\">Visit <a href=\"http://www.python.org/downloads\" target=\"_blank\" rel=\"noopener\">www.python.org/downloads</a>.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\">From the menu bar, select Downloads→Windows.</p>\r\n<p class=\"child-para\">You can see the menu options in Figure 2.</p>\r\n\r\n<div class=\"imageBlock\" style=\"width: 535px;\">\r\n\r\n<img src=\"https://www.dummies.com/wp-content/uploads/497375.image1.png\" alt=\"<b>Figure </b><b>2:</b> Download Python with Internet Explorer.\" width=\"535\" height=\"304\" />\r\n<div class=\"imageCaption\"><b>Figure </b><b>2:</b> Download Python with Internet Explorer.</div>\r\n</div></li>\r\n \t<li>\r\n<p class=\"first-para\">Scroll down to the heading Python 2.7.9-2014-12-10.</p>\r\n<p class=\"child-para\">Or scroll to a more recent version, which starts with Python 2.7, if one is available.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\">Under this heading, click the link titled <span class=\"code\">Download Windows x86 MSI Installer</span>.</p>\r\n<p class=\"child-para\">See Figure 3. This is a link for a 32-bit installation, which makes things work better with third-party libraries. Use the 32-bit installer even if you have a 64-bit machine and even if you have no idea what this paragraph is talking about.</p>\r\n\r\n<div class=\"imageBlock\" style=\"width: 535px;\">\r\n\r\n<img src=\"https://www.dummies.com/wp-content/uploads/497376.image2.png\" alt=\"<b>Figure </b><b>3:</b> Python x86 MSI Installer.\" width=\"535\" height=\"464\" />\r\n<div class=\"imageCaption\"><b>Figure </b><b>3:</b> Python x86 MSI Installer.</div>\r\n</div></li>\r\n</ol>\r\n<ol class=\"level-one\">\r\n \t<li>\r\n<p class=\"first-para\">If you're asked to choose whether to run or save the file, choose Run.</p>\r\n<p class=\"child-para\">This downloads <span class=\"code\">python2.7.9.msi</span> and starts running the installer.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\">If you get a security warning when the installer begins (or at random times during the installation), choose Run.</p>\r\n</li>\r\n \t<li>\r\n<p class=\"first-para\">Accept the default installation options that the installer provides.</p>\r\n</li>\r\n</ol>\r\n<h2 id=\"tab3\" >How to install Python for Linux</h2>\r\n<p class=\"Warning\">If you're running Linux, confirm that you have version 2.7.9 of Python installed, rather than version 3. This shouldn't be a problem because Python 2.7 is installed by default in recent versions of OpenSuSE, Ubuntu, and Red Hat Fedora.</p>\r\nIn the nutty odd case when someone has Python 3 but not Python 2.7, read your distribution's documentation for how to use the package manager and get Python 2.7 and IDLE.","blurb":"","authors":[{"authorId":9026,"name":"Brendan Scott","slug":"brendan-scott","description":" <p>Brendan Scott is a dad who loves Python and wants kids to get some of its magic too. He started pythonforkids.brendanscott.com to help teach his oldest child to code. He maintains it to help other young people learn Python.</p> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/9026"}}],"primaryCategoryTaxonomy":{"categoryId":33606,"title":"Python","slug":"python","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33606"}},"secondaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"tertiaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"trendingArticles":[{"articleId":192609,"title":"How to Pray the Rosary: A Comprehensive Guide","slug":"how-to-pray-the-rosary","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/192609"}},{"articleId":208741,"title":"Kabbalah For Dummies Cheat Sheet","slug":"kabbalah-for-dummies-cheat-sheet","categoryList":["body-mind-spirit","religion-spirituality","kabbalah"],"_links":{"self":"/articles/208741"}},{"articleId":230957,"title":"Nikon D3400 For Dummies Cheat Sheet","slug":"nikon-d3400-dummies-cheat-sheet","categoryList":["home-auto-hobbies","photography"],"_links":{"self":"/articles/230957"}},{"articleId":235851,"title":"Praying the Rosary and Meditating on the Mysteries","slug":"praying-rosary-meditating-mysteries","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/235851"}},{"articleId":284787,"title":"What Your Society Says About You","slug":"what-your-society-says-about-you","categoryList":["academics-the-arts","humanities"],"_links":{"self":"/articles/284787"}}],"inThisArticle":[{"label":"How to install Python on Mac OSX","target":"#tab1"},{"label":"How to install Python on Windows","target":"#tab2"},{"label":"How to install Python for Linux","target":"#tab3"}],"relatedArticles":{"fromBook":[{"articleId":207407,"title":"Python For Kids For Dummies Cheat Sheet","slug":"python-for-kids-for-dummies-cheat-sheet","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/207407"}},{"articleId":141581,"title":"Use Python to Help with Your Math Homework","slug":"use-python-to-help-with-your-math-homework","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/141581"}},{"articleId":141474,"title":"Python 2.7 Keyword Subset and Examples","slug":"python-2-7-keyword-subset-and-examples","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/141474"}},{"articleId":141443,"title":"Using Tkinter Widgets in Python","slug":"using-tkinter-widgets-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/141443"}},{"articleId":139551,"title":"How to Interrupt a Program in Python","slug":"how-to-interrupt-a-program-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/139551"}}],"fromCategory":[{"articleId":264919,"title":"How to Define and Use Python Lists","slug":"how-to-define-and-use-python-lists","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264919"}},{"articleId":264911,"title":"How to Use Lambda Functions in Python","slug":"how-to-use-lambda-functions-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264911"}},{"articleId":264906,"title":"Your Guide to the Python Standard Library","slug":"your-guide-to-the-python-standard-library","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264906"}},{"articleId":264894,"title":"A Beginner’s Guide to Python Versions","slug":"a-beginners-guide-to-python-versions","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264894"}},{"articleId":264888,"title":"How to Build a Simple Neural Network in Python","slug":"how-to-build-a-simple-neural-network-in-python","categoryList":["technology","programming-web-design","python"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/264888"}}]},"hasRelatedBookFromSearch":false,"relatedBook":{"bookId":281835,"slug":"python-for-kids-for-dummies","isbn":"9781119093107","categoryList":["technology","programming-web-design","python"],"amazon":{"default":"https://www.amazon.com/gp/product/1119093104/ref=as_li_tl?ie=UTF8&tag=wiley01-20","ca":"https://www.amazon.ca/gp/product/1119093104/ref=as_li_tl?ie=UTF8&tag=wiley01-20","indigo_ca":"http://www.tkqlhce.com/click-9208661-13710633?url=https://www.chapters.indigo.ca/en-ca/books/product/1119093104-item.html&cjsku=978111945484","gb":"https://www.amazon.co.uk/gp/product/1119093104/ref=as_li_tl?ie=UTF8&tag=wiley01-20","de":"https://www.amazon.de/gp/product/1119093104/ref=as_li_tl?ie=UTF8&tag=wiley01-20"},"image":{"src":"https://www.dummies.com/wp-content/uploads/python-for-kids-for-dummies-cover-9781119093107-203x255.jpg","width":203,"height":255},"title":"Python For Kids For Dummies","testBankPinActivationLink":"","bookOutOfPrint":false,"authorsInfo":"<p>Brendan Scott is a dad who loves Python and wants kids to get some of its magic too. He started pythonforkids.brendanscott.com to help teach his oldest child to code. He maintains it to help other young people learn Python.</p>","authors":[{"authorId":9026,"name":"Brendan Scott","slug":"brendan-scott","description":" <p>Brendan Scott is a dad who loves Python and wants kids to get some of its magic too. He started pythonforkids.brendanscott.com to help teach his oldest child to code. He maintains it to help other young people learn Python.</p> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/9026"}}],"_links":{"self":"https://dummies-api.dummies.com/v2/books/"}},"collections":[],"articleAds":{"footerAd":"<div class=\"du-ad-region row\" id=\"article_page_adhesion_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_adhesion_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;python&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119093107&quot;]}]\" id=\"du-slot-6350112fa2eea\"></div></div>","rightAd":"<div class=\"du-ad-region row\" id=\"article_page_right_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_right_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;python&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119093107&quot;]}]\" id=\"du-slot-6350112fa36e5\"></div></div>"},"articleType":{"articleType":"Articles","articleList":null,"content":null,"videoInfo":{"videoId":null,"name":null,"accountId":null,"playerId":null,"thumbnailUrl":null,"description":null,"uploadDate":null}},"sponsorship":{"sponsorshipPage":false,"backgroundImage":{"src":null,"width":0,"height":0},"brandingLine":"","brandingLink":"","brandingLogo":{"src":null,"width":0,"height":0},"sponsorAd":"","sponsorEbookTitle":"","sponsorEbookLink":"","sponsorEbookImage":{"src":null,"width":0,"height":0}},"primaryLearningPath":"Explore","lifeExpectancy":"Two years","lifeExpectancySetFrom":"2022-01-25T00:00:00+00:00","dummiesForKids":"no","sponsoredContent":"no","adInfo":"","adPairKey":[]},"status":"publish","visibility":"public","articleId":139548}],"_links":{"self":{"self":"https://dummies-api.dummies.com/v2/categories/33606/categoryArticles?sortField=time&sortOrder=1&size=10&offset=0"},"next":{"self":"https://dummies-api.dummies.com/v2/categories/33606/categoryArticles?sortField=time&sortOrder=1&size=10&offset=10"},"last":{"self":"https://dummies-api.dummies.com/v2/categories/33606/categoryArticles?sortField=time&sortOrder=1&size=10&offset=74"}}},"objectTitle":"","status":"success","pageType":"article-category","objectId":"33606","page":1,"sortField":"time","sortOrder":1,"categoriesIds":[],"articleTypes":[],"filterData":{"categoriesFilter":[{"itemId":0,"itemName":"All Categories","count":83}],"articleTypeFilter":[{"articleType":"All Types","count":83},{"articleType":"Articles","count":74},{"articleType":"Cheat Sheet","count":4},{"articleType":"Step by Step","count":5}]},"filterDataLoadedStatus":"success","pageSize":10},"adsState":{"pageScripts":{"headers":{"timestamp":"2025-04-17T15:50:01+00:00"},"adsId":0,"data":{"scripts":[{"pages":["all"],"location":"header","script":"<!--Optimizely Script-->\r\n<script src=\"https://cdn.optimizely.com/js/10563184655.js\"></script>","enabled":false},{"pages":["all"],"location":"header","script":"<!-- comScore Tag -->\r\n<script>var _comscore = _comscore || [];_comscore.push({ c1: \"2\", c2: \"15097263\" });(function() {var s = document.createElement(\"script\"), el = document.getElementsByTagName(\"script\")[0]; s.async = true;s.src = (document.location.protocol == \"https:\" ? \"https://sb\" : \"http://b\") + \".scorecardresearch.com/beacon.js\";el.parentNode.insertBefore(s, el);})();</script><noscript><img src=\"https://sb.scorecardresearch.com/p?c1=2&c2=15097263&cv=2.0&cj=1\" /></noscript>\r\n<!-- / comScore Tag -->","enabled":true},{"pages":["all"],"location":"footer","script":"<!--BEGIN QUALTRICS WEBSITE FEEDBACK SNIPPET-->\r\n<script type='text/javascript'>\r\n(function(){var g=function(e,h,f,g){\r\nthis.get=function(a){for(var a=a+\"=\",c=document.cookie.split(\";\"),b=0,e=c.length;b<e;b++){for(var d=c[b];\" \"==d.charAt(0);)d=d.substring(1,d.length);if(0==d.indexOf(a))return d.substring(a.length,d.length)}return null};\r\nthis.set=function(a,c){var b=\"\",b=new Date;b.setTime(b.getTime()+6048E5);b=\"; expires=\"+b.toGMTString();document.cookie=a+\"=\"+c+b+\"; path=/; \"};\r\nthis.check=function(){var a=this.get(f);if(a)a=a.split(\":\");else if(100!=e)\"v\"==h&&(e=Math.random()>=e/100?0:100),a=[h,e,0],this.set(f,a.join(\":\"));else return!0;var c=a[1];if(100==c)return!0;switch(a[0]){case \"v\":return!1;case \"r\":return c=a[2]%Math.floor(100/c),a[2]++,this.set(f,a.join(\":\")),!c}return!0};\r\nthis.go=function(){if(this.check()){var a=document.createElement(\"script\");a.type=\"text/javascript\";a.src=g;document.body&&document.body.appendChild(a)}};\r\nthis.start=function(){var t=this;\"complete\"!==document.readyState?window.addEventListener?window.addEventListener(\"load\",function(){t.go()},!1):window.attachEvent&&window.attachEvent(\"onload\",function(){t.go()}):t.go()};};\r\ntry{(new g(100,\"r\",\"QSI_S_ZN_5o5yqpvMVjgDOuN\",\"https://zn5o5yqpvmvjgdoun-wiley.siteintercept.qualtrics.com/SIE/?Q_ZID=ZN_5o5yqpvMVjgDOuN\")).start()}catch(i){}})();\r\n</script><div id='ZN_5o5yqpvMVjgDOuN'><!--DO NOT REMOVE-CONTENTS PLACED HERE--></div>\r\n<!--END WEBSITE FEEDBACK SNIPPET-->","enabled":false},{"pages":["all"],"location":"header","script":"<!-- Hotjar Tracking Code for http://www.dummies.com -->\r\n<script>\r\n (function(h,o,t,j,a,r){\r\n h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};\r\n h._hjSettings={hjid:257151,hjsv:6};\r\n a=o.getElementsByTagName('head')[0];\r\n r=o.createElement('script');r.async=1;\r\n r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv;\r\n a.appendChild(r);\r\n })(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv=');\r\n</script>","enabled":false},{"pages":["article"],"location":"header","script":"<!-- //Connect Container: dummies --> <script src=\"//get.s-onetag.com/bffe21a1-6bb8-4928-9449-7beadb468dae/tag.min.js\" async defer></script>","enabled":true},{"pages":["homepage"],"location":"header","script":"<meta name=\"facebook-domain-verification\" content=\"irk8y0irxf718trg3uwwuexg6xpva0\" />","enabled":true},{"pages":["homepage","article","category","search"],"location":"footer","script":"<!-- Facebook Pixel Code -->\r\n<noscript>\r\n<img height=\"1\" width=\"1\" src=\"https://www.facebook.com/tr?id=256338321977984&ev=PageView&noscript=1\"/>\r\n</noscript>\r\n<!-- End Facebook Pixel Code -->","enabled":true}]}},"pageScriptsLoadedStatus":"success"},"navigationState":{"navigationCollections":[{"collectionId":287568,"title":"BYOB (Be Your Own Boss)","hasSubCategories":false,"url":"/collection/for-the-entry-level-entrepreneur-287568"},{"collectionId":293237,"title":"Be a Rad Dad","hasSubCategories":false,"url":"/collection/be-the-best-dad-293237"},{"collectionId":295890,"title":"Career Shifting","hasSubCategories":false,"url":"/collection/career-shifting-295890"},{"collectionId":294090,"title":"Contemplating the Cosmos","hasSubCategories":false,"url":"/collection/theres-something-about-space-294090"},{"collectionId":287563,"title":"For Those Seeking Peace of Mind","hasSubCategories":false,"url":"/collection/for-those-seeking-peace-of-mind-287563"},{"collectionId":287570,"title":"For the Aspiring Aficionado","hasSubCategories":false,"url":"/collection/for-the-bougielicious-287570"},{"collectionId":291903,"title":"For the Budding Cannabis Enthusiast","hasSubCategories":false,"url":"/collection/for-the-budding-cannabis-enthusiast-291903"},{"collectionId":299891,"title":"For the College Bound","hasSubCategories":false,"url":"/collection/for-the-college-bound-299891"},{"collectionId":291934,"title":"For the Exam-Season Crammer","hasSubCategories":false,"url":"/collection/for-the-exam-season-crammer-291934"},{"collectionId":301547,"title":"For the Game Day Prepper","hasSubCategories":false,"url":"/collection/big-game-day-prep-made-easy-301547"}],"navigationCollectionsLoadedStatus":"success","navigationCategories":{"books":{"0":{"data":[{"categoryId":33512,"title":"Technology","hasSubCategories":true,"url":"/category/books/technology-33512"},{"categoryId":33662,"title":"Academics & The Arts","hasSubCategories":true,"url":"/category/books/academics-the-arts-33662"},{"categoryId":33809,"title":"Home, Auto, & Hobbies","hasSubCategories":true,"url":"/category/books/home-auto-hobbies-33809"},{"categoryId":34038,"title":"Body, Mind, & Spirit","hasSubCategories":true,"url":"/category/books/body-mind-spirit-34038"},{"categoryId":34224,"title":"Business, Careers, & Money","hasSubCategories":true,"url":"/category/books/business-careers-money-34224"}],"breadcrumbs":[],"categoryTitle":"Level 0 Category","mainCategoryUrl":"/category/books/level-0-category-0"}},"articles":{"0":{"data":[{"categoryId":33512,"title":"Technology","hasSubCategories":true,"url":"/category/articles/technology-33512"},{"categoryId":33662,"title":"Academics & The Arts","hasSubCategories":true,"url":"/category/articles/academics-the-arts-33662"},{"categoryId":33809,"title":"Home, Auto, & Hobbies","hasSubCategories":true,"url":"/category/articles/home-auto-hobbies-33809"},{"categoryId":34038,"title":"Body, Mind, & Spirit","hasSubCategories":true,"url":"/category/articles/body-mind-spirit-34038"},{"categoryId":34224,"title":"Business, Careers, & Money","hasSubCategories":true,"url":"/category/articles/business-careers-money-34224"}],"breadcrumbs":[],"categoryTitle":"Level 0 Category","mainCategoryUrl":"/category/articles/level-0-category-0"}}},"navigationCategoriesLoadedStatus":"success"},"searchState":{"searchList":[],"searchStatus":"initial","relatedArticlesList":[],"relatedArticlesStatus":"initial"},"routeState":{"name":"ArticleCategory","path":"/category/articles/python-33606/","hash":"","query":{},"params":{"category":"python-33606"},"fullPath":"/category/articles/python-33606/","meta":{"routeType":"category","breadcrumbInfo":{"suffix":"Articles","baseRoute":"/category/articles"},"prerenderWithAsyncData":true},"from":{"name":null,"path":"/","hash":"","query":{},"params":{},"fullPath":"/","meta":{}}},"profileState":{"auth":{},"userOptions":{},"status":"success"}}
Logo
  • Articles Open Article Categories
  • Books Open Book Categories
  • Collections Open Collections list
  • Custom Solutions

Article Categories

Book Categories

Collections

Explore all collections
BYOB (Be Your Own Boss)
Be a Rad Dad
Career Shifting
Contemplating the Cosmos
For Those Seeking Peace of Mind
For the Aspiring Aficionado
For the Budding Cannabis Enthusiast
For the College Bound
For the Exam-Season Crammer
For the Game Day Prepper
Log In
  • Home
  • Technology Articles
  • Programming & Web Design Articles
  • Python Articles

Python Articles

Don't be scared, it's not poisonous. Python is one of the easiest languages you can learn. Check out our articles on Python here.

Articles From Python

page 1
page 2
page 3
page 4
page 5
page 6
page 7
page 8
page 9

Filter Results

84 results
84 results
Python How to Define and Use Python Lists

Article / Updated 10-28-2024

The simplest data collection in Python is a list. A list is any list of data items, separated by commas, inside square brackets. Typically, you assign a name to the Python list using an = sign, just as you would with variables. If the list contains numbers, then don't use quotation marks around them. For example, here is a list of test scores: scores = [88, 92, 78, 90, 98, 84] If the list contains strings then, as always, those strings should be enclosed in single or double quotation marks, as in this example: To display the contents of a list on the screen, you can print it just as you would print any regular variable. For example, executing print(students) in your code after defining that list shows this on the screen. ['Mark', 'Amber', 'Todd', 'Anita', 'Sandy'] This may not be exactly what you had in mind. But don’t worry, Python offers lots of great ways to access data in lists and display it however you like. Referencing Python list items by position Each item in a list has a position number, starting with zero, even though you don’t see any numbers. You can refer to any item in the list by its number using the name for the list followed by a number in square brackets. In other words, use this syntax: <em>listname</em>[<em>x</em>] Replace <em><code>listname</code></em> with the name of the list you're accessing and replace <em><code>x</code></em> with the position number of item you want. Remember, the first item is always number zero, not one. For example, in the first line below, I define a list named <code>students</code>, and then print item number zero from that list. The result, when executing the code, is that the name <code>Mark</code> is displayed. students = ["Mark", "Amber", "Todd", "Anita", "Sandy"] print(students[0]) Mark When reading access list items, professionals use the word sub before the number. For example, students[0] would be spoken as students sub zero. This next example shows a list named scores. The print() function prints the position number of the last score in the list, which is 4 (because the first one is always zero). scores = [88, 92, 78, 90, 84] print(scores[4]) 84 If you try to access a list item that doesn't exist, you get an “index out of range” error. The index part is a reference to the number inside the square brackets. For example, the image below shows a little experiment in a Jupyter notebook where a list of scores was created and then the printing of score[5] was attempted. It failed and generated an error because there is no scores[5]. There's only scores[0], scores[1], scores[2], scores[3], and scores[4] because the counting always starts at zero with the first one on the list. Looping through a Python list To access each item in a list, just use a for loop with this syntax: for <em>x</em> in <em>list</em>: Replace >x with a variable name of your choosing. Replace list with the name of the list. An easy way to make the code readable is to always use a plural for the list name (such as students, scores). Then you can use the singular name (student, score) for the variable name. You don't need to use subscript numbers (numbers in square brackets) with this approach either. For example, the following code prints each score in the scores list: for score in scores: print(score) Remember to always indent the code that’s to be executed within the loop. This image shows a more complete example where you can see the result of running the code in a Jupyter notebook. Seeing whether a Python list contains an item If you want your code to check the contents of a list to see whether it already contains some item, use in <em>listname</em> in an if statement or a variable assignment. For example, the code in the image below creates a list of names. Then, two variables store the results of searching the list for the names Anita and Bob. Printing the contents of each variable shows True for the one where the name (Anita) is in the list. The test to see whether Bob is in the list proves False. Getting the length of a Python list To determine how many items are in a list, use the len() function (short for length). Put the name of the list inside the parentheses. For example, type the following code into a Jupyter notebook or Python prompt or whatever: students = ["Mark", "Amber", "Todd", "Anita", "Sandy"] print(len(students)) Running that code produces this output: 5 There are indeed five items in the list, though the last one is always one less than the number because Python starts counting at zero. So the last one, Sandy, actually refers to students[4] and not students[5]. Appending an item to the end of a Python list When you want your Python code to add a new item to the end of a list, use the .append() method with the value you want to add inside the parentheses. You can use either a variable name or a literal value inside the quotation marks. For instance, in the following image the line that reads students.append("Goober") adds the name Goober to the list. The line that reads students.append(new_student) adds whatever name is stored in the variable named new_student to the list. The .append() method always adds to the end of the list. So when you print the list you see those two new names at the end. You can use a test to see whether an item is in a list and then append it only when the item isn't already there. For example, the code below won’t add the name Amber to the list because that name is already in the list: student_name = "Amanda" #Add student_name but only if not already in the list. if student_name in students: print (student_name + " already in the list") else: students.append(student_name) print (student_name + " added to the list") Inserting an item into a Python list Although the append() method allows you to add an item to the end of a list, the insert() method allows you to add an item to the list in any position. The syntax for insert() is <em>listname</em>.insert(<em>position</em>, <em>item</em>) Replace listname with the name of the list, position with the position at which you want to insert the item (for example, 0 to make it the first item, 1 to make it the second item, and so forth). Replace item with the value, or the name of a variable that contains the value, that you want to put into the list. For example, the following code makes Lupe the first item in the list: #Create a list of strings (names). students = ["Mark", "Amber", "Todd", "Anita", "Sandy"] student_name = "Lupe" # Add student name to front of the list. students.insert(0,student_name) #Show me the new list. print(students) If you run the code, print(students) will show the list after the new name has been inserted, as follows: ['Lupe', 'Mark', 'Amber', 'Todd', 'Anita', 'Sandy'] Changing an item in a Python list You can change an item in a list using the = assignment operator (check out these common Python operators) just like you do with variables. Just make sure you include the index number in square brackets of the item you want to change. The syntax is: listname[index]=newvalue Replace listname with the name of the list; replace index with the subscript (index number) of the item you want to change; and replace newvalue with whatever you want to put in the list item. For example, take a look at this code: #Create a list of strings (names). students = ["Mark", "Amber", "Todd", "Anita", "Sandy"] students[3] = "Hobart" print(students) When you run this code, the output is as follows, because Anita's name has been changed to Hobart. ['Mark', 'Amber', 'Todd', 'Hobart', 'Sandy'] Combining Python lists If you have two lists that you want to combine into a single list, use the extend() function with the syntax: <em>original_list</em>.extend(<em>additional_items_list</em>) In your code, replace original_list with the name of the list to which you’ll be adding new list items. Replace additional_items_list with the name of the list that contains the items you want to add to the first list. Here is a simple example using lists named list1 and list2. After executing list1.extend(list2), the first list contains the items from both lists, as you can see in the output of the print() statement at the end. # Create two lists of Names. list1 = ["Zara", "Lupe", "Hong", "Alberto", "Jake"] list2 = ["Huey", "Dewey", "Louie", "Nader", "Bubba"] # Add list2 names to list1. list1.extend(list2) # Print list 1. print(list1) ['Zara', 'Lupe', 'Hong', 'Alberto', 'Jake', 'Huey', 'Dewey', 'Louie', 'Nader', 'Bubba'] Easy Parcheesi, no? Removing Python list items Python offers a remove() method so you can remove any value from the list. If the item is in the list multiple times, only the first occurrence is removed. For example, the following code shows a list of letters with the letter C repeated a few times. Then the code uses letters.remove("C") to remove the letter C from the list: # Remove "C" from the list. letters.remove("C") #Show me the new list. print(letters) When you actually execute this code and then print the list, you'll see that only the first letter C has been removed: ['A', 'B', 'D', 'C', 'E', 'C'] If you need to remove all of an item, you can use a while loop to repeat the .remove as long as the item still remains in the list. For example, this code repeats the .remove as long as the “C” is still in the list. #Create a list of strings. letters = ["A", "B", "C", "D", "C", "E", "C"] If you want to remove an item based on its position in the list, use pop() with an index number rather than remove() with a value. If you want to remove the last item from the list, use pop() without an index number. For example, the following code creates a list, one line removes the first item (0), and another removes the last item (pop() with nothing in the parentheses). Printing the list shows those two items have been removed: #Create a list of strings. letters = ["A", "B", "C", "D", "E", "F", "G"] #Remove the first item. letters.pop(0) #Remove the last item. letters.pop() #Show me the new list. print(letters) Running the code shows that the popping the first and last items did, indeed, work: ['B', 'C', 'D', 'E', 'F'] When you pop() an item off the list, you can store a copy of that value in some variable. For example this image shows the same code as above. However, it stores copies of what's been removed in variables named first_removed and last_removed. At the end it prints the Python list, and also shows which letters were removed. Python also offers a del (short for delete) command that deletes any item from a list based on its index number (position). But again, you have to remember that the first item is zero. So, let's say you run the following code to delete item number 2 from the list: # Create a list of strings. letters = ["A", "B", "C", "D", "E", "F", "G"] # Remove item sub 2. del letters[2] print(letters) Running that code shows the list again, as follows. The letter C has been deleted, which is the correct item to delete because letters are numbered 0, 1, 2, 3, and so forth. ['A', 'B', 'D', 'E', 'F', 'G'] You can also use del to delete an entire list. Just don’t use the square brackets and the index number. For example, the code you see below creates a list then deletes it. Trying to print the list after the deletion causes an error, because the list no longer exists when the print() statement is executed. Clearing out a Python list If you want to delete the contents of a list but not the list itself, use .clear(). The list still exists; however, it contains no items. In other words, it's an empty list. The following code shows how you could test this. Running the code displays [] at the end, which lets you know the list is empty: # Create a list of strings. letters = ["A", "B", "C", "D", "E", "F", "G"] # Clear the list of all entries. letters.clear() # Show me the new list. print(letters) Counting how many times an item appears in a Python list You can use the Python count() method to count how many times an item appears in a list. As with other list methods, the syntax is simple: <em>listname</em>.count(<em>x</em>) Replace listname with the name of your list, and x with the value you're looking for (or the name of a variable that contains that value). The code in the image below counts how many times the letter B appears in the list, using a literal B inside the parentheses of .count(). This same code also counts the number of C grades, but that value was stored in a variable just to show the difference in syntax. Both counts worked, as you can see in the output of the program at the bottom. One was added to count the F's, not using any variables. The F’s were counted right in the code that displays the message. There are no F grades, so this returns zero, as you can see in the output. When trying to combine numbers and strings to form a message, remember you have to convert the numbers to strings using the str() function. Otherwise, you get an error that reads something like can only concatenate str (not "int") to str. In that message, int is short for integer, and str is short for string. Finding a Python list item's index Python offers an .index() method that returns a number indicating the position, based on index number, of an item in a list. The syntax is: <em>listname</em>.index(<em>x</em>) As always, replace listname with name of the list you want to search. Replace x what whatever you're looking for (either as a literal or as a variable name, as always). Of course, there’s no guarantee that the item is in the list, and even if it is, there’s no guarantee that the item is in the list only once. If the item isn’t in the list, then an error occurs. If the item is in the list multiple times, then the index of the first matching item is returned. The following image shows an example where the program crashes at the line f_index = grades.index(look_for) because there is no F in the list. An easy way to get around that problem is to use an if statement to see whether an item is in the list before you try to get its index number. If the item isn't in the list, display a message saying so. Otherwise, get the index number and show it in a message. That code is as follows: # Create a list of strings. grades = ["C", "B", "A", "D", "C", "B", "C"] # Decide what to look for look_for = "F" # See if the item is in the list. if look_for in grades: # If it's in the list, get and show the index. print(str(look_for) + " is at index " + str(grades.index(look_for))) else: # If not in the list, don't even try for index number. print(str(look_for) + " isn't in the list.") Alphabetizing and sorting Python lists Python offers a sort() method for sorting lists. In its simplest form, it alphabetizes the items in the list (if they’re strings). If the list contains numbers, they’re sorted smallest to largest. For a simple sort like that, just use sort() with empty parentheses: <em>listname</em>.sort() Replace listname with the name of your list. The following image shows an example using a list of strings and a list of numbers. In the example, a new list was created for each of them simply by assigning each sorted list to a new list name. Then the code prints the contents of each sorted list. If your list contains strings with a mixture of uppercase and lowercase letters, and if the results of the sort don't look right, try replacing .sort() with .sort(key=lambda s:s.lower()) and then running the code again. Dates are a little trickier because you can’t just type them in as strings, like "12/31/2020". They have to be the date data type to sort correctly. This means using the datetime module and the date() method to define each date. You can add the dates to the list as you would any other list. For example, in the following line, the code creates a list of four dates, and the code is perfectly fine. dates = [dt.date(2020,12,31), dt.date(2019,1,31), dt.date(2018,2,28), dt.date(2020,1,1)] The computer certainly won't mind if you create the list this way. But if you want to make the code more readable to yourself or other developers, you may want to create and append each date, one at a time, so just so it’s a little easier to see what’s going on and so you don’t have to deal with so many commas in one line of code. The image below shows an example where an empty list named datelist was created: datelist = [] Then one date at a time was appended to the list using the dt.date(<em>year</em>,<em>month</em>,<em>day</em>) syntax. After the list is created, the code uses datelist.sort() to sort them into chronological order (earliest to latest). You don’t need to use print(datelist) in that code because that method displays the dates with the data type information included, like this: [datetime.date(2018, 2, 28), datetime.date(2019, 1, 31), datetime.date (2020, 1, 1), datetime.date(2020, 12, 31)] Not the easiest list to read. So, rather than print the whole list with one print() statement, you can loop through each date in the list, and printed each one formatted with the f-string %m/%d/%Y. This displays each date on its own line in mm/dd/yyyy format, as you can see at the bottom of the image above. If you want to sort items in reverse order, put reverse=True inside the sort() parentheses (and don't forget to make the first letter uppercase). The image below shows examples of sorting all three lists in descending (reverse) order using reverse=True. Reversing a Python list You can also reverse the order of items in a list using the .reverse method. This is not the same as sorting in reverse, because when you sort in reverse, you still actually sort: Z–A for strings, largest to smallest for numbers, latest to earliest for dates. When you reverse a list, you simply reverse the items in the list, no matter their order, without trying to sort them in any way. The following code shows an example in which you reverse the order of the names in the list and then print the list. The output shows the list items reversed from their original order: # Create a list of strings. names = ["Zara", "Lupe", "Hong", "Alberto", "Jake"] # Reverse the list names.reverse() # Print the list print(names) ['Jake', 'Alberto', 'Hong', 'Lupe', 'Zara'] Copying a Python list If you ever need to work with a copy of a list, use the .copy() method so as not to alter the original list,. For example, the following code is similar to the preceding code, except that instead of reversing the order of the original list, you make a copy of the list and reverse that one. Printing the contents of each list shows how the first list is still in the original order whereas the second one is reversed: # Create a list of strings. names = ["Zara", "Lupe", "Hong", "Alberto", "Jake"] # Make a copy of the list backward_names = names.copy() # Reverse the copy backward_names.reverse() # Print the list print(names) print(backward_names) ['Zara', 'Lupe', 'Hong', 'Alberto', 'Jake'] ['Jake', 'Alberto', 'Hong', 'Lupe', 'Zara'] For future references, the following table summarizes the methods you've learned about. Methods for Working with Lists Method What it Does append() Adds an item to the end of the list. clear() Removes all items from the list, leaving it empty. copy() Makes a copy of a list. count() Counts how many times an element appears in a list. extend() Appends the items from one list to the end of another list. index() Returns the index number (position) of an element within a list. insert() Inserts an item into the list at a specific position. pop() Removes an element from the list, and provides a copy of that item that you can store in a variable. remove() Removes one item from the list. reverse() Reverses the order of items in the list. sort() Sorts the list in ascending order. Put reverse=True inside the parentheses to sort in descending order.

View Article
Python Python All-in-One For Dummies Cheat Sheet

Cheat Sheet / Updated 04-12-2024

Python is a flexible programming language that has become increasingly popular in the past few years. This cheat sheet is designed to give you a handy resource for common Python data types, Python operators, and Python functions. It includes Python data types, operators, special characters, f-strings, and functions for working with robots.

View Cheat Sheet
Python Python 2.7 Keyword Subset and Examples

Article / Updated 10-04-2023

Programming is an important skill. Python will serve you well for years to come. The tables here give you the core words, built-ins, standard library functions, and operators that you'll use most when you're coding with Python. Python Core Words KeywordSummaryExample and Logical operator to test whether two things are both True. andx>2 and x<10 as Assign a file object to a variable. Used with with.Let your code refer to a module under a different name (also called an alias). Used with import. with open(<name of file>,<file mode>) as <object name>:import cPickle as pickle break Stop execution of a loop. for i in range(10): if i%2 ==0: break class Define a custom object. class <name of class>(object): ""Your docstring"" class MyClass(object): ""A cool function."" continue Skip balance of loop and begin a new iteration. for i in range(10): if i%2 ==0: continue def Define a function. def <name of function>(): ""Your docstring"" def my_function(): ""This does... "" elif Add conditional test to an if clause. See if. else Add an alternative code block. See if. for Create a loop which iterates through elements of a list (or other iterable). for <dummy variable name> in <sequence>:for i in range(10): from Import specific functions from a module without importing the whole module. from <module name> import <name of function or object>from random import randint global Make a variable global in scope. (If a variable is defined in the main section, you can change its value within a function.) global x if Create a condition. If the condition is True, the associated code block is executed. Otherwise, any elif commands are processed. If there are none, or none are satisfied, execute the else block if there is one. if : [elif : , ...][else: ]if x == 1: print("x is 1")elif x == 2: print("x is 2")elif x > 3: print("x is greater than 3")else print("x is not greater than 3, nor is it 1 one or 2") import Use code defined in another file without retyping it. import <name of module>import random in Used to test whether a given value is one of the elements of an object. 1 in range(10) is Used to test whether names reference the same object. x = Nonex is None # faster thanx == None lambda Shorthand function definition. Usually used where a function needs to be passed as an argument to another function. lamda :times = lambda x, y: x*ycommand=lambda x: self.draw_line(self.control_points) not Logical negation, used to negate a logical condition. Don't use for testing greater than, less than, or equal. 10 not in range(10) or Logical operator to test whether at least one of two things is True. orx<2 or x>10 pass Placeholder keyword. Does nothing but stop Python complaining that a code block is empty. for i in range (10): pass print Output text to a terminal. print("Hello World!") return Return from the execution of a function. If a value is specified, return that value, otherwise return None. return return x+2 while Execute a code block while the associated condition is True. while :while True: pass with Get Python to manage a resource (like a file) for you. with open(,) as : Extend Python's core functionality with these built-ins. Python Built-ins Built-inNotesExample False Value, returned by a logical operation or directly assigned. ok_to_continue = Falseage = 16old_enough = age >=21(evaluates comparison age>=21 and assigns the result to old_enough) None Value used when representing the absence of a value or to initialise a variable which will be changed later. Returned by functions which do not explicitly return a value. x = None True Value, returned by a logical operation. ok_to_continue = Trueage = 16old_enough = age >=21(evaluates comparison age>=21 and assigns the result to old_enough) __name__ Constant, shows module name. If it's not "__main__", the code is being used in an import. if __name__=="__main__": dir List attributes of an item. dir(<object name>) enumerate Iterate through a sequence and number each item. enumerate('Hello') exit Exit Python (Command Line) interpreter. exit() float Convert a number into a decimal, usually so that division works properly. 1/float(2) getattr Get an attribute of an object by a name. Useful for introspection. getattr(<name of object>, <name of attribute>) help Get Python docstring on object. help(<name of object>)help(getattr) id Show the location in the computer's RAM where an object is stored. id(<name of object>)id(help) int Convert a string into an integer number. int('0') len Get the number of elements in a sequence. len([0,1]) object A base on which other classes can inherit from. class CustomObject(object): open Open a file on disk, return a file object. open(, )open('mydatafile.txt', 'r') # read(opens a file to read data from)open('mydatafile.txt', 'w') # write(creates a new file to write to, destroys any existing file with the same name)open('mydatafile.txt', 'a') # append(adds to an existing file if any, or createsa new one if none existing already) print Reimplementation of print keyword, but as a function.Need to import from the future to use it (srsly!) from future import print_functionprint ('Hello World!') range Gives numbers between the lower and upper limits specified (including the lower, but excluding the upper limit). A step may be specified. range(10)range(5,10)range(1,10,2) raw_input Get some text as a string from the user, with an optional prompt. prompt = 'What is your guess? 'players_guess = raw_input(prompt) str Convert an object (usually a number) into a string (usually for printing). str(0) type Give the type of the specified object. type(0)type('0')type([])type({})type(()) Use the work that others have already done. Try these modules from the Python standard library. Selected Functions from the Standard Library ModuleWhat It DoesSample Functions/Objects os.path Functions relating to files and file paths. os.path.exists() pickle, cPickle Save and load objects to/from a file. pickle.load(), pickle.dump(, ) random Various functions relating to random numbers. random.choice(), random.randint(, ), random.shuffle() String Stuff relating to strings. string.printable sys Various functions related to your computer system. sys.exit() Time Time-related functions. time.time() Tkinter User interface widgets and associated constants. Tkinter.ALLTkinter.BOTHTkinter.CENTERTkinter.ENDTkinter.HORIZONTALTkinter.LEFTTkinter.NWTkinter.RIGHTTkinter.TOPTkinter.YTkinter.Button(,text=)Tkinter.Canvas(, width=, height=)Tkinter.Checkbutton(, text=)Tkinter.Entry(, width=),Tkinter.Frame()Tkinter.IntVar()Tkinter.Label(, text = )Tkinter.mainloop()Tkinter.Menu()Tkinter.OptionMenu(, None, None)Tkinter.Scale(, from_=, to=)Tkinter.Scrollbar()Tkinter.StringVar()Tkinter.Tk() Add, subtract, divide, multiply, and more using these operators. Python Operators OperatorNameEffectExamples + Plus Add two numbers.Join two strings together. Add: >>> 1+12Join: >>> 'a'+'b''ab' – Minus Subtract a number from another.Can't use for strings. >>> 1-10 * Times Multiply two numbers.Make copies of a string. Multiply: >>> 2*24Copy: >>> 'a'*2'aa' / Divide Divide one number by another.Can't use for strings. 1/2 # integer division:Answer will be rounded down.1/2.0 # decimal division1/float(2) # decimal division % Remainder (Modulo) Give the remainder when dividing the left number by the right number.Formatting operator for strings. >>> 10%31 ** Power x**y means raise x to the power of y.Can't use for strings. >>> 3**29 = Assignment Assign the value on the right to the variable on the left. >>> a = 1 == Equality Is the left side equal to the right side? Is True if so; is False otherwise. >>> 1 == 1True>>> 'a' == 'a'True != Not equal Is the left side not equal to the right side? Is True if so; is False otherwise. >>> 1 != 1False>>> 1 != 2True>>> 'a' != 'a'True > Greater than Is the left side greater than the right side?>= means greater than or equal to >>> 2 > 1True < Less than Is the left side less than the right side?<= means less than or equal to >>> 1 < 2True & (or and) And Are both left and right True?Typically used for complex conditions where you want to do something if everything is True:while im_hungry and you_have_food: >>> True & TrueTrue>>> True and FalseFalse >>> True & (1 == 2)False | (or or) Or Is either left or right True?Typically used for complex conditions where you want at least one thing to be True:while im_bored or youre_bored: >>> True | FalseTrue>>> True or FalseTrue>>> False | FalseFalse>>> (1 == 1) | FalseTrue

View Article
Python Python for Data Science For Dummies Cheat Sheet

Cheat Sheet / Updated 10-03-2023

Python is an incredible programming language that you can use to perform data science tasks with a minimum of effort. The huge number of available libraries means that the low-level code you normally need to write is likely already available from some other source. All you need to focus on is getting the job done. With that in mind, this Cheat Sheet helps you access the most commonly needed reminders for making your programming experience fast and easy.

View Cheat Sheet
Python 8 Major Uses of Python

Article / Updated 09-13-2023

Many organizations are using Python these days to perform major tasks. You don't necessarily hear about them because organizations are usually reserved about giving out their trade secrets. However, Python is still there making a big difference in the way organizations work and toward keeping the bottom line from bottoming out. Following, are some major ways in which Python is used commercially that will make it easier to argue for using Python in your own organization. (Or you can read about some Python success stories.) Corel: PaintShop Pro is a product that many people have used over the years to grab screenshots, modify their pictures, draw new images, and perform a lot of other graphics-oriented tasks. The amazing thing about this product is that it relies heavily on Python scripting. In other words, to automate tasks in PaintShop Pro, you need to know Python. D-Link: Upgrading firmware over a network connection can be problematic, and D-Link was encountering a situation in which each upgrade was tying up a machine — a poor use of resources. In addition, some upgrades required additional work because of problems with the target device. Using Python to create a multithreaded application to drive updates to the devices allows one machine to service multiple devices, and a new methodology allowed by Python reduces the number of reboots to just one after that new firmware is installed. D-Link chose Python over other languages, such as Java, because it provides an easier-to-use serial communication code. Eve-Online: Games are a major business because so many people enjoy playing them. Eve-Online is a Massively Multiplayer Online Role Playing Game (MMORPG) that relies heavily on Python for both the client and server ends of the game. It actually relies on a Python variant named StacklessPython, which is important because you encounter these variants all the time when working with Python. Think of them as Python on steroids. These variants have all the advantages of Python, plus a few extra perks. The thing to take away from this particular company is that running an MMORPG takes major horsepower, and the company wouldn't have chosen Python unless it were actually up to the task. ForecastWatch.com: If you have ever wondered whether someone reviews the performance of your weatherman, look no further than ForecastWatch.com. This company compares the forecasts produced by thousands of weather forecasters each day against actual climatological data to determine their accuracy. The resulting reports are used to help improve weather forecasts. In this case, the software used to make the comparisons is written in pure Python because it comes with standard libraries useful in collecting, parsing, and storing data from online sources. In addition, Python's enhanced multithreading capabilities makes it possible to collect the forecasts from around 5,000 online sources each day. Most important of all, the code is much smaller than would have been needed by other languages such as Java or PHP. Frequentis: The next time you fly somewhere, you might be relying on Python to get you to the ground safely again. It turns out that Frequentis is the originator of TAPTools, a software product that is used for air traffic control in many airports. This particular tool provides updates on the weather and runway conditions to air traffic controllers. Honeywell: Documenting large systems is expensive and error prone. Honeywell uses Python to perform automated testing of applications, but it also uses Python to control a cooperative environment between applications used to generate documentation for the applications. The result is that Python helps generate the reports that form the documentation for the setup. Industrial Light & Magic: In this case, you find Python used in the production process for scripting complex, computer graphic-intensive films. Originally, Industrial Light & Magic relied on Unix shell scripting, but it was found that this solution just couldn't do the job. Python was compared to other languages, such as Tcl and Perl, and chosen because it's an easier-to-learn language that the organization can implement incrementally. In addition, Python can be embedded within a larger software system as a scripting language, even if the system is written in a language such as C/C++. It turns out that Python can successfully interact with these other languages in situations in which some languages can't. Philips: Automation is essential in the semiconductor industry, so imagine trying to coordinate the effort of thousands of robots. After a number of solutions, Philips decided to go with Python for the sequencing language (the language that tells what steps each robot should take). The low-level code is written in C++, which is another reason to use Python, because Python works well with C++.

View Article
Python Write a Simple Program in Python

Article / Updated 08-10-2023

Tradition dictates that Hello World! be the first program that you write when you're learning a new programming language like Python. You're following in the footsteps of many great programmers when you create this project. To create your Hello World! program, follow these steps: Open your Start menu and choose Python (command line). You should get a prompt that looks like >>>. At the moment, you're doing everything in interactive mode in the Python interpreter. That's where the >>> comes in. Python shows you >>> when you're supposed to type something. At the prompt, type the following. Use a single quote at the start and the end — it's beside the Enter key: print('Hello World!') Press the Enter key. Python runs the code you typed. You see the output shown in Figure 1. Congratulations — you've written your first program. Welcome to the Python-programmers-in-training club. If you don't see what's in Figure 1, check that you typed in the text from Step 2 exactly as it's written: Check that the parentheses and single quotes are in the right places. Check that for each opening parenthesis there is a closing parenthesis. (Otherwise, you're left hanging. Check that for each opening quote there's a closing quote. Programming languages have their own grammar and punctuation rules. These rules are the language's syntax. Humans, can work most stuff out even if perfect not you're is grammar (See? You figured out what that sentence was trying to say), but Python pretty much freaks out if you get the syntax wrong.

View Article
Python How to Spot and Fix Errors in Python

Article / Updated 08-10-2023

The Python interpreter takes in each line and operates on it immediately (more or less) after you press the Enter key. In Hello World! you use Python's print feature. print takes what's inside the parentheses and outputs it to the command line (also called the console). Python is sensitive to both the grammar and punctuation. If you misspell something, the program won't work. If Python is expecting special characters and you don't put them in, then Python will fail. Some Python issues are shown here. Can you work out how you would fix them? >>> pritn('Hello World!') Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'pritn' is not defined Here's another: >>> print('Hello World!) File "<stdin>", line 1 print('Hello World!) SyntaxError: EOL while scanning string literal Here's another: >>> print 'Hello World!') File "<stdin>", line 1 print 'Hello World!') ^ SyntaxError: invalid syntax Python tries to give you the reason it failed (that is, NameError and SyntaxError). Check each of these things: Opening parenthesis has a closing parenthesis Every opening quote mark has a matching closing quote mark All commands are correctly spelled

View Article
Python The Raspberry Pi: The Perfect PC Platform for Python

Article / Updated 07-10-2023

Before you can get going here, make sure you have your Raspberry Pi computer set up and running on your monitor, keyboard, and mouse. If not, go do that now The next few paragraphs are going to be lots more fun with a computer to work with! The Raspberry Pi is the perfect platform to do physical computing with Python because it has a multiscreen environment, lots of RAM and storage to play with and all the tools to build fun projects. A huge and powerful feature of the Raspberry Pi is the row of GPIO (general purpose input-output) pins along the top of the Raspberry Pi. It is a 40-pin header into which you can plug a large number of sensors and controllers to do amazing things to expand your Raspberry Pi. GPIO pins on the Raspberry Pi GPIO pins can be designated (using Python software) as input or output pins and used for many different purposes. There are two 5V power pins, two 3.3V power pins and a number of ground pins that have fixed uses. An GPIO pin output pin “outputs” a 1 or a 0 from the computer to the pin. Basically, A “1” is 3.3V and a “0” is 0V. You can think of them just as 1s and 0s. GPIO Python libraries There are a number of GPIO Python libraries that are usable for building projects. A good one to use is the gpiozero library that is installed on all Raspberry Pi desktop software releases. Check out the library documentation and installation instructions (if needed). Now let’s jump into the “Hello World” physical computing project with our Raspberry Pi. The hardware for “Hello World” on the Raspberry Pi To do this project, you’ll need some hardware. Because these instructions involve using Grove connectors, let's get the two pieces of Grove hardware that you need for this project: Pi2Grover: This converts the Raspberry Pi GPIO pin header to Grove connectors (ease of use and can’t reverse the power pins!). You can buy this either at shop.switchdoc.com or at Amazon.com. You can get $5.00 off the Pi2Grover board at shop.switchdoc.com by using the discount code PI2DUMMIES at checkout. Grove blue LED: A Grove blue LED module including Grove cable. You can buy this on shop.switchdoc.com or on amazon.com. How to assemble the Raspberry Pi’s hardware For a number of you readers, this will be the first time you have ever assembled a physical computer-based product. because of this, we’ll give you the step-by-step process: Identify the Pi2Grover board. Making sure you align the pins correctly gently press the Pi2Grover Board (Part A) onto the 40 pin GPIO connector on the Raspberry Pi. Gently finish pushing the Pi2Grover (Part A) onto the Raspberry Pi GPIO pins, making sure the pins are aligned. There will be no pins showing on either end and make sure no pins on the Raspberry Pi are bent. Plug one end of the Grove cable into the Grove blue LED board. If your blue LED is not plugged into the Grove blue LED board, then plug in the LED with the flat side aligned with the flat side of the outline on the board. Plug the other end of the Grove cable into the slot marked D12/D13 on the Pi2Grover board.You are now finished assembling the hardware. Now it’s time for the Python software.

View Article
Python How Permanent Storage Works for Python Programming

Article / Updated 07-07-2023

You don’t need to understand absolutely every detail about how permanent storage works with Python in order to use it. For example, just how the drive spins (assuming that it spins at all) is unimportant. However, most platforms adhere to a basic set of principles when it comes to permanent storage. These principles have developed over a period of time, starting with mainframe systems in the earliest days of computing. Data is generally stored in files (with pure data representing application state information), but you could also find it stored as objects (a method of storing serialized class instances). probably know about files already because almost every useful application out there relies on them. For example, when you open a document in your word processor, you’re actually opening a data file containing the words that you or someone else has typed. Files typically have an extension associated with them that defines the file type. The extension is generally standardized for any given application and is separated from the filename by a period, such as MyData.txt. In this case, .txt is the file extension, and you probably have an application on your machine for opening such files. In fact, you can likely choose from a number of applications to perform the task because the .txt file extension is relatively common. Internally, files structure the data in some specific manner to make it easy to write and read data to and from the file. Any application you write must know about the file structure in order to interact with the data the file contains. File structures can become quite complex. Files would be nearly impossible to find if you placed them all in the same location on the hard drive. Consequently, files are organized into directories. Many newer computer systems also use the term folder for this organizational feature of permanent storage. No matter what you call it, permanent storage relies on directories to help organize the data and make individual files significantly easier to find. To find a particular file so that you can open it and interact with the data it contains, you must know which directory holds the file. Directories are arranged in hierarchies that begin at the uppermost level of the hard drive. For example, when working with the downloadable source code for this book, you find the code for the entire book in the BPPD directory within the user folder on your system. On a Windows system, that directory hierarchy is C:\Users\John\BPPD. However, other Mac and Linux systems have a different directory hierarchy to reach the same BPPD directory, and the directory hierarchy on your system will be different as well. Notice that you use a backslash (\) to separate the directory levels. Some platforms use the forward slash (/); others use the backslash. The book uses backslashes when appropriate and assumes that you'll make any required changes for your platform. A final consideration for Python developers (at least for this book) is that the hierarchy of directories is called a path. You see the term path in a few places in this book because Python must be able to find any resources you want to use based on the path you provide. For example, C:\Users\John\BPPD is the complete path to the source code on a Windows system. A path that traces the entire route that Python must search is called an absolute path. An incomplete path that traces the route to a resource using the current directory as a starting point is called a relative path. To find a location using a relative path, you commonly use the current directory as the starting point. For example, BPPD\__pycache__ would be the relative path to the Python cache. Note that it has no drive letter or beginning backslash. However, sometimes you must add to the starting point in specific ways to define a relative path. Most platforms define these special relative path character sets: \: The root directory of the current drive. The drive is relative, but the path begins at the root, the uppermost part, of that drive. .\: The current directory. You use this shorthand for the current directory when the current directory name isn't known. For example, you could also define the location of the Python cache as .\__pycache__. ..\: The parent directory. You use this shorthand when the parent directory name isn't known. ..\..\: The parent of the parent directory. You can proceed up the hierarchy of directories as far as necessary to locate a particular starting point before you drill back down the hierarchy to a new location.

View Article
Python How to Install Python on Your Computer

Article / Updated 10-19-2022

Whether you use a Mac, Windows, or Linux OS (operating system), you can find and install Python on your computer. The following sections give you instructions for each OS. How to install Python on Mac OSX To find and start Python on Mac OSX computers, follow these steps: Press Cmd+spacebar to open Spotlight. Type the word terminal. Or, from the Finder, select Finder→Go→Utilities→Terminal. The Terminal window opens. In the terminal, type python. The Python interpreter that's built in to Mac OSX opens. How to install Python on Windows Unfortunately, Python doesn't come on Windows. If you're running Windows, then you need to download and install Python by following the instructions here. Installing Python on Windows isn't difficult. If you can download a file from a website, you have the skills to install Python. Fortunately, the Python Foundation (the peeps who guide the development of Python) makes installable files available from its website. Firefox and Internet Explorer responded differently to the Python download website, so the instructions are based on which of these browsers you use. If you use a whole other browser altogether, try the Internet Explorer instructions. Installing with Firefox To install Python on a Windows machine with Firefox, follow these steps: Visit www.python.org/downloads. Click the button that says Download Python 2.7.9. Or, if it's there, click a more recent version number that starts with 2.7. Clicking this button automatically downloads and saves an msi file for you. If not, try the instructions for Internet Explorer. See Figure 1. Figure 1: Download Python with Firefox. When the download's complete, click the icon for Firefox's download tool. Click the file called python-2.7.9.msi (or the more recent version, if you downloaded one). Python 2.7.9 installs on your computer. Installing with Internet Explorer To install Python on a Windows machine with Internet Explorer, follow these steps: Visit www.python.org/downloads. From the menu bar, select Downloads→Windows. You can see the menu options in Figure 2. Figure 2: Download Python with Internet Explorer. Scroll down to the heading Python 2.7.9-2014-12-10. Or scroll to a more recent version, which starts with Python 2.7, if one is available. Under this heading, click the link titled Download Windows x86 MSI Installer. See Figure 3. This is a link for a 32-bit installation, which makes things work better with third-party libraries. Use the 32-bit installer even if you have a 64-bit machine and even if you have no idea what this paragraph is talking about. Figure 3: Python x86 MSI Installer. If you're asked to choose whether to run or save the file, choose Run. This downloads python2.7.9.msi and starts running the installer. If you get a security warning when the installer begins (or at random times during the installation), choose Run. Accept the default installation options that the installer provides. How to install Python for Linux If you're running Linux, confirm that you have version 2.7.9 of Python installed, rather than version 3. This shouldn't be a problem because Python 2.7 is installed by default in recent versions of OpenSuSE, Ubuntu, and Red Hat Fedora. In the nutty odd case when someone has Python 3 but not Python 2.7, read your distribution's documentation for how to use the package manager and get Python 2.7 and IDLE.

View Article
page 1
page 2
page 3
page 4
page 5
page 6
page 7
page 8
page 9

Quick Links

  • About For Dummies
  • Contact Us
  • Activate Online Content

Connect

About Dummies

Dummies has always stood for taking on complex concepts and making them easy to understand. Dummies helps everyone be more knowledgeable and confident in applying what they know. Whether it's to pass that big test, qualify for that big promotion or even master that cooking technique; people who rely on dummies, rely on it to learn the critical skills and relevant information necessary for success.

Copyright @ 2000-2024 by John Wiley & Sons, Inc., or related companies. All rights reserved, including rights for text and data mining and training of artificial technologies or similar technologies.

Terms of Use
Privacy Policy
Cookies Settings
Do Not Sell My Personal Info - CA Only