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-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 ArticleArticle / Updated 10-19-2022
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 10-19-2022
While you can use Python to delete information from files, you may find you no longer need the file at all. The following steps describe how to delete files that you no longer need. Open a Python File window. You see an editor in which you can type the example code. Type the following code into the window — pressing Enter after each line: Choose Run→Run Module The application displays the File Removed! message. When you look in the directory that originally contained the ChangedFile.csv file, you see that the file is gone. The task looks simple in this case, and it is. All you need to do to remove a file is call os.remove() with the appropriate filename and path (Python defaults to the current directory, so you don’t need to specify a path if the file you want to remove is in the default directory). The ease with which you can perform this task is almost scary because it’s too easy. Putting safeguards in place is always a good idea. You may want to remove other items, so here are other functions you should know about: os.rmdir(): Removes the specified directory. The directory must be empty or Python will display an exception message. shutil.rmtree(): Removes the specified directory, all subdirectories, and all files. This function is especially dangerous because it removes everything without checking (Python assumes that you know what you’re doing). As a result, you can easily lose data using this function.
View ArticleArticle / Updated 08-16-2022
Python gives you several different ways to view package content. The method that most developers use is to work with the dir() function, which tells you about the attributes that the package provides. Function attributes are automatically generated by Python for you. These attributes perform the following tasks or contain the following information: __builtins__: Contains a listing of all the built-in attributes that are accessible from the package. Python adds these attributes automatically for you. __cached__: Tells you the name and location of the cached file that is associated with the package. The location information (path) is relative to the current Python directory. __doc__: Outputs help information for the package, assuming that you’ve actually filled it in. For example, if you type os.__doc__ and press Enter, Python will output the help information associated with the os library. __file__: Tells you the name and location of the package. The location information (path) is relative to the current Python directory. __initializing__: Determines whether the package is in the process of initializing itself. Normally this attribute returns a value of False. This attribute is useful when you need to wait until one package is done loading before you import another package that depends on it. __loader__: Outputs the loader information for this package. The loader is a piece of software that gets the package and puts it into memory so that Python can use it. This is one attribute you rarely (if ever) use. __name__: Tells you just the name of the package. __package__: This attribute is used internally by the import system to make it easier to load and manage packages. You don’t need to worry about this particular attribute. It may surprise you to find that you can drill down even further into the attributes. Type dir(MyLibrary.SayHello) and press Enter. Some of these entries, such as __name__, also appeared in the package listing. However, you might be curious about some of the other entries. For example, you might want to know what __sizeof__ is all about. One way to get additional information is to type help(“__sizeof__”) and press Enter. You see some scanty (but useful) help information. Python isn’t going to blow up if you try the attribute. Even if the shell does experience problems, you can always start a new one. So, another way to check out a package is to simply try the attributes. For example, if you type MyLibrary.SayHello.__sizeof__( ) and press Enter, you see the size of the SayHello() function in bytes. Unlike many other programming languages, Python also makes the source code for its native language libraries available. For example, when you look into the Python33Lib directory, you see a listing of .py files that you can open in IDLE with no problem at all. Viewing the content directly can help you discover new programming techniques and better understand how the library works. The more time you spend working with Python, the better you’ll become at using it to build interesting applications. Make sure that you just look at the library code and don’t accidentally change it. If you accidentally change the code, your applications can stop working. Worse yet, you can introduce subtle bugs into your application that will appear only on your system and nowhere else. Always exercise care when working with library code.
View ArticleCheat Sheet / Updated 04-26-2022
Python is an incredibly flexible language that has significant third-party support and is used in a broad range of applications. The applications you build will run on any platform that Python supports without any modification as long as you create a pure Python solution. Of course, you want to ensure that your applications have the best chance possible of working exactly as you anticipated everywhere they're run, which is why you need the information in this cheat sheet.
View Cheat SheetCheat Sheet / Updated 02-24-2022
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 SheetCheat Sheet / Updated 02-24-2022
Python coding helps you with things you do every day, like math homework. Python programming can also help with things like making web pages: Thank goodness for widgets and keywords!
View Cheat SheetArticle / Updated 01-25-2022
For all the hoopla about Python modules, a module is actually a pretty simple thing. In fact, a Python module is just a file with a .py extension that contains Python code. That’s it. So any time you write Python code and save it in a .py file, you’ve basically created a module. That’s not to say you always have to use that code as a module. It can certainly be treated as a standalone app. But if you wanted to create your own Python module, with just code that you need often in your own work, you could certainly do so. A Python module is also just a file with a .py filename extension. The name of the module is the same as the filename (without the .py). Like any .py file, the module contains Python code. As a working example, let’s suppose you want to have three functions to simplify formatting dates and currency values. You can make up any name you like for each function. For our working example, we’ll use these three names: to_date(<em>any_str</em>): Lets you pass in any string (any_str) date in mm/dd/yy or mm/dd/yyyy format and sends back a Python datetime.date that you can use for date calculations. mdy(<em>any_date</em>): Lets you pass in any Python date or datetime, and returns a string date formatted in mm/dd/yyyy format for display on the screen. to_curr(<em>any_num, len</em>): Lets you pass in any Python float or integer number and returns a string with a leading dollar sign, commas in thousands places, and two digits for the pennies. The len is an optional number for length. If provided, the return value will be padded on the left with spaces to match the length specified So here is all the code for that: # Contains custom functions for dates and currency values. import datetime as dt def to_date(any_str): """ Convert mm/dd/yy or mm/dd/yyyy string to datetime.date, or None if invalid date. """ try: if len(any_str) == 10: the_date = dt.datetime.strptime(any_str,'%m/%d/%Y').date() else: the_date = dt.datetime.strptime(any_str,'%m/%d/%y').date() except (ValueError, TypeError): the_date = None return the_date def mdy(any_date): """ Returns a string date in mm/dd/yyyy format. Pass in Python date or string date in mm/dd/yyyy format """ if type(any_date) == str: any_date = to_date(anydate) # Make sure its a dateime being forwarded if isinstance(any_date,dt.date): s_date = f"{any_date:'%m/%d/%Y'}" else: s_date = "Invalid date" return s_date def to_curr(anynum, len=0): """ Returns a number as a string with $ and commas. Length is optional """ s = "Invalid amount" try: x = float(anynum) except ValueError: x= None if isinstance(x,float): s = '$' + f"{x:,.2f}" if len > 0: s=s.rjust(len) return s You can create the same file yourself and name it myfunctions.py if you want to follow along. Notice that the file contains only functions. So if you run it, it won't do anything on the screen because there is no code in there that calls any of those functions. To use those functions in any Python app or program you write, first make sure you copy that myfunc.py file to the same folder as the rest of the Python code that you’re writing. Then, when you create a new page, you can import myfunc as a module just as you would any other module created by somebody else. Just use import myfunc You will have to use the module name in front of any of the functions that you call from that module. So if you want to make the code a little more readable, you can use this instead: import myfunc as my With that as your opening line, you can refer to any function in your custom Python module with my. as the prefix. For example, my.to_date() to call the to_date function. Here is a page that imports the module and then tests out all three functions using that my syntax: # Import all the code from myfunc.py as my. import myfunc as my # Need dates in this code from datetime import datetime as dt # Some simple test data. string_date="12/31/2019" # Convert string date to datetime.date print(my.to_date(string_date)) today = dt.today() # Show today's date in mm/dd/yyyy format. print(my.mdy(today)) dollar_amt=12345.678 # Show this big number in currency format. print(my.to_curr(dollar_amt)) You can also skip using the prefix if you import items by name. In this case, that means you could call to_date() and mdy() and to_curr() without using the my. prefix. The first line of code would need to be from myfunc import to_date, mdy, to_curr The rest of the code would be the same as in the previous example, except you can leave off the my. prefixes as in the following code: # Import all the code from myfunc.py by name. from myfunc import to_date, mdy, to_curr # Need dates in this code from datetime import datetime as dt # Some simple test data. string_date="12/31/2019" # Convert string date to datetime.date print(to_date(string_date)) today = dt.today() # Show today's date in mm/dd/yyyy format. print(mdy(today)) dollar_amt=12345.678 # Show this big number in currency format. print(to_curr(dollar_amt)) Check out these 10 amazing Python programming resources for more information.
View ArticleArticle / Updated 12-29-2021
You can format strings in a number of ways using Python. The main emphasis of formatting is to present the string in a form that is both pleasing to the user and easy to understand. Formatting doesn’t mean adding effects in this case, but refers merely to the presentation of the data. For example, the user might want a fixed-point number rather than a decimal number as output. You have quite a few ways to format strings. However, the focus of most formatting is the format() function. You create a formatting specification as part of the string and then use the format() function to add data to that string. A format specification may be as simple as two curly brackets {} that specify a placeholder for data. You can number the placeholder to create special effects. For example, {0} would contain the first data element in a string. When the data elements are numbered, you can even repeat them so that the same data appears more than once in the string. The formatting specification follows a colon. When you want to create just a formatting specification, the curly brackets contain just the colon and whatever formatting you want to use. For example, {:f} would create a fixed-point number as output. If you want to number the entries, the number that precedes the colon: {0:f} creates a fixed-point number output for data element one. The formatting specification follows this form, with the italicized elements serving as placeholders here: [[fill]align][sign][#][0][width][,][.precision][type] This specification provides you with the in-depth details, but here’s an overview of what the various entries mean: fill: Defines the fill character used when displaying data that is too small to fit within the assigned space. align: Specifies the alignment of data within the display space. You can use these alignments: <: Left aligned >: Right aligned ^: Centered =: Justified sign: Determines the use of signs for the output: +: Positive numbers have a plus sign and negative numbers have a minus sign. -: Negative numbers have a minus sign. <space>: Positive numbers are preceded by a space and negative numbers have a minus sign. #: Specifies that the output should use the alternative display format for numbers. For example, hexadecimal numbers will have a 0x prefix added to them. 0: Specifies that the output should be sign aware and padded with zeros as needed to provide consistent output. width: Determines the full width of the data field (even if the data won’t fit in the space provided). ,: Specifies that numeric data should have commas as a thousands separator. .precision: Determines the number of characters after the decimal point. type: Specifies the output type, even if the input type doesn’t match. The types are split into three groups: String: Use an s or nothing at all to specify a string. Integer: The integer types are as follows: b (binary); c (character); d (decimal); o (octal); x (hexadecimal with lowercase letters); X (hexadecimal with uppercase letters); and n (locale-sensitive decimal that uses the appropriate characters for the thousands separator). Floating point: The floating-point types are as follows: e (exponent using a lowercase e as a separator); E (exponent using an uppercase E as a separator); f (lowercase fixed point); F (uppercase fixed point); g (lowercase general format); G (uppercase general format); n (local-sensitive general format that uses the appropriate characters for the decimal and thousands separators); and % (percentage). The formatting specification elements must appear in the correct order or Python won’t know what to do with them. If you specify the alignment before the fill character, Python displays an error message rather than performing the required formatting. The following steps help you see how the formatting specification works and demonstrate the order you need to follow in using the various formatting specification criteria. Open a Python File window. You see an editor in which you can type the example code. Type the following code into the window — pressing Enter after each line: Formatted = "{:d}" print(Formatted.format(7000)) Formatted = "{:,d}" print(Formatted.format(7000)) Formatted = "{:^15,d}" print(Formatted.format(7000)) Formatted = "{:*^15,d}" print(Formatted.format(7000)) Formatted = "{:*^15.2f}" print(Formatted.format(7000)) Formatted = "{:*>15X}" print(Formatted.format(7000)) Formatted = "{:*<#15x}" print(Formatted.format(7000)) Formatted = "A {0} {1} and a {0} {2}." print(Formatted.format("blue", "car", "truck")) The example starts simply with a field formatted as a decimal value. It then adds a thousands separator to the output. The next step is to make the field wider than needed to hold the data and to center the data within the field. Finally, the field has an asterisk added to pad the output. Of course, the example contains other data types. The next step is to display the same data in fixed-point format. The example also shows the output in both uppercase and lowercase hexadecimal format. The uppercase output is right aligned and the lowercase output is left aligned. Finally, the example shows how you can use numbered fields to your advantage. In this case, it creates an interesting string output that repeats one of the input values. Click Run Cell. Python outputs data in various forms, as shown in the figure below.
View ArticleArticle / Updated 12-28-2021
It’s time to create your first Python application. Your initial IDLE Shell window won’t work for creating an application, so you can begin by creating a new Edit window for the application. You’ll type the required commands and then save the file to disk. Open a new window The initial IDLE Shell window is just fine for experimentation, but you need a nice, clean Edit window for typing your first application. The IDLE Shell window is interactive, which means that it gives you immediate feedback for any commands you type. The Edit window provides a static environment, where you type commands, save them, and then run them after you type enough commands to create an application. The two windows serve distinctly different purposes. Choose File→New File to create a new window. A new window opens. Notice that the title bar says untitled instead of IDLE Shell 3.1.0. A Python Shell window will always have the word “Shell” in the title bar. The two windows also have some unique toolbar entries. For example, an Edit window includes the Run command, which you use later to test your application. Working with the Edit window is just like working with any other text editor. You have access to basic editing commands such as Copy, Cut, and Paste. Pressing Enter moves to the next line rather than executing a command as it would when working in the Python Shell window. That’s because the Edit window is a static environment — one where you type commands and save them for later reuse. The Edit window also provides special commands to format the text. What you need to know now is that these formatting commands act differently from those in a standard text editor because they help you control the appearance of code rather than of generic text. Many of the formatting features work automatically, so you don’t need to worry about them now. Finally, the Edit window provides access to commands that tell Python to perform the steps in the procedure you create one at a time. This process is called running the application. Typing the command As with the Python Shell window, you can simply type a command into the Edit window. To see how this works, type print(. Notice that the Edit window provides you with helpful information about the print() command. The information is a little terse, so you may not understand it now. For now, the word value is the one that you need to focus on. The print() command needs a value before it can print anything. Finish the command by typing “This is a simple Python application.”) and pressing Enter. This is one of the simplest applications you can create using Python. Saving the file You could run the application now if you wanted to. However, saving your application before you run it is always a good idea. That way, if you make a mistake that causes Python or the system to freeze for some reason, your application code is still safe. Saving the application makes it easier to go back later to determine what went wrong, make corrections, and try running the application again. Choose File→Save to display the Save As dialog box. The Edit window automatically chooses the Python3 10 folder to save the application in. However, this is where the Python code resides, and saving your application code in the same folder is a bad idea. If you want, create a directory structure with similar names using a technique that works for your platform as you follow along. Type FirstApp.py in the Filename field of the Save As dialog box and click Save. Your application code is now saved on disk and you can access it anytime you want. When you return to the Edit window, the title bar text changes. Notice that the title bar includes the full path to the application.
View Article