Programming with Python and Biopython

Variables and Assignment

Overview

Teaching: 5 min
Exercises: 5 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.

Use variables to store values.

age = 42
first_name = 'Ahmed'

Use print to display values.

print(first_name, 'is', age, 'years old')
Ahmed is 42 years old

Variables persist between cells.

Variables must be created before they are used.

print(last_name)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-c1fbb4e96102> in <module>()
----> 1 print(last_name)

NameError: name 'last_name' is not defined

Python is case-sensitive.

Use meaningful variable names.

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

Variables can be used in calculations.

age = age + 3
print('Age in three years:', age)
Age in three years: 45

Swapping Values

Draw a table showing the values of the variables in this program after each statement is executed. In simple terms, what do the last three lines of this program do?

lowest = 1.0
highest = 3.0
temp = lowest
lowest = highest
highest = temp

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"

Key Points