7. Variable conversion Pt. 1

  • Variables contain either string, integer or float data
  • All user input is stored as a string by default, meaning an extra step is required to convert the input to the correct data type
  • For example, the program below will not output the expected result (doubling the age entered)
age = input("What's Your Age? ")
double_age = age + age
print(double_age)
  • This is because you shouldn’t add a number to a string of characters
  • To solve this problem you convert the age to an integer as shown below
age = input("What's Your Age? ")
age = int(age) #Convert to Integer
double_age = age + age
print(double_age)
  • Finally, a common technique is to convert numbers back to a string before printing them out, or displaying them as part of a message
print("Your doubled age is " + str(double_age))

Tasks

  1. Type in the first example and observe the output. Why is it incorrect?
  2. Type in the second example and observe the output. What has changed?
  3. Type in the final line to print out the doubled age as part of a sentence
  4. Save and label your code

Extension

Can you modify the program to ask 2-3 questions, and print them out as part of a sentence?