Sometimes you need to change from one data type into another. This is called casting. You have already done this when you used input to get a number. You put the function int in the program command like this:
height = int(input(“Please enter a height in cm: ”))
To cast a variable to be a specific data type you use these functions in Python:
|str(x)||converts the value to a string|
|int(x)||converts the value to an integer – must be a whole number|
|float(x)||converts the value to a floating point number – must only contain digits and a decimal point|
|bool(x)||converts a non-zero number to True and zero to False|
|hex(x)||converts x to a hexadecimal string|
|ord(x)||converts character x to a string|
|chr(x)||converts integer x to a character|
Functions accept a certain datatype. For example, print only accepts the string datatype so often it is necessary to change the data type of a variable in order to display a result to the user.
It is best practice to store the data a user enters as the type requested when the program was executed. We can use the above methods to convert the data in an instance (when using the data), that way the data remains usable and in the format entered by the user.
With this idea in mind it is important when planning your program to consider how the data might be used going forward. For example it would not be necessary to store a telephone number as an int or float as we don't perform calculations with this type of data, however data could also be entered as a string then we can use a method to extract the day/month/year from the data by splitting the string.
You might need to convert a string to a number so that you can use it in a calculation. Consider the following program in Python:
num1 = input("Please enter the first line") num2 = input("Please enter the second number") num3 = num1 + num2 print("The sum equals ", num3)
If the user enters 3 and 5 what will the output be?Click to show answer.
What has happend? The numbers are input as strings, and the + symbol when used with strings means concatenation, or joining two strings together. Therefore we need to convert the strings to integers or floating point numbers. A corrected program might look like this..
Type in this program in a Python IDE and see what happens when you enter various different inputs.
repeat = "y" while repeat != "n": #Input a string variable = input("Please input a number: ") print("String :",variable) #Convert string to integer integer = int(variable) print("Integer :",integer) #Convert string to float floatvar = float(variable) print("Float :",floatvar) #Convert to bool boolvar = bool(integer) print("Boolean :",boolvar) repeat = input("Another number? (y/n) ").lower()