How#

Define an integer variable#

To define an integer variable we use the = operator which is the assignment operator. We create the name of the variable then the assignment operator followed by the integer value.

Tip

name_of_variable = int_value

For example:

year = 2020
year
2020

Attention

When choosing a variable name there are some rules to follow:

  • No spaces, use _ instead.

  • Cannot start with a number or other special characters.

There are other important conventions:

  • Use explicit names that clearly describe what the variable is (try not to use i, a unless those refer to specific mathematical variables).

  • Do not use CamelCase but use snake_case when combining words. This follows the Python convention called PEP8

##Ā Define a float variable

To define a float variable we use the = operator which is the assignment operator. We create the name of the variable then the assignment operator followed by the real value.

Tip

name_of_variable = float_value

For example:

cms_in_an_inch = 2.54
cms_in_an_inch
2.54

Define a string variable#

To define a string variable we use the = operator which is the assignment operator. We create the name of the variable then the assignment operator followed by the string which is a combination of characters between quotation marks.

Tip

name_of_variable = string_value

For example:

capital_of_dominica = "roseau"
capital_of_dominica
'roseau'

Define a boolean variable#

A boolean variable is one of two things: True or False. To define a boolean variable we again use the = operator which is the assignment operator. We create the name of the variable then the assignment operator followed by the boolean variable (either True or False).

Tip

name_of_variable = boolean_value

For example:

john_nash_has_a_noble = True
john_nash_has_a_noble
True

Tip

Creating boolean variables gives an overview of how to create boolean variables from other variables.

How to check the type of a variable#

We can get the type of a variable using the type tool.

Tip

type(object)

Where object is any variable.

For example:

year = 2020
type(year)
int
cms_in_an_inch = 2.54
type(cms_in_an_inch)
float
capital_of_dominica = "roseau"
type(capital_of_dominica)
str

Warning

If a numeric variable is given with any decimal part (including 0) then it is considered to be a float.

##Ā How to manipulate numeric variables

Numeric values can be combined to create new numeric variables.

  1. Addition, \(2 + 2\): 2 + 2;

  2. Subtraction, \(3 - 1\): 3 - 1;

  3. Multiplication, \(3 \times 5\): 3 * 5;

  4. Division, \(20 / 5\): 20 / 5;

  5. Exponentiation, \(2 ^ 4\): 2 ** 4;

  6. Integer remainder, \(5 \mod 2\): 5 % 2;

  7. Combining operations, \(\frac{2 ^ 3 + 1}{4}\): (2 ** 3 + 1) / 4;

For example:

cms_in_an_inch = 2.54
average_male_height_in_cms = 170
average_male_height_in_inches = average_male_height_in_cms / cms_in_an_inch
average_male_height_in_inches
66.92913385826772

Tip

This is similar to what we did in Carry out basic arithmetic operations.

Tip

Some languages, including Python have a shortcut to manipulate a variable ā€œin placeā€. The following takes the variable money and replaces it by 3 times money:

money *= 3

This is equivalent to:

money = money * 3

How to include variables in strings#

Variables can be used in strings using string formatting. There are numerous ways this can be done in Python but the current best practice is to use f-strings.

Tip

f"{variable}"

For example the following creates a string that uses a random number:

import random

random.seed(0)
random_number = random.random()
string = f"Here is a random number: {random_number}"
string
'Here is a random number: 0.8444218515250481'

How to combine boolean variables#

Boolean variables can be combined using the logical operators and and or.

Tip

new_boolean = first_boolean and second_boolean

Tip

new_boolean = first_boolean or second_boolean

For example:

is_tall = True
is_strong = False
is_tall_and_strong = is_tall and is_strong
is_tall_and_strong
False
is_tall = True
is_strong = False
is_tall_or_strong = is_tall or is_strong
is_tall_or_strong
True

Run code if a condition holds#

An important part of giving instructions to a computer is to specify when to do different things. This is done using what is called an if statement. Following an if a boolean variable is expected, if that boolean is True then the indented code that follows is run. Otherwise it is not.

Tip

if boolean:
    code to run if boolean is true
else:
    code to run if boolean is false
code to run after either of two previous code blocks are run.

Attention

An else statement is not always necessary. Specifically when combined with functions as seen in Probability when combined with return statement the else is often not needed.

For example the following code selects a random integer between 0 and 100 and then prints a different string depending on what the number was.

import random

random.seed(0)
random_number = random.randint(0, 100)
is_even = random_number % 2 == 0
if is_even:
    message = f"The random number ({random_number}) is even."
else:
    message = f"The random number ({random_number}) is odd."
message
'The random number (49) is odd.'

Repeat code for a given set of variables#

Given an iterable, it is possible to repeat some code for every item in the iterable. This is done using what is called a for loop. Following the for a placeholder variable is given then followed by the in keyword and the iterable. After that the indented code that will be repeated for every value of the iterable.

Tip

for dummy_variable in iterable:
    code to repeat
    ```

For example the following will print a message for every given value in the iterable:

iterable = ("Dog", 3, 2, -1.0)
for item in iterable:
    type_of_variable = type(item)
    message = f"The variable {item} has type {type_of_variable}"
    print(message)
The variable Dog has type <class 'str'>
The variable 3 has type <class 'int'>
The variable 2 has type <class 'int'>
The variable -1.0 has type <class 'float'>

Attention

for loops are a common tool across most programming languages. They are similar to the list comprehensions we saw in Create a list using a list comprehension.

  • List comprehensions should be specifically used when the goal is to create a collection of items.

  • Traditional for loops should be used when the code to run for every iteration is more complex.

Attention

Similarly to Creating an iterable with a given number of items a common use case of for loops is to combine them with a range statement to repeat code a known number of items.

Repeat code while a given condition holds#

To repeat code while a condition holds a while loop can be used. Similarly to the if statement, Following a while a boolean variable is expected, if that boolean is True then the indented code that follows is repeated. After it is run, the boolean is checked once more. When the boolean is False the indented code is skipped.

Tip

while boolean:
    code to repeat before checking boolean once more
code to run once boolean is False

Here is some code that repeatedly selects a random number until that number is even.

import random

random.seed(4)
selected_integer = random.randint(0, 10)
number_of_selections = 1
while selected_integer % 2 == 1:
    selected_integer = random.randint(0, 10)
    number_of_selections += 1
number_of_selections
2