2.1 — Variables, Arithmetic & String operations

Review of last week

All data in a Python program is represented by objects.

An object always has a type (or class) associated with it.

  • int: Integers such as ...,1,0,1,2,......, -1, 0, 1, 2, ...
  • float: Floating-point numbers such as 1.2,3.14,-1.2, 3.14, etc.
  • str: Text data (a sequence of characters) such as “hello world”, “Python”, etc.

In Thonny, we can use Edit menu -> Toggle comment to comment/uncomment the selected lines.

Variables

In Python, a Variable is a name that refers to an object in computer memory.
A variable can be created using Assignment Statement:

variable_name = value

= is known as the assignment operator.

1# create a variable and assign it value 20
2temperature = 20
3
4# variable temperature refers to 20 which is displayed
5print("Today's temperature is", temperature)
6
7# show type of the variable
8print("Type of temperature variable is", type(temperature))
Output
Today's temperature is 20
Type of temperature variable is <class 'int'>

Arithmetic with numbers

Calculations with numbers can be done using arithmetic operators.

1# Addition
2print(1.5 + 1.5) # 3.0
3
4# Subtraction
5print(10 - 20) # -10
1# Multiplication
2print(42 * 42) # 1764
3
4# Division
5print(1 / 5) # 0.2
6
7# Exponentiation (x to the power of y)
8print(2 ** 16) # 65536

1temperature = 20
2# Unary minus operator
3print(-temperature) # -20
4
5
6# Computing rest mass energy of an electron
7rest_mass = 9.109e-31 # Using scientific notation
8speed_of_light = 3e8
9
10rest_mass_energy = rest_mass * (speed_of_light ** 2) # E = mc^2
11print(rest_mass_energy) # 8.198099999999999e-14

Floor division and remainder

