131.2 Data types and type casting
Learn how different data types represent information in programs, and how to convert between them safely and effectively.
What is a data type?
A data type defines the kind of value a variable can hold. Programming languages use data types to allocate memory and determine what operations can be performed. Choosing the correct data type is essential for writing efficient and error-free programs.
Common types include:
Integer – whole numbers (e.g. 10, -4)
Float (real numbers) – numbers with decimals (e.g. 3.14, -0.5)
String – sequences of characters (e.g. "hello")
Boolean – logical values:
True
orFalse
Declaring variables with different data types
Python automatically assigns a type when a value is given. Pseudocode assumes types from context.
SET age TO 17
SET height TO 1.72
SET name TO "Ella"
SET is_admin TO FALSE
Type casting
Type casting means converting one data type into another. This is useful when combining values or handling user input.
SET age TO "17"
SET age TO INTEGER(age)
SET score TO 3.9
SET score TO INTEGER(score)
SET is_ready TO STRING(TRUE)
Casting can sometimes lose information. For example, converting from float
to int
removes the decimal part.
Concatenating strings and numbers
You cannot directly combine strings and numbers without converting.
name = "Ava"
age = 15
message = name + " is " + str(age) + " years old"
Using type()
to check data types (Python only)
type()
to check data types (Python only)In Python, you can use type()
to check what data type a variable holds:
x = 10
print(type(x)) # <class 'int'>
y = "hello"
print(type(y)) # <class 'str'>
Key concepts
Each variable stores a value of a specific data type.
Python handles types dynamically, but understanding types prevents bugs.
Casting lets you safely convert between types when needed.
Strings and numbers must be cast to the same type before combining.
Last updated
Was this helpful?