We’ve seen how Python can print strings of characters by enclosing them in quotes, but often when those characters are digits, we want to be able to handle them as mathematical numbers that lets us do calculations. Numbers that are not surrounded by quotes, are treated as mathematical numbers. For example (click ▶ to run):

Note that:

  1. The seven print() commands print out 7 lines text (two lines are not numbered).
  2. The + operator combines strings, which are surrounded by quotes
  3. The + operator adds numbers mathematically, which do not have quotes
  4. The comma , in the print command separates values of different type
  5. Strings and numbers are examples of different data types.

Exercises

In the program above, the last line of code is “commented out”, ie., the line starts with a # so that Python considers it a comment, and will not run it. This is deliberate, because the print() command is attempting to add a string to a number, which is ambiguous.

  1. Remove the # from the last line, and re-run the program. Python displays an error message confirming that you can’t add a string to a number, followed by a line which confirms this is a “TypeError” (ie. two different types of data), and that it can’t automatically convert an ‘int’ (or integer number) into a ‘str’ (string)
  2. In the last line, surround the 3-digits number with quotes, and re-run the program, and the program will run successfully.

Strings versus numbers Keywords

  • operator: a symbol that represents an action to be performed, such as + for mathematical addition or string combining. Other commons maths operators include: – (subtraction), * (multiplication), / (division)
  • type: whether data is a string of characters (ie string), or mathematical number (ie integer, or floating point number called “float”), or some other type. Examples of other data types include:
    • Booleans (True of False)
    • Lists (ordered sequences of values)