Casting
Casting errors happen when a value is the wrong data type for the operation you use it in, or when a conversion function cannot make sense of the text you give it. The program runs until it reaches the bad line, then stops with a runtime error.
Using text where a number is needed, or joining text to a number with +, raises a runtime error. For example, + between a string and a number fails because Python cannot decide whether you want addition or concatenation. The value must be cast first: use int() or float() to turn numeric text into a number before calculating, and str() to turn a number into text before joining it to a string.
name = "Priya"
age = 15
print(name + age) # text plus numberOutput:
TypeError: can only concatenate str (not "int") to str (line 3)
Conversion is strict. int() only accepts text that is a valid whole number, and float() only accepts text that is a valid real number. The string "19 goals" contains extra characters, so int("19 goals") fails rather than picking out the 19. Letters, punctuation, spaces between digits and an empty string all cause the conversion to fail.
score = int("6.5")
print(score)Output:
ValueError: invalid literal for int() with base 10: '6.5' (line 1)
A string with a decimal point cannot go straight to an integer. int("6.5") fails because the decimal point is not part of a whole number. Convert to a real number first with float("6.5"), then to an integer with int(...) if you need one. The order matters: the float conversion handles the decimal point before the integer conversion removes the fractional part.
Edexcel GCSE Computer Science · Casting
Edexcel GCSE Computer Science · Input Function