Types and built-in functions

# Replace the value of this variable with your name
my_name = 'John Coltrane'

Every value has a type.

  • Every value in a program has a specific type.

  • Integer (int): represents positive or negative whole numbers like 3 or -512.

  • Floating point number (float): represents real numbers like 3.14159 or -2.5.

  • Character string (usually called “string”, str): text.

    • Written in either single quotes or double quotes (as long as they match).

    • The quote marks aren’t printed when the string is displayed.

Built-in functions

  • Use the built-in function type to find out what type a value has.

  • Works on variables as well.

    • But remember: the value has the type — the variable is just a label.

def get_gdp(C,I,G,X,M):
     return  C + I + G + (X - M)

island_gdp = get_gdp(1000000, 500000,800000,100000,2000000)

Types control what operations (or methods) can be performed on a given value.

  • A value’s type determines what the program can do to it.

print(5 - 3)
print('hello' + ', ' + my_name)

You can use the “+” and “*” operators on strings.

  • “Adding” character strings concatenates them.

full_name = 'Ahmed' + ' ' + 'Walsh'
  • Multiplying a character string by an integer N creates a new string that consists of that character string repeated N times.

    • Since multiplication is repeated addition.

separator = '=' * 10

Strings have a length (but numbers don’t).

  • The built-in function len counts the number of characters in a string.

  • But numbers don’t have a length (not even zero).


Must convert numbers to strings or vice versa when operating on them.

  • Cannot add numbers and strings.

print(1 + '2')
  • Not allowed because it’s ambiguous: should 1 + '2' be 3 or '12'?

  • Some types can be converted to other types by using the type name as a function.

print(1 + int('2'))
print(str(1) + '2')

Can mix integers and floats freely in operations.

  • Integers and floating-point numbers can be mixed in arithmetic.

    • Python 3 automatically converts integers to floats as needed. (Integer division in Python 2 will return an integer, the floor of the division.)

print('half is', 1 / 2.0)
print('three squared is', 3.0 ** 2)