What is a Number in Python?

  • Python treats numbers in several ways, depending on how they are used. Numbers can be represented as Integers or Floats.
  • You can add (+), subtract (-), multiply(*), and divide (/) integers in Python.

What is an Integer in Python?

  • Integers are numbers that can be positive, negative or 0. However, they cannot have a decimal point.
  • In a terminal session Python will return the result of an operation:
python
1>>>3+3
26
  • The integer type is int — In other words:
1answer = 3.1415
2int(answer) == 3
  • We can use this type name (int) to convert a variable to an integer.
  • Note that in Python the operator ”==” means comparison or equality. The operator ”=” means assignment.

Avoiding Type Errors with the str() Function:

  • Often, you’ll want to use a variable’s value within a message. For example, you might want to share your address with someone. You might write code like this:
python
1streetNumber = 87
2streetName = " Cullowhee Mountain Drive"
3streetAddress = streetNumber + streetName
4
5print(streetAddress)
  • You might expect this code to print the simple street address, 87 Cullowhee Mountain Drive. But if you run this code you’ll see that it generates an error:
1Traceback (most recent call last):
2    File "Act3_Integers.py", line 3, in <module>
3    streetAddress = streetNumber + streetName
4TypeError: unsupported operand type(s) for +: 'int' and 'str'
  • This is a type error. It means that Python can’t recognize the kind of information you’re using. Here we are using a variable that has an integer value (int) but it’s not sure how to interpret the value.
  • When we use integers within strings like this, we need to specify explicitly that we want Python to use the integer as a string of characters. We can do this by wrapping the variable in the str() function (aka type conversion function), which tells Python to represent non-string values as strings:
python
1streetNumber = 87
2streetName = " Cullowhee Mountain Drive"
3streetAddress = str(streetNumber) + streetName
4
5print(streetAddress)

Output:

187 Cullowhee Mountain Drive