Skip to content

Programming Concepts 1: Variables

Nicholas DiBari edited this page Jan 18, 2018 · 2 revisions

Variables

Variables are the way you store data in a program. They are referenced by a name and can be used to store various types of data. You can store integers (1, 47, -2), floating point numbers (0.25421, 68.21, -97.21123), strings ('John', 'apple', 'word'), and Boolean Values (True and False). Throughout the execution of your program, these values can change values AND types, meaning a variable can hold a string at one point in the code and later be used to hold an integer.

Declaring variables is easy in Python. Simply use the '=' operator to assign a name to a value.

>>> x = 5
>>> print x  
5
>>> x = 'John'
>>> print('Hello ' + x + '!')  
Hello John!
>>>

You can typecast a variable to force it to be an arbitrary type. Be warned this will raise a ValueError if the variable type is not able to be cast.

>>> x = '5'
>>> type(x)
<type 'str'>
>>> x = int(x)
>>> type(x)
<type 'int'>
>>> name = 'John'
>>> name = int(name)  # Can't convert a literal string to an int!
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'John'
>>>

Clone this wiki locally