Variables, Expressions, and Assignments 1#

Introduction #

In this chapter, we introduce some of the main building blocks needed to create programs–that is, variables, expressions, and assignments. Programming related variables can be intepret in the same way that we interpret mathematical variables, as elements that store values that can later be changed. Usually, variables and values are used within the so-called expressions. Once again, just as in mathematics, an expression is a construct of values and variables connected with operators that result in a new value. Lastly, an assignment is a language construct know as an statement that assign a value (either as a constant or expression) to a variable. The rest of this notebook will dive into the main concepts that we need to fully understand these three language constructs.

Values and Types#

A value is the basic unit used in a program. It may be, for instance, a number respresenting temperature. It may be a string representing a word. Some values are 42, 42.0, and ‘Hello, Data Scientists!’.

Each value has its own type: 42 is an integer (int in Python), 42.0 is a floating-point number (float in Python), and ‘Hello, Data Scientists!’ is a string (str in Python).

The Python interpreter can tell you the type of a value: the function type takes a value as argument and returns its corresponding type.

type(42)
int
type(42.0)
float
type('Hello Data Scientists!')
str

Observe the difference between type(42) and type('42')!

type('42')
str

Expressions and Statements #

On the one hand, an expression is a combination of values, variables, and operators.

A value all by itself is considered an expression, and so is a variable.

42
42
n = 17
n
17
m = 27
m + 25
52
k = 9
k * 37
333

When you type an expression at the prompt, the interpreter evaluates it, which means that it calculates the value of the expression and displays it.

In boxes above, m has the value 27 and m + 25 has the value 52. m + 25 is said to be an expression.

On the other hand, a statement is an instruction that has an effect, like creating a variable or displaying a value.

n = 17
print(n)
17

The first statement initializes the variable n with the value 17, this is a so-called assignment statement.

The second statement is a print statement that prints the value of the variable n.

The effect is not always visible. Assigning a value to a variable is not visible, but printing the value of a variable is.

Assignment Statements#

We have already seen that Python allows you to evaluate expressions, for instance 40 + 2. It is very convenient if we are able to store the calculated value in some variable for future use. The latter can be done via an assignment statement. An assignment statement creates a new variable with a given name and assigns it a value.

magicnumber = 40 + 2    
pi = 3.141592653589793  
message = 'Data is eating the world'  
print(magicnumber)
42

The example in the previous code contains three assignments. The first one assigns the value of the expression 40 + 2 to a new variable called magicnumber; the second one assigns the value of π to the variable pi, and; the last assignment assigns the string value 'Data is eatig the world' to the variable message.

Programmers generally choose names for their variables that are meaningful. In this way, they document what the variable is used for.

# You can add type hints to your variables too
magicnumber: int = 40 + 2   # An integer
pi: float = 3.141592653589793 # A float
message: str = 'Data is eating the world' # A string
# Remove this line and add your code here

Do It Yourself!

Well done! Now, why don’t you print the result in a message? It can say something like “The volume of the cube with side 5 is \(volume\)”.

# Remove this line and add your code here

Beware that there is no checking of types (type checking) in Python, so a variable to which you have assigned an integer may be re-used as a float, even if we provide type-hints.

magicnumber: int = 40 + 2 # An integer 
print(type(magicnumber))

magicnumber: int = 3.141592653589793 # A float
print(type(magicnumber))

magicnumber: int = "Hello" # A string
print(type(magicnumber))
<class 'int'>
<class 'float'>
<class 'str'>

Names and Keywords#

Names of variable and other language constructs such as functions (we will cover this topic later), should be meaningful and reflect the purpose of the construct.

In general, Python names should adhere to the following rules:

  • It should start with a letter or underscore.

  • It cannot start with a number.

  • It must only contain alpha-numeric (i.e., letters a-z A-Z and digits 0-9) characters and underscores.

  • They cannot share the name of a Python keyword.

If you use illegal variable names you will get a syntax error.

By choosing the right variables names you make the code self-documenting, what is better the variable v or velocity?

velocity: int = 5 # in meters/second.

The following are examples of invalid variable names.

99ballons: str = 'Nena'
  Cell In[18], line 1
    99ballons: str = 'Nena'
      ^
SyntaxError: invalid syntax
largenr$: int = 1000000
  Input In [4]
    largenr$: int = 1000000
           ^
SyntaxError: invalid syntax

These basic development principles are sometimes called architectural rules. By defining and agreeing upon architectural rules you make it easier for you and your fellow developers to understand and modify your code.

If you want to read more on this, please have a look at Code complete a book by Steven McConnell [McC04].

Every programming language has a collection of reserved keywords. They are used in predefined language constructs, such as loops and conditionals. These language concepts and their usage will be explained later.

The interpreter uses keywords to recognize these language constructs in a program. Python 3 has the following keywords:

False class finally is return

None continue for lambda try

True def from nonlocal while

and del global not with

as elif if or yield

assert else import pass break

except in raise

# Wrong variable name
while: str = 'while'
# Correct variable name
while_name: str = 'while'

Reassignments #

It is allowed to assign a new value to an existing variable. This process is called reassignment. As soon as you assign a value to a variable, the old value is lost.

x: int = 42
print(x)

x = 43
print(x)

The assignment of a variable to another variable, for instance b = a does not imply that if a is reassigned then b changes as well.

