Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Casting

As referenced in the Mathematical Operators section, there are times when we need to change one value into another data type. This can be done using a concept called “Casting”.

In order to cast a value from one data type to another data type, we must use the specific function to convert it. We’ll discuss what functions are later on, but for now, just think of it as a way for us to run code that we didn’t write ourselves, without needing to rewrite the code.

Int

In order to convert a value into an integer, we must use the int() function. This requires us to enter the value we’d like to convert into an integer between the parentheses.

For example, if we wanted to convert the string value of "123" into an int for some calculation, we could simply do int("123"). This will give us 123 in return. As this is now an int, we can use our regular mathematical operators on the number.

The following short code snippet creates a string variable named age, converts it into an int, and prints out the age stored after 2 years have passed.

age = "25"
age = int(age)
print("Your age in 2 years will be:", age+2)

This is valid, as the age is an integer now and we can add 2 to the integer value. If we don’t cast it into an int, we would simply add the number 2 to the string value, getting "252" instead.

Converting Input to Int

As briefly mentioned in the input section, we can convert the inputted value from a String into an int. This can be done with the following snippet:

age = input("Enter your age: ")
age = int(age)
print("Your age in 2 years will be:", age + 2)

This way, we can ask the user to enter their age. We then convert the age into an int instead of a string. From here, we’re able to change the value as a number.

Possible Errors

If the value cannot be converted into an integer, meaning non-numeric values are included (this includes periods), then we would get a ValueError and our code would crash. This crash is not ideal. In a future chapter, we will discuss proper ways to manage this error, but for now, ensure the values being passed into the int function are valid possible integer values. This could also be done using a helper function called isdigit(), which will return a boolean if the string is a digit/numeric value.

This could be done using the following snippet:

age = "25"
if age.isdigit() == True:
    age = int(age)
    print("Your age in 2 years is", age + 2)
else:
    print("Age is not a valid integer value")

In the case above, the output would say: "Your age in 2 years is 27". While we haven’t discussed the if-else convention, as this appears in Chapter 2, this code will check if our age variable is a digit. If it is, then we will execute the code. If the age variable is not a digit, causing the condition to be False, then we go down to the else section and execute that code. We will explore the if-else convention more in Chapter 2.

If we convert the age variable to a non-integer compliant value, our print statement would be executed.

age = "25.1"
if age.isdigit() == True:
    age = int(age)
else:
    print("Age is not a valid integer value")

In the case above, the output would say: "Age is not a valid integer value" since “25.1” is not a valid integer value due to the period/decimal. If we want to convert the value into a numeric value, we could instead convert it into a float.

Float

If we want to convert a value into a floating-point value, we can cast it into a float using the float() function. This process is the same as the process to cast a value into an int. We must enter the value between the parentheses to convert the value into a float.

For example, if we wanted to covert the string value of "3.1415", we could simply write float("3.1415") and we would have the floating-point value of 3.1415, which we could then use as a number.

Value Error again

If we try to convert a non-floating-point value into a float, we will receive another ValueError. In this case, we would need some additional checks.

String

Now, if we want to convert a value into a string, we could follow our pattern by calling the str() function. This would look like str(14) to get "14" or str(1.332) to get 1.332.