Python 3 for Absolute Beginners

Python 3 for Absolute Beginners

Download

Introduction

So, you want to learn programming. Welcome to one of the great adventures of the twenty-first century. Programming requires little in the way of specialized equipment; the software tools can all be downloaded for free off the Internet, and it can be practiced in the safety and comfort of your own home, without having to ask anyone’s permission. This chapter will ease you in gently by introducing you to the software you will need to create your programs: a command-line interface, which allows you to use Python in interactive mode, and a text editor for writing scripts—nothing more complicated than that. I will also show you where to go to find help and documentation, so you can decode the sometimesimpenetrable jargon that seems to surround this, the geekiest of all technical disciplines. To begin with, you will need to make sure that you have a decently recent version of Python installed on your machine or follow the steps later in this chapter to install it (see “Choosing the Right Python Version” for a definition of decently recent). This chapter explains how to make sure that you have everything set up correctly and that you have suitable references at hand before you start your journey.

Python is an excellent language with which to learn programming. There are many reasons for this, but the simple explanation is that it’s easy to read and fast to write; it doesn’t take long to come up with working code that does something meaningful. Python has a very human-friendly syntax, which makes writing elegant code easy. The basic language is fairly simple and therefore easy to remember, and then it has an extensive library of predefined functions that you can use to facilitate most common computer tasks. Writing effective applications in Python can be as simple as playing with conceptual building blocks. It works really well for writing a little two-line application to perform some routine system administration task or to provide interactive functions on a web page, but it has enough power and flexibility to comfortably create much larger and more complex applications with graphic interfaces indistinguishable from the programs you are used to running from your computer’s main menu. If you follow the suggestions laid out in this book about writing self-explanatory code, in several months, even years, you will be able to come back to your programs and see immediately what they were supposed to do and what your original intentions were; this makes maintaining programs much simpler too.

OK, let’s make sure your system is ready for you to start running Python programs.

Chapter 1: Introducing Python
This chapter has explained some of the technical terms that you will encounter as you study the art of programming and has introduced you to some sources of further information to help you as you grow in understanding.

So far, you have made sure that the right version of Python is installed on your system and you know how to get to the Python command prompt. You should have selected a text editor to use for writing and saving your scripts, but you haven’t written any code yet. In the next chapter I will show you how to start designing programs from the initial seed of a problem that you wish to solve.

Chapter 2: Designing Software
Congratulations! You have completed your first turn around the software design cycle and produced your first Python program. In the process, you have discovered how to identify and analyze problems and have created a simple framework by breaking the problem down into simple steps. You wrote your first lines of Python code and learned how to assign values to variables. You also obtained user input using your first function and then tested it out, and you learned how to use error messages to help detect and correct coding errors. Finally, you learned about the importance of documenting your intentions, expectations, and results. This chapter has concentrated mainly on preparing ideas in order to turn them into effective applications. In the rest of this book, I will focus on the specifics of the Python programming language, and you will learn how to construct more complex applications.

Chapter 3: Variables and Data Types
In this chapter, you have learned how to assign different types of values to variables, how to manipulate simple text strings and perform basic mathematical operations using expressions and statements. Now, you know how to construct and run a simple Python script that can perform a useful calculation. In the next chapter, I will show you how to make decisions that can alter the way the program runs based on those calculations

Chapter 4: Making Choices
You now know how to get your programs to actually do something. Much of the fundamental action of a program is controlled by the use of comparison operators, logical operators, assignment operators combined with the arithmetical operators that were covered in the previous chapter, and in accordance with the rules of operator precedence. You have learned about the fundamental control structures used for decision making (if, elif, else) and looping (while, else, and for...in...else) as well as how to get out of loops cleanly using break and continue.
You have also started to learn how to refine the design and deal with logical errors using trace tables and flowcharting. In the next chapter, I will introduce the first of several more complex data types—the list—and show you how you can manipulate entire sequences of data at once.

Chapter 5: Using Lists
You have taken on a lot of new information in this chapter, culminating in developing the ideas from previous chapters to create a much more complex program that processes several related pieces of information and returns a rather verbose human readable response. This level of sophistication was made possible using Python’s data structures—strings, tuples, and lists (which are all kinds of sequence) and dictionaries (a mapping).

You have also learned that some of these structures (i.e., strings and tuples) are immutable, whereas others like dictionaries and lists are mutable, which means they can be modified. You know how to access items of a sequence using indexes and slices; you can test for membership of a structure using the in keyword or iterate through an entire sequence using the for keyword or a list comprehension. You have encountered several different uses of lists as stacks, queues and matrices of information and you know how to create dictionaries out of key-value pairs.

