Python Variables: Part 2

So we’re going to go a bit deeper into Python variables and variable types so we can move on toward some more complex and useful logic than preventing clumsiness.

Variables themselves are pretty dynamic, but there are a few caveats we have to keep in mind when programming.  The first item to remember is how variable names must be composed.

Variable names must not start with a number, as that would confuse Python when reading your dynamic value:

>>> 
>>> 1dollar = 1
  File "<stdin>", line 1
    1dollar = 1
          ^
SyntaxError: invalid syntax
>>>

After starting with a letter, variable names must be alphanumeric:

>>> 
>>> te$t_var = 'test'
  File "<stdin>", line 1
    te$t_var = 'test'
      ^
SyntaxError: invalid syntax
>>> 
>>> 
>>> file_backups~ = 4
  File "<stdin>", line 1
    file_backups~ = 4
                ^
SyntaxError: invalid syntax
>>>

Notice how the ‘$’ dollar sign and ‘~’ tilde cause Python some heartburn.

Variable names must also not conflict with Python keywords, which can be found here.  Python reserves these for its special cases and logic, so variable names cannot be the same.

and       del       from      not       while    
as        elif      global    or        with     
assert    else      if        pass      yield    
break     except    import    print              
class     exec      in        raise              
continue  finally   is        return             
def       for       lambda    try

But, if I choose a good variable name and find out it is a keyword, what I do, and what is often done is to prepend or append an ‘_’ underscore and an optional prefix/suffix.

>>> 
>>> school = 'Harvard'
>>> class = 'CS203'
  File "<stdin>", line 1
    class = 'CS203'
          ^
SyntaxError: invalid syntax
>>> class_ = 'CS203'
>>> class_
'CS203'
>>> 
>>> pass = 'P@$$w0rd'
  File "<stdin>", line 1
    pass = 'P@$$w0rd'
         ^
SyntaxError: invalid syntax
>>> user_pass = 'P@$$w0rd'
>>>

Although, you should never store a password in clear text (unencrypted), this is a sufficient example.

A few types of useful variable types are as follows:

>>> 
>>> # We mentioned strings
... string_var = 'FirstName LastName'
>>> 
>>> # I also mentioned integers (simple numbers)
... integer_amount = 1309
>>> 
>>> # We can also use floats
... # Which is just a fancy name for a decimal
... float_amount = 9.99
>>> 
>>> # Tuple here
... book_tuple = ('Book Title', 29.99, 2010)
>>> 
>>> # List is like arrays in other langs
... lotto_nums = [23, 45, 67, 99]
>>> 
>>> # A dictionary is like book index
... # with titles and prices
... book_prices = {'Book Title': 29.99, '2010 Funnies': 9.99}
>>> 
>>> # Which can be retrieved like so...
... book_prices['2010 Funnies']
9.99
>>>

There are also types called classes which are a bit more complicated, and we will cover those a little later.  For the most part, these variables mimic items we deal with day-to-day.  A list is just that, a list of items, like a shopping cart.  Tuples are similar to lists, except that tuples represent more of a single object and its properties.

>>> 
>>> # Tuple here
... book_tuple = ('Book Title', 29.99, 2010)
>>>

For our tuple, example, the book_tuple represents a book title, price, and publication date.  So another book would follow the same pattern, whereas we don’t necessarily expect a list to contain properties in the same location within the list.  The differences are subtle, but over time, you learn to understand and use the differences appropriately.

Lastly, we display a dictionary which acts as an index of key-value pairs.

>>> # A dictionary is like book index
... # with titles and prices
... book_prices = {'Book Title': 29.99, '2010 Funnies': 9.99}
>>>

Here we declare a dictionary, book_prices, with 2 books and their respective prices.  Then we access a book to get its price:

>>> 
>>> # Which can be retrieved like so...
... book_prices['2010 Funnies']
9.99
>>>

All of these variable types will help us perform logic based on input and requirements of our application.

I’ll give you a hint of things to come.  Now we have a book store and we want a list of book titles as well as a list of those titles and their respective price.

>>> 
>>> book_titles = ['Book Title', 'Smashed Soup', 'Learning Programming']
>>> 
>>> # Let's create a list of books we have
... for title in book_titles:
...     print title
... 
Book Title
Smashed Soup
Learning Programming
>>> 
>>> book_pricing = {'Book Title': 29.99,
...                 'Smashed Soup': 4.99,
...                 'Learning Programming': 999.99}
>>> 
>>> for title in book_pricing.keys():
...     price = book_pricing[title]
...     print title + ' - $' + str(price)
... 
Smashed Soup - $4.99
Learning Programming - $999.99
Book Title - $29.99
>>>

I’ll try to remember to use this example in our next lesson to go over exactly what is going on here, but for now that’s all.  Any questions, comment below.

Series Navigation<< Python Variables
Python Variables, Loops, and More…Oh My >>