CHAPTER 2

image

Variables

Variables are “slots” that we can store data in. Some languages, such as C#, Visual Basic, and others, require you to declare your variables before you use them along with the type of variable it is, for example, Integer or String. Python doesn’t require you to do this. As I said in the Introduction, Python uses a scheme called “Duck Typing.” This means that you don’t have to declare variables before they are used and that you don’t have to specify what a type variable is or will be. There is a mix of opinions on this as to whether it is a good or bad thing.

Case Sensitivity

Variables names must start with either a letter (upper- or lowercase) or an underscore character. They may not begin with a number, space, or sign character.

Everything in Python is case-sensitive: not only the keywords and functions that Python provides, but for any variables you happen to create. For example:

“Print” is not the same as “print.”

Because of this, you could use the word “Print” as a variable, but not the word “print.”That having been said, it isn’t a good idea to use “re-cased” function names or keywords.

Proper Variable Naming

A variable name should explain what the variable is used for. If you use variable names such as “x” or “q,” it doesn’t tell you anything about what the variable does or is for. This is termed “self-documenting.” A long time ago, it was “normal” practice to use single character variable names wherever possible. Many times it was to save memory. Although there is nothing that says you can not use single letters or some obscure variable names (and it really does save time and finger power when typing a large amount of code), it will make it very difficult for you or someone else to read and maintain your code after the fact.

Because spaces are not allowed in variable names, many people use what is called Camel Casing to make the variable names easier to understand. Camel Casing (sometimes called Pascal Casing) says that you put the first letter of each word in uppercase and all the rest in lowercase:

ThisIsAnExampleOfCamelCasingForVariables.
CounterVariable
ReturnedValue

Another alternative is to use underscores in place of spaces:

this_is_an_example_of_a_long_variable_name
counter_variable
returned_value

Either way is “acceptable.” It mainly depends on what you want to use or what your work uses as a standard. As I stated earlier, it is important for you to use variable names that are “self-documenting.”

Assignment

To assign a value to a variable, use the equal (“=”) sign:

AnInteger = 3
AFloatValue = 3.14159
AString = “The time has come for all good men…”
TheList = [1,2,3,4,5]

You can also make multiple assignments of a single value on one line. In the following snippet, the variable ‘a’ is assigned to the value 1. Then the variables ‘b’ and ‘c’ are assigned to be equal to the variable ‘a:’

>>> a = 1
>>> b = c = a
>>> print('a=%d, b=%d, c=%d') % (a,b,c)
a=1, b=1, c=1

Data Types

Python has five “standard” data types: numeric, string, list, tuple, and dictionary.

Numeric

Numeric data types are for storing numeric values. In Python 2.x, there are four types of numeric data, Integers (signed), Long (signed), Float (floating point numbers), and complex numbers. Booleans (0 or 1) are subtypes of integer under version 2.x. The actual range of values that can be stored in any different numeric type will vary from system to system. On my Windows machine, the maximum value for an integer is 2,147,483,647. You can find the actual maximum value for an integer on your system by using the following code in a Python Interactive Shell session:

import sys
print sys.maxint
2147483647 (My system)

Hexadecimal, octal, and binary numbers also fall under the Numeric data type umbrella.

Hexadecimal numbers are base 16. They range from 0 to 9 and A to F. Octal numbers are base 8 numbers. They range from 0 to 7. Binary numbers are base 2 numbers and only include 0 and 1. Examples of each follow:

Hexadecimal - 1B = 27 (decimal)

Octal - 033 = 27 (decimal)

Binary - 00011011 = 27 (decimal)

String

The string data type is a series of characters that is delimited by quotation marks (either single or double). Strings will be discussed seperately in Chapter 4. An example of strings would include:

'This is a string'
"3.14159"

Lists, Tuples, and Dictionaries will be discussed in Chapter 6, but for now here is a quick description.

List

Lists are a way to create multiple values that are referenced by a single variable name with a zero-based index, similar to arrays in other programming languages. Lists use square brackets (“[ ]”) to define them. An example would be:

ColorList = ['Red','Orange','Yellow','Green','Blue','Purple']

ColorList[2] would be the value ‘Yellow.’

Tuple

Tuples are a number of values seperated by commas. The data within a tuple may consist of numbers, strings, and even other objects:

t = 3,42,'The time has come for all good men'

Like lists, tuples are referenced by a zero-based index. t[1] would be the value “42”.

Dictionary

A dictionary is like a mini database in memory. Each item in a dictionary has two parts: a key and a value. Each item is referenced (usually) by its key. A dictionary uses curly brackets to define them:

dict = {"Fname":"Jack","LName":"Sprat"}

In this example, there are two sets of data in the ‘dict’ dictionary. ‘Fname’ is the key for the value ‘Jack’ and ‘LName’ is the key for the value ‘Sprat’.

Data Type Conversion

There are several built-in functions to perform conversion from one data type to another.

int(s,[base])

Returns an integer from the string s. If base is provided, specifies what base to use for the conversion. If the string is not that of a value (binary, hex, octal, integer, long, etc.), you will receive an error.

>>> int('1001',2)
9
>>> int('FA',16)
250

long(s,[base])

Returns a long integer from the string s. If base is provided, it specifies what base to use for the conversion. If the string is not a valid number, it will return an error.

>>> long(30219568420)
30219568420L

float(s)

Returns a floating point number from the string s. If the string is not a valid number, this will return an error.

>>> d = '3.14159'
>>> e = float(d)
>>> e
3.14159

complex(real [,imaginary])

Creates a complex number.

>>> complex(3.14159)
(3.14159+0j)
>>> complex(-123.45)
(-123.45+0j)
>>> complex(32,43)
(32+43j)

str(x)

Returns a string based on the numeric value x. If (x) is not a valid number, this function will return an error.

>>> str(3.14159)
'3.14159'

tuple(s)

Returns a tuple based on sequence s. The sequence should be something like a string or a list.

>>> tuple([3,5,7])
(3, 5, 7)
>>> tuple('abcd')
('a', 'b', 'c', 'd')

list(s)

Returns a list based on sequence s. The sequence should be something like a string or a tuple.

>>> list((1,2,3))
[1, 2, 3]
>>> list('abcd')
['a', 'b', 'c', 'd']

set(l)

Returns a set based on sequence l. Sequence l must be a list.

>>> set([7,3,11])
set([11, 3, 7])

dict(s) (s must be sequence of (key,value) tuples)

Returns a dictionary from a list of tuples.

>>> dict([('fname','fred'),('value',1)])
{'value': 1, 'fname': 'fred'}

frozenset(s)

Returns a frozenset created from set s.

>>> s = set([7,3,1])
>>> frozenset(s)
frozenset([1, 3, 7])

chr(x)

Returns a character created from integer x in the range of 0 to 255.

>>> chr(65)
'A'

unichr(x)

Returns a unicode character created from integer x in the range (on most machines) of 0 to 0x10000.

>>> unichr(1000)
u'u03e8'

ord(c)

Returns the ascii value of character c.

>>> ord('M')
77

hex(x)

Returns a hexadecimal string created from integer x.

>>> hex(23)
'0x17'

oct(x)

Returns an octal string created from integer x.

>>> oct(32)
'040'
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset