Python Variables, Loops, and More…Oh My

This entry is part 5 of 8 in the series Python

We’ll start with the example at the end of Python Variables: Part 2.

>>> 
>>> 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
>>>

In this example, there are quite a few new functions and manipulations that we haven’t seen yet.  That is to be expected since variables would be quite boring and useless if there were no provided way to change them as necessary.

We start with an array, book_titles, and then loop through each title by using a for loop.  In the loop, we print the title of each book.

>>> 
>>> 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
>>>

The way a for loop works in Python is again similar to other languages.  We write:

for <single_item_in_list> in <our_list>:
    <logic for each item here>

You can read this as “for each <item> in <list>, do stuff,” where <item> is your variable name for the single item in the <list>.  This is used when you have a list of items you want to perform the same logic on.

After this, we loop through the dictionary of books and their prices.  Sometimes, you have an array of items like book titles and use those titles to access their prices in a dictionary, like book_pricing.  Other times, you just want to loop through all the items in a dictionary.  Those are called key – value pairs.

>>> 
>>> 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
>>>

Here we use keys() which is a method of all dictionary objects.  Method is just another name for function but used on objects which we’ll go over more when we discuss object-oriented development.  What keys() does is return all the, you guessed it, keys of the dictionary as a list.

In our case, we loop through this list of titles and use title as a key for book_pricing to get the book title’s price.  We assign this value to the price variable, then we print title and price.  You may notice, though, that we add ‘ – $’ to format the output.  In order to get this all together, we concatenate the strings by using the ‘+’ plus sign, which is like ‘adding’ our text together.  We also use the str() function to convert our price to a string, since Python will throw a fit if we try to concatenate a string and a different type:

>>> 
>>> price = 9.99
>>> title = 'Book Title'
>>> 
>>> print title + ' - $' + price
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'float' objects
>>>

As you’ll find out as you use more Python, there are many other ways to build and manipulate variables and data in general.  This is just the tip of the iceberg, and we’ll see more of that as we move forward.

Python Variables: Part 2

This entry is part 4 of 8 in the series Python

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.

Python Variables

This entry is part 3 of 8 in the series Python

Variables in Python are similar to most other languages.  They store values, both static and dynamic, for use and manipulation later in your application.

Here is an example:

>>> name = 'Zach'
>>> print name
Zach
>>> name
'Zach'
>>> 
>>> 
>>> wallet_money = 150
>>> print '%s has $%d in his wallet'%(name,wallet_money)
Zach has $150 in his wallet
>>> 
>>> book_cost = 55
>>> 
>>> print '%s buys a book for $%d'%(name,book_cost)
Zach buys a book for $55
>>> 
>>> wallet_money = wallet_money - book_cost
>>> wallet_money
95
>>> print '%s has $%d left in his wallet'%(name,wallet_money)
Zach has $95 left in his wallet
>>> 
>>> # Comment here isn't processed as code
... # Zach loses $40 by being clumsy
... 
>>> clumsy_loss = 40
>>> wallet_money = wallet_money - clumsy_loss
>>> wallet_money
55
>>> print '%s has $%d left after being clumsy'%(name,wallet_money)
Zach has $55 left after being clumsy
>>> # Zach changes his name to George to hide his
... # previous clumsy life
... 
>>> name = 'George'
>>> print '%s is no longer clumsy or broke'%(name)
George is no longer clumsy or broke
>>>

In this code snippet, we have variables namewallet_moneybook_cost, and clumsy_loss.  Variables here are the names with an ‘=’ sign then a value.  This is called a variable assignment.  The primary purpose for using these is to be able to interchange values without having to know the actual value at the time your code runs.  That way, if you create a bank account application, each variable will store different items for name, wallet_money, book_cost, etc., depending on the person and account currently running.

You as the developer are then able to create logic around how you want your program to work and have it apply the same to everyone who uses your application.

It is best to name variables appropriately for their use so you are able to understand what is happening within your program, as well as anyone else who works with you or after you.  For example, you wouldn’t create a variable var1, var2, var3 instead of name, wallet_money, and book_cost, because you wouldn’t be able to tell them apart or why you are using them.

I’ll break each part in the code down below:

>>> name = 'Zach'
>>> print name
Zach
>>> name
'Zach'
>>>

