Common data types

Data types tell the computer what kind of value a variable holds. Here are some basic types.

1. Integer (int)

Whole numbers, positive or negative.

score = 10
year = 2025

2. Floating Point (float)

Numbers with decimals.

height = 1.75
price = 3.99

3. String (str)

Text, written inside quotes.

greeting = "Hello"
color = 'blue'

4. Boolean (bool)

True or False values.

is_active = True
has_passed = False


← Back to where you were | → Start the course from the beginning

Testing for data types

Using type()

The type() function tells you what type a variable is:

age = 25
name = "Alice"
height = 1.75
is_student = True

print(type(age))        # <class 'int'>
print(type(name))       # <class 'str'>
print(type(height))     # <class 'float'>
print(type(is_student)) # <class 'bool'>

This is especially useful when debugging or checking user input:

user_input = input("Enter your age: ")
print(type(user_input))  # <class 'str'> - input is always a string!

age = int(user_input)
print(type(age))         # <class 'int'> - now it's a number

Checking if a string contains only digits: .isdigit()

The .isdigit() method checks if a string contains only numeric digits (0-9):

"123".isdigit()    # True
"42".isdigit()     # True
"12.5".isdigit()   # False (has a decimal point)
"12a".isdigit()    # False (has a letter)
"abc".isdigit()    # False (no digits)
"-5".isdigit()     # False (has a minus sign)
"".isdigit()       # False (empty string)

Common use case: Validating user input before converting to a number:

user_input = input("Enter a number: ")

if user_input.isdigit():
    number = int(user_input)
    print(f"You entered: {number}")
else:
    print("That's not a valid number!")

Important notes about .isdigit():

  • ✅ Returns True only for strings containing digits 0-9
  • ❌ Returns False for decimals (because of the . character)
  • ❌ Returns False for negative numbers (because of the - sign)
  • ❌ Returns False for empty strings

For more complex validation:

# Check for positive integers
if user_input.isdigit():
    number = int(user_input)
    print(f"Valid positive integer: {number}")

# Check for any integer (including negative)
try:
    number = int(user_input)
    print(f"Valid integer: {number}")
except ValueError:
    print("Not a valid integer!")

# Check for any number (including decimals)
try:
    number = float(user_input)
    print(f"Valid number: {number}")
except ValueError:
    print("Not a valid number!")

See Getting User Input for more examples of input validation.


← Back to where you were | → Start the course from the beginning