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
Filter Results
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 ArticleCheat 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 SheetArticle / 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 ArticleCheat 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 SheetArticle / 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 ArticleArticle / 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 ArticleArticle / 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 ArticleArticle / 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 ArticleArticle / 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 ArticleArticle / 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