Understanding Boolean values
It may seem amazing, but computers always give you a straight answer! A computer will never provide “maybe” as output. Every answer you get is either True or False. In fact, there is an entire branch of mathematics called Boolean algebra that was originally defined by George Boole (a super-geek of his time) that computers rely upon to make decisions. Contrary to common belief, Boolean algebra has existed since 1854 — long before the time of computers.
When using Boolean value in Python, you rely on the bool type. A variable of this type can contain only two values: True or False. You can assign a value by using the True or False keywords, or you can create an expression that defines a logical idea that equates to true or false. For example, you could say, myBool = 1 > 2, which would equate to False because 1 is most defi- nitely not greater than 2. You see the bool type used extensively in the book, so don’t worry about understanding this concept right now.
Of all the data types, strings are the most easily understood by humans and not understood at all by computers. If you have read the previous chapters in this book, you have already seen strings used quite. For example, all the example code in Chapter 4 relies on strings. A string is simply any grouping of characters you place within double quotes. For example, myString = “Python is a great language.” assigns a string of characters to myString.
The computer doesn’t see letters at all. Every letter you use is represented by a number in memory. For example, the letter A is actually the number 65. To see this for yourself, type ord(“A”) at the Python prompt and press Enter. You see 65 as output. It’s possible to convert any single letter to its numeric equivalent using the ord() command.
Because the computer doesn’t really understand strings, but strings are so useful in writing applications, you sometimes need to convert a string to a number. You can use the int() and float() commands to perform this conversion. For example, if you type myInt = int(“123”) and press Enter at the Python prompt, you create an int named myInt that contains the value 123. Figure 5-4 shows how you can perform this task and validate the content and type of myInt.
Figure 5-4: Converting a string to a number is easy using the
int() and float() commands.
You can convert numbers to a string as well by using the str() command.
For example, if you type myStr = str(1234.56) and press Enter, you create a string containing the value “1234.56” and assign it to myStr. Figure 5-5
shows this type of conversion and the test you can perform on it. The point
is that you can go back and forth between strings and numbers with great ease. Later chapters demonstrate how these conversions make a lot of seem- ingly impossible tasks quite doable.
Figure 5-5: It’s possible to convert numbers to strings as