next up previous
Next: "Adding" strings Up: A Second Python Program: Previous: Python variable types

Using the correct type

Python is quite particular about doing operations with the correct variable type. Try changing your program so it prints your age five years from now. That is, add the print statement with




  print("In five years you will be", age + 5)

Then run your new program. What happens? This operation fails because you are telling Python to add a number to a string. In order to do this properly, it is necessary to convert the string to a number. For integers, this is done with the int() function, and for floats, this is done with the float() function. So try this:


  intAge = int(age)
  print("In five years you will be", intAge + 5)

If you typed it correctly, this should work.



Carleton DeTar 2017-08-10