Control Structures

To write programs we need data types, with variables and data structures in which to store them, and we need control structures such as branches and loops to provide control of program flow and iteration. In this chapter, we will learn how to use Python's if statement and how to loop using for and while loops. Exceptions can affect the flow of control, so we also cover both handling and creating exceptions.

One fundamental way of encapsulating functionality is to put it into functions and methods. This chapter shows how to define functions, and the next chapter shows how to define classes and methods. Programmers coming from a C++ or similar background are used to functions being defined just once. The same is true in Python, but with an additional possibility: In Python, we can create functions at runtime in a way that reflects the current circumstances, as we will see later in this chapter.

In the preceding chapter, we used IDLE to experiment with snippets of Python code. In this chapter, we will almost always simply show the code as it would be written in a file as part of a program. However, it is perfectly possible to type the snippets used in this chapter into IDLE to see the results "live", and this is certainly worth doing for anything covered that you are not sure about.

Some of Python's functions and operators work on Boolean values. For example, the binary operator in returns True if its left-hand operand is in its right-hand operand. Similarly, the if and while statements evaluate the expressions they are given, as we will see shortly.

In Python, a value evaluates to False if it is the predefined constant False, the number 0, the special object None, an empty sequence (e.g., an empty string or list), or an empty collection; otherwise, the value is True.

In PyQt an empty QString and any "null" object, that is, any object of a PyQt data type that has an isNull() method (and where isNull() returns True), eval- Qt uatesto False. For example, an empty QStringList, a null QDate, a null QDateTime,

and a null QTime are all False. Correspondingly, nonempty and non-null PyQt objects are True.

We can test any object to see its Boolean value by converting it to a bool type. For example:

from PyQt4.QtCore import * now = QDate.currentDate() never = QDate()

print bool(now), bool(never) # Prints "True False"

The QDate() constructor with no arguments creates a null date; the QDate. currentDate() static method returns today's date which, of course, is not null.

Was this article helpful?

0 0


The main focus of this report is to show how to get involved in video marketing on the run, how to rank quickly on YouTube and Google using FREE semi-automatic tools and services. QUICKLY AND FREE. I will show methods and techniques I use to rank my videos, as well as free resources and tools to make video clips, to get backlinks and free traffic.

Get My Free Ebook

Post a comment