Types and Variables

Oliver Irwin

10th March 2023

Objectives

  • explain the idea of variable in Python
  • use variables to simplify scripts
  • implement more complex scripts with variables

Motivation

Programmers aim to be lazy and to write as little code as possible to solve a task

Writing the same code twice = no-no

For that, we use the machine’s memory and variables

Variables

a variable is a box in the machine’s memory where we can store a value

we can then reuse the value at multiple different places in the code

Variable creation

to create a variable, you declare it

in Python, this is done with the = sign

a = 42

creates a variable named a which contains the value 42

Variable names

variable names follow rules

  • they can contain letters, numbers and underscores _
  • they can’t start with a number
  • is case-sensitive
  • cannot be a keyword

Variable names - examples

correct names

my_title = "This is a title"
test_nb = 123
student3 = 0.2

incorrect names

1Title = "This is a title"
t€st! = 123
while = 0.2

Using a variable

a variable can be used unlimited number of times

you can access it’s value by using the identifier (the name)

name = "James Bond"
print(name)
$ python script.py
James Bond

Types

as we have seen earlier, variables can be of different types

a type is a family of values

each type allows different operations to be done

most common type groups: numbers, text

Numbers

two main types of numbers:

  • int: integer values (1, 153, -254)
  • float: decimal values (1.2, 3.1415)

Operations on numbers

classical operations

# adding two numbers
>>> 10 + 5
15
# substracting two numbers
>>> 10 - 5
5
# multiplying two numbers
>>> 10 * 5
50

Division

3 types of division possible:

# regular division
>>> 10 / 3
3.3333333333333335
# get the integer part of the division
>>> 10 // 3
3
# get the remainder
>>> 10 % 3
1

Text

text is represented by strings

to create a string, put text in quotes (")

text = "This is a text"
text = "This is text with numbers 1 2 3 !"
text = "Hello, World!"

Operations on text

we can concatenate strings

# extending text
>>> "Hello, I am  " + "James Bond"
Hello, I am James Bond
# repeating text
>>> "Hello! " * 3
Hello! Hello! Hello!

Other operations

# show the value of x in the console
print(x)
# get user input and store it in x
x = input()
# convert x to a string
y = str(x)
# convert x to an integer
y = int(x)
# make string x uppercase
x.upper()
# make string x lowercase
x.lower()