Python Tutorial-Variables

A variable is defined as an object that is not consistent, subject to change. In programming a variable is the act of taking one object and defining it as another object. Variables are a large part of all programming languages because they allow programs to be more dynamic. Using IDLE we would set a variable as follows:

Did you get an error? If you did then you copied and pasted this into IDLE. Remember IDLE can only read one statement at a time so you have to type out each line and press enter to get your answer. If you want to enter them all together you have to use the Python Shell as reviewed in the comments tutorial.

This simply returns 9. Now 9 is an integer which means that Python knows you wanted to return an integer. How did Python know this? Because you used integers when setting the variables. But suppose I wanted to use string (text) instead? Well I could do this..

This would return
Hi there!

A couple of things to point out here. First this time I used quotation marks ” around my variables. This tells python that you want to return a string of text. Second, notice the space in front of the word there. If I did not add the space I would have returned Hithere!. And that’s not very attractive.

Now suppose I had variables of mixed content for some reason, but I want to set the result to a specific type of variable (integer or string). I can do that as well. Here’s how:

This returns 12. Let me explain what happened here. First we declared number1 a string by placing quotations ” around 5. By default Python will recognize this as text rather than a number. For the second variable we set number2 to 7, an integer. If we simply tried to print(number1 + number2) we would get 5undefined as a result. In the print statement we added the type of variable we wanted as a result by placing the int in the statement.

Some of the more important(commonly used) variable types are listed below:

  • int(variable)-casts variable to integer
  • str(variable)-casts variable to string
  • float(variable)-casts variable to a float

Because I did not define what a float is yet, I will do so now. A float is another way to represent a number. The difference between an integer and a float is a float will include a decimal and at least 1 number to the right of the decimal. For example 2.2

That’s it for the overview of variables. Now open up IDLE and practice because practice makes perfect.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.