Class Notes: Data Types and Arithmetic Operators

We can use the function type to query the type of a value or a variable

For now, we will focus on ints and floats, also called integers and floating-point numbers

Arithmetic in Python

Number types:

Some Builtin Operators:

CategoryOperators
Arithmetic+, -, *, /, //, **, %
Relational <, <=, >=, >, ==, !=
Assignment+=, -=, *=, /=, //=, **=, %=, <<=, >>=
Logicaland, or, not

Note that:

What are the steps required to solve any programming problem?

  1. Read it
  2. Understand it
  3. Write some test cases
  4. Design your algorith
  5. Write the code

Problem 1: Temperature conversion

Fahrenheit temperatures can be calculated in terms of Celcius temperatures using the following formula:

$F = C × \dfrac{9}{5} + 32$

Implement the functions celciusToFahrenheit(c) and fahrenheitToCelcius(f) that converts the temperatures.

Solution

Problem 2: Color Blender tool:

Online tool can be found here: https://meyerweb.com/eric/tools/color-blend/

Colors in a computer are sometimes represented using integer RGB values, corresponding to the amount of red, green, and blue it is composed of. These values are integers between 0 and 255. For example, (0,0,0) is black, and (255,255,255) is white. Given two colors, we can combine them to form a palette (the colors in between the two). We can decide how many colors we want in this palette (the midpoints). For example, we can combine the colors crimson (RGB = (220, 20, 60)) and mint (RGB = (189, 252, 201)) using 3 midpoints to obtain:

color0: (220, 20, 60) # crimson
color1: (212, 78, 95)
color2: (205, 136, 131)
color3: (197, 194, 166)
color4: (189, 252, 201) # mint

This pallete has 5 colors. We could then ask ourselves: what is color 2? Implement the function getColor(r1, g1, b1, r2, g2, b2, midpoints, n) that takes as input the two initial colors, the number of midpoints, and the number of the color in the palette, and returns the RGB value of the n-th color. For example, following the case above: getColor(220, 20, 60, 189, 252, 201, 3, 1) returns (212, 78, 95).

**Hint:** for the sake of this exercise, it is ok if your result differs by one unit from the example, since integer division is not exact. We will learn how to fix this later.

**Hint:** try thinking about the problem with one component at a time (red, green, or blue), and with small midpoints (e.g. 1, 2, 3).

Solution