Applications of all kinds, from boring business apps to the coolest games, are all about gathering, storing, manipulating, and presenting data. Here, you’ll discover how Python tackles these basic but essential tasks. You’re now familiar with the Python working environment, so it’s time to get busy.
A variable is just a bit of memory set aside to store something—an address, a city, a high score, or the number of birds you have left to hurl at the evil pigs. You name your variables and store data in them.
To create a new variable, you just give it a name and assign a value to it, like so:
>>> lives = 3
To store things like addresses or names, you use quotation marks around the value, like this:
>>> player = "Noob1"
Variables come in a number of varieties, or types, based on what they hold. In each of the following sections, you’ll discover variable types and the ways they can be used in your application.
Numeric data is special because you can manipulate it using all the rich math functions available in Python. Numeric data can be divided into two kinds: whole numbers and decimal numbers.
Integers and Longs
For whole numbers, Python offers two data types: integers and long integers. An integer’s variable is referred to as int and is stored using at least 32 bits. This will likely meet most of your needs because it can hold any number from around negative 2 billion to positive 2 billion. (You can check the documentation on your platform to find the exact limits.)
If you do need to hold a whole number that’s bigger (or smaller) than that, you use a long type variable. In Python, a long doesn’t have any limit on its size. Note that if you compare or do arithmetic on a mix of ints and longs, Python will automatically convert them all to longs.
For decimal numbers, Python provides the float type. This type specifics the precision and range of values supported, again dependent on the platform.
Note that you don’t need to specify the keywords int, long, or float when you create variables (as you would in some other languages). Instead, you just put a value in your variable (as above) and Python figures out the appropriate type automatically.
Specific letters may be used together with literal numbers in your code to indicate the type you intend. If you assign the value 23L to a variable, you are indicating that you want the value stored as a long instead of a standard int. For unadorned literals, Python will select between int or float as appropriate.
Numeric Operators and Functions
Python uses all the standard math operators you find in any language: +, –, /, and * for add, subtract, divide, and multiply. The % is the modulus operator (the remainder after integer division). And, ** is used to raise a value to a specified power.
>>> amount = 157.56 >>> amount = amount + 15.75 >>> print(amount) 173.31 >>> rate = 0.15 >>> interest = amount * rate 25.9965
You may convert among the different types by using int(), long(), and float(), passing the value you want to convert. To round numbers in different ways, you’ll use math.trunc(), round(x,n), math.floor(), and math.ceil().
Strings store letters, numbers, and symbols “strung” together to specify things like the a person’s name, their address, and the make of their car. The data type to hold these values is str. String literals are always surrounded by either single or double quotes, as in “Goldie the Cat” or ‘Subaki the Dog’.
Note: If your application requires exchange of data with other applications that use a Unicode character set, you can use the unicode data type. A Unicode literal string is prefixed with u, as in u”Lola the Cat”. Note that there must not be any whitespace between the u and the first quote.
Within a string literal, you also can specify a number of special characters by using an escape sequence. Here are a few common ones.
|‘ and “||Used to add a single or double quote within a string|
|Used to display the backslash character itself|
So, for example…
>>> title = "He is Called 'Uncle' Dunkershnozeln" >>> print(title) He is Called 'Uncle' Dunkershnozel
This assigns a string to a title that has single quotes around Uncle and a line feed at the end.
Operators and Functions
There are a host of string functions to help you search, join, divide, and otherwise manipulate string values.
Use + for Concatenation
You don’t perform math on strings like you do with numbers, but there are a few handy operators. For example, when you use the + with two strings, it sticks the strings together (concatenates them).
>>> first = "Fred" >>> last = "Smith" >>> print(first + last) FredSmith
Of course, because there wasn’t a space in either the first or last name, no space appears after they are combined. But, you can add one by using the + operator.
>>> print(first + " " + last) Fred Smith
In this case, we just added a literal string that only contained a single space and concatenated it between the other two. You can concatenate together as many strings as you like this way.
Use * for Repetition
Although most languages allow you to easily concatenate strings with an operator, few provide a repetition operator, as Python does. Here’s how it works.
>>> piggy = "Oink" >>> print(piggy * 3) OinkOinkOink
Just use the times operator between your string and a number and the resulting string will be repeated that many times.
Slicing Up Your Strings
In Python, you can use square brackets to get at parts of a string, like so:
>>> alert = "The Red Coats are coming!" >>> print(alert) R
The number inside the square brackets tells you the character to display, in this case, the 4th. The fourth is a space, you say? Sure if you start counting with 1, like a human. Python (and virtually all other computer languages) begin counting with 0 instead of 1. So, if the first character is 0, the fourth would be R.
A more interesting use of the square brackets is to pull out a piece of the string. For example…
>>> print(alert[4 : 7]) Red
This code plucks out characters 4 through 7. “But wait…” I know, I know. It’s actually 4 through 6, right? Actually, no. Think of it this way…
Figure 1: Determining the numerical assignment to letters
Imagine the numbers you use to refer to parts of the string aren’t character numbers, really. The numbers actually go between each letter. So, when we say we want the characters 4 through 7, you can see in Figure 1 that we’re referring to R, e, and d.
Searching a String
The easiest way to determine if one string is within another is to use the in operator.
>>> "Gold" in "Goldie the Cat" True
You now have the basics for using variables with numbers and strings. With this foundation, you are ready to launch into Python’s exciting commands, structures, and libraries.