You also now have at your disposal a number of methods you can use to manipulate your data to produce useful output. Combined with looping techniques, these data structures provide the logical building blocks with which you can process your data. In fact, using what you have already learned, you could probably write a program that will do most things you can think of. However that code will be very long-winded, possibly difficult to read, and not really reusable. So, in the next chapter, I will introduce the next stage of program development, known as abstraction, which means you get to create your own functions.

Chapter 6: Functions
In this chapter, I covered how to abstract and generalize your code into functions. Functions allow you to make your code more readable, maintainable, and efficient. And it’s not just for your main application; your test code can also benefit from this.

During our discussion, we covered passing data to functions and working with variable scope. Variable scope allows us to keep information where it belongs, whether it belongs in the global scope of an application or in a function only.

All this means you can now refactor your early Python programs to make them easier to work with and more elegant. To prove this, we refactored one of our sample applications.

Chapter 7: Working with Text
As you’ve seen, text is integral to most Python programs, and you saw how often of our examples use it. We take text input from users, manipulate that text, and display messages in response. This is why Python comes with so many text-related features.

In this chapter, you learned how to split and join strings; format, edit, and search for strings; use regular expressions to search for patterns within strings; and work with the files on your file system. We then applied much of this in our example application.

Chapter 8: Executable Files, Organization, and Python on the Web
A lot of information has been covered in the short space of this chapter. You have learned how to create stand-alone applications, organize your projects, lay out your code, use modules to accept commandline arguments and input from stdin, execute and evaluate arbitrary strings, and create a custom namespace. Finally, you have learned how to write a simple CGI script that can receive input from a web-based form.

You can now create proper programs that will work in the same way as any other application you have installed on your system. Your end users don’t need to know anything about what language you wrote it in or the details of the code; they only need to know what commands are available via the interface you have created for them. It’s up to you whether the program is self-explanatory or in what form you provide help files. If in doubt, there is nothing wrong with plain text

You are now ready for the next coding paradigm shift—full object-oriented programming. Nearly everything in Python is an object of some type or another, and in the next chapter, you will learn about classes and see how to create and implement your own.

Chapter 9: Classes
You have covered most of Python's main coding constructs now and have started on the path of objectoriented programming. You have learned about concepts with brash new names like polymorphism, inheritance, and encapsulation. You have grasped the basic usage of attributes, methods, and their related properties. Now you are happily creating subclasses and overloading operators using magic methods. If I have done my work well, you will also understand the meanings of all these terms. The last remaining constructions you really need to know are the ones involved in handling Errors and Exceptions. You saw an example of a try: ... except: construction already in Listing 9-2. Chapter 10 will fill in the details.
Beyond that, the power of Python lies in its sprawling standard library. The remaining chapters of this book will give you insight into the functions and classes contained in some of the more commonly used modules.

Chapter 10: Exceptions
You can now include sophisticated error handling techniques in your Python repertoire. You have seen how the try...except...else...finally statement is used to handle exceptions and you now know how to create exception classes of your own based on the existing exception class. The next chapter looks at some of the most useful modules in Python’s standard library

Chapter 11: Reusing Code with Modules and Packages
Python comes with a lot of useful functionality, but it can’t do everything. To make up for this, it gives you the ability to add whatever functionality you want in the form of modules. This allows you to organize and reuse your code and to use modular code provided by other Python developers.

We had a good look at Python’s module system and built modules of our own to see how easy it is. This allowed us to talk about the different ways to import and use modules, another flexible aspect of Python modules. We also covered some of the more advanced aspects of modules, such as reloading them and how they work internally. The power of Python modules can be seen when you consider the wealth of material provided by the Python community. It’s fair to say that almost any piece of functionality is out there in the form of a Python module (and if it’s not, then get to work on it and get it out there).

Chapter 12: Simple Windowed Applications
Award yourself the rest of the day off, or failing that, your favorite beverage and a light snack. You’ve just finished the final chapter in the book. We covered a fair amount in this chapter too, including four major tools for building GUIs in Python. It’s clear that Python 3 isn’t yet the best language to use for GUI programming, but this chapter will give you enough to look into it when Python 3 is ready for GUIs.

As for the book as a whole, you know Python. You will probably be more aware of what you still don’t know about programming than when you started reading this book. Good. Over the coming months, you will want to familiarize yourself with the parts of Python’s standard library that look like they might be useful. Just take one module at a time, and construct an application that does what you want it to do. As we’ve done in this book’s examples, start with a pseudocode design or flowchart, and improve the design until you have ticked all your user requirements boxes. Once you have done that, move on to the next thing.

You now know how to go about designing applications with command-line, windowed, and webbased interfaces from a basic set of requirements. As you progress, you will develop your own methods through experience and come into contact with more sophisticated programming ideas, which you may want to integrate. I hope this book provides a first step on the path of programming that you can always come back to when you want to remind yourself of the basics. Happy programming!

Share This