1# floor division
2print(20 // 3) # 6
3
4# remainder
5print(20 % 3) # 2

1# Converting seconds to minutes
2
3duration = 320
4print(duration, "seconds equal", duration / 60, "minutes.")
5# 320 seconds equal 5.333333333333333 minutes.
6
7
8# Alternative approach:
9minutes = duration // 60
10seconds = duration % 60
11print(duration, "seconds equal", minutes, "minutes and",
12 seconds, "seconds.")
13# 320 seconds equal 5 minutes and 20 seconds.

Result type of arithmetic operations

1x = 2 + 1
2print(x, type(x)) # 3 <class 'int'>
3
4x = 2 + 1.0
5print(x, type(x)) # 3.0 <class 'float'>
6
7# Classic division always results in float
8x = 1 / 2
9print(x, type(x)) # 0.5 <class 'float'>

Try the above examples with other operators!

Try the problem “Distance between two points” on Ed.

Basic string operations

Strings are sequences of zero or more characters.

In Python, strings are enclosed by either single or double quotes.

1"Hello"
2'everyone!'
3"I'm Batman." # single quote allowed inside double quotes,
4'You can call me "Bruce".' # and vice versa.
5'123' # this is a string, not a number!
6"" # this is an empty string
7" " # this is a string with just one space

1# a multi-line string using triple quotes
2lines = """The woods are lovely, dark and deep,
3But I have promises to keep,
4And miles to go before I sleep,
5And miles to go before I sleep.
6"""
7print(lines)
8
9# We can also use single quotes for multi-line strings
10print(
11'''I hold it true, whate'er befall;
12I feel it when I sorrow most;
13'Tis better to have loved and lost
14Than never to have loved at all.
15''')

String concatenation (joining) using + operator

1message = "Hello" + "everyone"
2print(message) # Helloeveryone
3
4name = "Alice"
5message = "Hello " + name
6print(message) # Hello Alice
7
8string = "1" + "2" + "3"
9print(string) # 123 and not the number 6
10
11price = 100
12print(price + " USD")
13# TypeError: unsupported operand type(s) for +: 'int' and 'str'

String repetition

String can be repeated multiple times using * operator.

1print("Welcome! " * 3) # 'Welcome! Welcome! Welcome! '
2
3print(4 * "ha") # 'hahahaha'

String length

The function len() returns length of its argument string.

1password = "xyz1234"
2print("Password length:", len(password))
3# Password length: 7
4
5print(len(1234))
6# TypeError: object of type 'int' has no len()

Order of Expression Evaluation

When we have multiple operators in the same expression, which operator should apply first?

All Python operators have a precedence and associativity:

  • Precedence — for two different kinds of operators, which should be applied first?
  • Associativity — for two operators with the same precedence, which should be applied first?

Table below show operators from higher precedence to lower.

OperatorAssociativity
() (parentheses)-
**Right
Unary --
*, /, //, %Left
Binary +, -Left
= (assignment)Right

1x = 3
2y = 5
3# Multiplication has higher precedence than addition
4z = x + 2 * y + 1
5print(z) # 14
6
7# Need to use parentheses to enforce the order we want
8z = (x + 2) * (y + 1)
9print(z) # 30
10
11# Same precedence so left to right
12z = x * y / 100
13print(z) # 0.15

1# Same as 2 ** (3 ** 2) because "**" goes right to left
2z = 2 ** 3 ** 2
3print(z) # 512
4
5# Using parentheses to enforce the order we want
6z = (2 ** 3) ** 2
7print(z) # 64
8
9x = 5
10x = x + 1 # addition happens first and then assignment
11print(x) # 6

More on Variables

Let us write code that implements the following formula to convert fahrenheit to celsius:

c=5(f32)9c = \frac{5(f-32)}{9}

1print("10 F in C is", 5 * (10 - 32) / 9)

Variables allow “saving” intermediate results of a computation

We can use variable to store the result so that we can reuse it in the program later.

1fahrenheit = 10
2
3# Store the result of the expression
4celsius = 5 * (fahrenheit - 32) / 9
5
6print(fahrenheit, "F in C is", celsius)
7
8# Use variable celsius for more calculations
9print("Adding 10 degrees today:", celsius + 10)

Variables can be reassigned new values

1# Create variable name "number" and assign a value to it
2number = 123
3print(number) # displays 123
4
5# Assign new value to existing variable "number"
6number = -50
7
8print(number) # displays -50
9
10# add 10 and assign the result value to existing variable "number"
11number = number + 10
12
13print(number) # displays -40

New values can be of different type.

However, variables should be changed with caution as it can produce errors or strange results.

1number = 123 # an int value
2message = "hello" # a string
3
4# Now variable number refers to the string "hello"
5number = message
6print(number * 2) # String repetition!
7print(number - 10) # minus won't work with string.
Output
hellohello
Traceback (most recent call last):
    print(number - 10)
TypeError: unsupported operand type(s) for -: 'str' and 'int'

Example: Swapping values

Sometimes we need to swap (interchange) values of two variables.

A naive attempt (does not work):

1x = 137
2y = 42
3
4# Try swapping
5x = y
6y = x
7
8print(x, y) # 42 42

The following will work:

1x = 137
2y = 42
3
4# Correct way to swap
5temp = x
6x = y
7y = temp
8
9print(x, y) # 42 137

Try the problem “Textbox” on Ed.

Rules for variable names

  • A variable name can only contain alpha-numeric characters and underscores A-Z, a-z, 0-9, _
  • A variable name cannot start with a number
  • Variable names are case-sensitive
    • (cat, Cat, and CAT are three different variables)
  • They cannot be keywords.
    • Python has 33 reserved keywords, you can see a list of them by typing help("keywords") in the Python shell.

Python filenames must follow the same rules as above.

Good practice for naming variables

  • Name your variable something descriptive of its purpose or content.
  • If the variable is one word, all letters should be lowercase. Eg: hour, day.
  • If the variable contains more than one word, then they should all be lowercase and each separated by an underscore. This is called snake case.
    e.g. is_sunny, cat_name
  • Good variable names: hour, is_open, number_of_books, course_code
  • Bad variable names: asfdstow, nounderscoreever, ur_stupid, CaPiTAlsANyWHErE