Beginning Programming with Python For Dummies book cover

Beginning Programming with Python For Dummies

Author:
John Paul Mueller
Published: February 13, 2018

Overview

The easy way to learn programming fundamentals with Python

Python is a remarkably powerful and dynamic programming language that's used in a wide variety of application domains. Some of its key distinguishing features include a very clear, readable syntax, strong introspection capabilities, intuitive object orientation, and natural expression of procedural code. Plus, Python features full modularity, supporting hierarchical packages, exception-based error handling, and modules easily written in C, C++, Java, R, or .NET languages, such as C#. In addition, Python supports a number of coding styles that include: functional, imperative, object-oriented, and procedural.

Due to its ease of use and flexibility, Python is constantly growing in popularity—and now you can wear your programming hat with pride and join the ranks of the pros with the help of this guide. Inside, expert author John Paul Mueller gives a complete step-by-step overview of all there is to know about Python. From performing common and advanced tasks, to collecting data, to interacting with package—this book covers it all!

  • Use Python to create and run your first application
  • Find out how to troubleshoot and fix errors
  • Learn to work with Anaconda and use Magic Functions
  • Benefit from completely updated and revised information since the last edition

If you've never used Python or are new to programming in general, Beginning Programming with Python For Dummies is a helpful resource that will set you up for success.

The easy way to learn programming fundamentals with Python

Python is a remarkably powerful and dynamic programming language that's used in a wide variety of application domains. Some of its key distinguishing features include a very clear, readable syntax, strong introspection capabilities, intuitive object orientation, and natural expression of procedural code. Plus, Python features full modularity, supporting hierarchical packages, exception-based error handling, and modules easily written in C, C++, Java, R, or .NET languages, such as C#. In addition, Python supports a number of coding styles that include: functional, imperative, object-oriented, and procedural.

Due to its ease of use and flexibility, Python is constantly growing in popularity—and now you can

wear your programming hat with pride and join the ranks of the pros with the help of this guide. Inside, expert author John Paul Mueller gives a complete step-by-step overview of all there is to know about Python. From performing common and advanced tasks, to collecting data, to interacting with package—this book covers it all!

  • Use Python to create and run your first application
  • Find out how to troubleshoot and fix errors
  • Learn to work with Anaconda and use Magic Functions
  • Benefit from completely updated and revised information since the last edition

If you've never used Python or are new to programming in general, Beginning Programming with Python For Dummies is a helpful resource that will set you up for success.

Beginning Programming with Python For Dummies Cheat Sheet

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.

Articles From The Book

33 results

Python Articles

How to View Package Content in Python

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.

Python Articles

How to Delete a File in Python

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.

  1. Open a Python File window.

    You see an editor in which you can type the example code.

  2. Type the following code into the window — pressing Enter after each line:

  3. 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.

Python Articles

How to Format Strings in Python

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.
  1. Open a Python File window.

    You see an editor in which you can type the example code.

  2. 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.

  3. Click Run Cell.

    Python outputs data in various forms, as shown in the figure below.