Variables and Assignment

Overview

Teaching: 15 min
Exercises: 10 min
Questions
  • How can I store data in programs?

Objectives
  • Write programs that assign scalar values to variables and perform calculations with those values.

  • Correctly trace value changes in programs that use scalar assignment.

Python is a programming Language

Python can be used as a simple calculator

In [1]: 1 + 3
Out[1]: 4

In [2]: 4 * 5
Out[2]: 20

In [3]: 1/2
Out[3]: 0.5

In [4]: 2**3
Out[4]: 8
In [5]: 6/2 + 3 * 5**2
Out[5]: 78.0
In [6]: 'hello'
Out[6]: 'hello'

In [7]: 'hello' + 'world'
Out[7]: 'helloworld'

In [8]: 3 * 'hello'
OUt[8]: 'hellohellohello'
In [9]: 'hello' + 3
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-c9c9952ff2b4> in <module>
----> 1 'hello' + 3

TypeError: Can't convert 'int' object to str implicitly

Use variables to store values.

In [1]: age = 42

In [2]: first_name = 'Ahmed'

Use print to display values in the midst of your script.

In [3]: print(first_name, 'is', age, 'years old')
Ahmed is 42 years old

Variables must be created before they are used.

In [1]: last_name
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-e1aeda7b4fde> in <module>
----> 1 last_name

NameError: name 'last_name' is not defined

Variables can be used in calculations.

age = age + 3
age
45

Use an index to get a single character from a string.

an illustration of indexing

atom_name = 'helium'
atom_name[0]
'h'

Use a slice to get a substring.

atom_name = 'sodium'
atom_name[0:3]
'sod'

Use the built-in function len to find the length of a string.

len('helium')
6

Python is case-sensitive.

Use meaningful variable names.

flabadab = 42
ewr_422_yY = 'Ahmed'
print(ewr_422_yY, 'is', flabadab, 'years old')

Swapping Values

Fill the table showing the values of the variables in this program after each statement is executed.

# Command  # Value of x   # Value of y   # Value of swap #
x = 1.0    #
y = 3.0    #
swap = x   #
x = y      #
y = swap   #

Solution

# Command  # Value of x   # Value of y   # Value of swap #
x = 1.0    # 1.0            not defined    not defined    
y = 3.0    # 1.0            3.0            not defined    
swap = x   # 1.0            3.0            1.0            
x = y      # 3.0            3.0            1.0            
y = swap   # 3.0            1.0            1.0            

These three lines exchange the values in x and y using the swap variable for temporary storage. This is a fairly common programming idiom.

Predicting Values

What is the final value of position in the program below? (Try to predict the value without running the program, then check your prediction.)

initial = 'left'
position = initial
initial = 'right'

Solution

'left'

The initial variable is assigned the value 'left'. In the second line, the position variable also receives the string value 'left'. In third line, the initial variable is given the value 'right', but the position variable retains its string value of 'left'.

Challenge

If you assign a = 123, what happens if you try to get the second digit of a via a[1]?

Solution

Numbers are not strings or sequences and Python will raise an error if you try to perform an index operation on a number. In the next lesson on types and type conversion we will learn more about types and how to convert between different types. If you want the Nth digit of a number you can convert it into a string using the str built-in function and then perform an index operation on that string.

a = 123
a[1]
TypeError: 'int' object is not subscriptable
a = str(123)
a[1]
'2'

Choosing a Name

Which is a better variable name, m, min, or minutes? Why? Hint: think about which code you would rather inherit from someone who is leaving the lab:

  1. ts = m * 60 + s
  2. tot_sec = min * 60 + sec
  3. total_seconds = minutes * 60 + seconds

Solution

minutes is better because min might mean something like “minimum” (and actually is an existing built-in function in Python that we will cover later).

Slicing practice

What does the following program print?

atom_name = 'carbon'
print('atom_name[1:3] is:', atom_name[1:3])

Solution

atom_name[1:3] is: ar

Slicing concepts

  1. What does thing[low:high] do?
  2. What does thing[low:] (without a value after the colon) do?
  3. What does thing[:high] (without a value before the colon) do?
  4. What does thing[:] (just a colon) do?
  5. What does thing[number:some-negative-number] do?
  6. What happens when you choose a high value which is out of range? (i.e., try atom_name[0:15])

Solutions

  1. thing[low:high] returns a slice from low to the value before high
  2. thing[low:] returns a slice from low all the way to the end of thing
  3. thing[:high] returns a slice from the beginning of thing to the value before high
  4. thing[:] returns all of thing
  5. thing[number:some-negative-number] returns a slice from number to some-negative-number values from the end of thing
  6. If a part of the slice is out of range, the operation does not fail. atom_name[0:15] gives the same result as atom_name[0:].

Key Points

  • Use variables to store values.

  • Values are displayed as output.

  • Use print to render strings.

  • Variables must be created before they are used.

  • Variables can be used in calculations.

  • Use an index to get a single character from a string.

  • Use a slice to get a substring.

  • Use the built-in function len to find the length of a string.

  • Python is case-sensitive.

  • Use meaningful variable names.