Here we assign the value ‘Zach’ to the variable name.  ‘Zach’ is a string type which just means it is treated as text.  We then print name to see the value, (or if you are using the Python interpreter you can just type the variable to see the current value.

>>> 
>>> wallet_money = 150
>>> print '%s has $%d in his wallet'%(name,wallet_money)
Zach has $150 in his wallet
>>>

This variable wallet_money, is assigned a number that represents $150.  This type of variable is called an integer in fancy programming lingo.  As we see later in the code, you can perform standard math on this type of value to also include multiplication ‘*’ and division ‘/’.  We’ll use more of these operations in later lessons.

We also use what we learned in the last lesson to print the name and wallet_money values in a way that is useful for us.

>>> book_cost = 55
>>> 
>>> print '%s buys a book for $%d'%(name,book_cost)
Zach buys a book for $55
>>> 
>>> wallet_money = wallet_money - book_cost
>>> wallet_money
95
>>> print '%s has $%d left in his wallet'%(name,wallet_money)
Zach has $95 left in his wallet
>>>

This time we have a variable that represents the cost of a book, book_cost equal to 55.  We print book_cost in a pretty sentence with name.  Then we subtract book_cost from wallet_money because name buys a $55 book.  The value of wallet_money can be seen now as 95.

 

>>> # Comment here isn't processed as code
... # Zach loses $40 by being clumsy
... 
>>> clumsy_loss = 40
>>> wallet_money = wallet_money - clumsy_loss
>>> wallet_money
55
>>> print '%s has $%d left after being clumsy'%(name,wallet_money)
Zach has $55 left after being clumsy

We now see a comment in the code.  Comments are used to explain what your thoughts or what is going on to help you remember something unusual or tell a future programmer why you are writing your code this way.  It could also just be a reminder.  In any case, it isn’t run as the rest of the code, it’s purely informational for developers.  clumsy_loss now has a value of 40 and is subtracted from wallet_money.  $55 is left after being clumsy.

>>> # Zach changes his name to George to hide his
... # previous clumsy life
... 
>>> name = 'George'
>>> print '%s is no longer clumsy or broke'%(name)
George is no longer clumsy or broke
>>>

Lastly, because Zach is clumsy and doesn’t want to keep that sort of reputation, he changes his name to be George.  I use this as an example to show that both wallet_money and name can contain the the same value, a modified version of its original value, or an entirely new value.  Here it doesn’t even have to be a string, as we could assign 100 to name, but that wouldn’t make any sense would it?  It would also cause an issue in our code and introduce a bug.

This is quite a bit to chew on, but I hope it explains the basics of variables, why we use them, and how to use them to make your application run.  In its essence, programming is simply a way to speed up a manual process so it can be run many, many times in a short amount of time.

If you have any questions, feel free to contact either Daryl @codecrawl or me (Zach) @zachhilbert on Twitter.  See you next time, same bat time, same bat channel.

C#: Declaring implicit variables using var

This entry is part 8 of 71 in the series C#

Beginning in C# 3.0, variables can have an implicitly type var.

Consider the following 2 declarations which are functionally equivalent.

int i = 90 //explicitly declared as integer
var i = 90 //implicitly typed

An implicitly typed variable is strongly typed just as if you had declared the type yourself.  

The type will be determined by the compiler during compile time.

For example, we look at the following examples:

var firstNumber = 6;
var secondNumber = 3.5;
var thirdVariable = "This is a string!";

During compilation by Visual Studio, the compiler will determine that firstNumber is integer, secondNumber will be assigned as double and the thirdVariable will be assigned as a string.

Implicitly typed variables are strongly typed

When the compiler first see the following line

var a = 9

it will assign an integer to variable a.  If you later declare

a = 9.5 //9.5 is a double

The compiler will generate an error as it has already been determined to be an integer instead of a double.

 

PHP: Types of variables

This entry is part 5 of 54 in the series PHP Tutorial

Just like any other programming languages, we can have different types of variables.

<?php
$var1 = 0;                          // Integer
$var2 = 3.14;                       // Float
$var3 = 'I am a string';             // String
$var4 = true;                       // Boolean
$arrayVar = array(250, 300, 325, 475);  // Array
  • Integer – Whole numbers. These can be either positive or negative.
  • Float – Numbers with decimal places. These can also be either positive or negative.
  • String – A mixture of letters, numbers, and symbols. Strings are surrounded by quotes.
  • Boolean – One of two values: true or false. The value must not have any quotes as this would turn it into a string.
  • Array – A multi-level storage type, similar to a table.