Introduction to Programming

Definitions
Types in Python

Every piece of data in a program is of a particular type. Three basic types of data in Python are:

What you can do to data depends on its type. As shown below, you can add two integers and get their integer sum. Similarly you can add two floats and get their float sum. You can also add an integer and a float. The result of mixing integers and floats will always be a float. However, you cannot add an integer to a string. This results in a syntax error. Perhaps surprisingly, you can add two strings, which performs concatenation.

>>> 1 + 2
3

>>> 1.2 + 1.3
2.5

>>> 1.2 + 4
5.2

>>> 1 + "testing"
Traceback (most recent call last):
  File "", line 1, in 
      TypeError: unsupported operand type(s) for +: 'int' and 'str'
      
>>> "test" + "this"
'testthis'
Variables in Python

Using a variable allows us to name a piece of data and store it in the computer's memory. You can assign a value to a variable using the equal sign.

Syntax of assignment:

  <variable> = <expression>

When describing syntax, anything enclosed between < > indicates that it is a placeholder. A <variable> is a name that is given by a string of characters that starts with a letter and contains no spaces. An <expression> is any set of operations (such as addition, subtraction, multiplication, or division) applied to data that produces a value.

Below are some examples of assignment. The first line assigns x to be the sum of 4 and 3, and we can see that x is now 7. Then we re-assign x to be 10. Finally we re-assign x to be its current value plus 1, which makes x be 11.

>>> x = 4+3
x

>>> x
7

>>> x = 10
x

>>> x
10

>>> x = x + 1
x

>>> x
11
  

Semantics of assignment:

The line, x = x + 1, might look a little weird to you, because it seems mathematically incorrect. But in Python, the semantics of an equal sign is to assign the value of the expression on the right-hand side to the variable on the left-hand side. Python first evaluates x + 1 by looking up the current value of x (which is 10) and adds 1 to it, making 11. Then Python associates the new value (which is 11) with the variable. These examples demonstrate that a variable can be re-assigned many times. It only retains the value of the most recent assignment.