a: int = 42
b: int = a # a and b have now the same value

print('a =', a)
print('b =', b)

a = 43 # a and b are no longer equal

print(a)
print(b)
# Remove this line and add your code here

Updating Variables #

A frequently used reassignment is for updating puposes: the value of a variable depends on the previous value of the variable.

print(x)
x = x + 1

print(x)

This statement expresses “get the current value of x, add one, and then update x with the new value.”

Beware, that the variable should be initialized first, usually with a simple assignment.

y = y + 1
print(y)
# Remove this line and add your code here
y: int = 0   # integer
y = y + 1
print(y)

Updating a variable by adding 1 is called an increment; subtracting 1 is called a decrement. A shorthand way of doing is using += and -=, which stands for x = x + ... and x = x - ... respectively.

z: int = 0    # integer
z += 100
print(z)
z -= 1
print(z)

Order of Operations #

Expressions may contain multiple operators. The order of evaluation depends on the priorities of the operators also known as rules of precedence.

For mathematical operators, Python follows mathematical convention. The acronym PEMDAS is a useful way to remember the rules:

  • Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first, 2 * (3 - 1) is 4, and (1 + 1)**(5 - 2) is 8. You can also use parentheses to make an expression easier to read, even if it does not change the result.

  • Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27, and 2 * 3**2 is 18, not 36.

  • Multiplication and division have higher precedence than addition and subtraction. So 2 * 3 - 1 is 5, not 4, and 6 + 4 / 2 is 8, not 5.

  • Operators with the same precedence are evaluated from left to right (except exponentiation). So in the expression degrees / 2 * pi, the division happens first and the result is multiplied by pi. To divide by 2π, you can use parentheses or write: degrees / 2 / pi.

In case of doubt, use parentheses!

Do It Yourself!

Let’s see what happens when we evaluate the following expressions. Just run the cell to check the resulting value.

# Parentheses 1
2 * (3 - 1) 
# Parentheses 2
(1 + 1)**(5 - 2)
# Exponentiation 1
1 + 2**3
# Exponentiation 2
2 * 3**2
# MDAS 1
2 * 3 - 1
# MDAS 2
6 + 4 / 2
# Same precedence 1
degrees: int = 180
pi: float = 3.141592653589793
degrees / 2 * pi
# Same precedence 2
degrees / 2 / pi

Floor Division and Modulus Operators #

The floor division operator // divides two numbers and rounds down to an integer.

For example, suppose that driving to the south of France takes 555 minutes. You might want to know how long that is in hours.

Conventional division returns a floating-point number.

minutes: int = 555
minutes / 60

Hours are normally not represented with decimal points. Floor division returns the integer number of hours, dropping the fraction part.

minutes: int = 555
hours: int = minutes // 60
hours

The modulus operator % works on integer values. It computes the remainder when dividing the first integer by the second one.

remainder: int = minutes % 60
remainder

The modulus operator is more useful than it seems.

For example, you can check whether one number is divisible by another—if x % y is zero, then x is divisible by y.

String Operations#

In general, you cannot perform mathematical operations on strings, even if the strings look like numbers, so the following operations are illegal: '2'-'1' 'eggs'/'easy' 'third'*'a charm'

'2' - '1'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-24-c3c854adf3eb> in <module>
----> 1 '2' - '1'

TypeError: unsupported operand type(s) for -: 'str' and 'str'

But there are two exceptions, + and *.

The + operator performs string concatenation, which means it joins the strings by linking them end-to-end.

first: str = 'data'
second: str = ' '
third: str = 'science'
first + ((second) + third)
'data science'

The * operator also works on strings; it performs repetition.

('Data' + ' ') * 3
'Data Data Data '
arriba = "Arriba"
andale = "Andale"
yepa = "Yepa"

# Remove this line and add your code here

Asking the User for Input#

The programs we have written so far accept no input from the user.

To get data from the user through the Python prompt, we can use the built-in function input.

When input is called your whole program stops and waits for the user to enter the required data. Once the user types the value and presses Return or Enter, the function returns the input value as a string and the program continues with its execution.

Try it out!

inp = input()
inp * 3
 45
'454545'

You can also print a message to clarify the purpose of the required input as follows.

food = input('What is your favourite food? \n')
print('I love ' + food)
What is your favourite food? 
 Pizza
I love Pizza

The resulting string can later be translated to a different type, like an integer or a float. To do so, you use the functions int and float, respectively. But be careful, the user might introduce a value that cannot be converted to the type you required.

age = input('What is your age? ')
print(int(age))
print(float(age))
What is your age?  59
59
59.0
# Remove this line and add your code here

Script Mode #

So far we have run Python in interactive mode in these Jupyter notebooks, which means that you interact directly with the interpreter in the code cells. The interactive mode is a good way to get started, but if you are working with more than a few lines of code, it can be clumsy. The alternative is to save code in a file called a script and then run the interpreter in script mode to execute the script. By convention, Python scripts have names that end with .py.

Use the PyCharm icon in Anaconda Navigator to create and execute stand-alone Python scripts. Later in the course, you will have to work with Python projects for the assignments, in order to get acquainted with another way of interacing with Python code.


1

This Jupyter Notebook is based on Chapter 2 of the books Python for Everybody [Sev16] and Think Python (Sections 5.1, 7.1, 7.2, and 5.12) [Dow15].