Common data types
Data types tell the computer what kind of value a variable holds. Python’s four main basic data types are:
int: Integers (whole numbers with no decimal point)float: Floating point numbersstr: String (text)bool: True or False values
1. Integer (int)
int values are whole numbers. They can be positive or negative.
score = 10
temperature = -17
2. Floating point (float)
float values are numbers with decimals.
height = 1.75
price = 0.79 # Can also be written .79
3. String (str)
str values are text written inside quotes.
greeting = "Hello"
color = 'blue'
4. Boolean (bool)
bool values are either True or False.
is_active = True
has_passed = False
Note that True and False are keywords (i.e. you can’t name variables after them) and must be written with the first letter capitalised.
The following code will not work because true and false do not have their first letter capitalised:
is_active = true # true treated as a variable, will throw an error
has_passed = false # false treated as a variable, will throw an error
You instead get an error:
NameError: name 'true' is not defined. Did you mean: 'True'?
Conversely the following code will not work because True has the first letter capitalised and is treated as a boolean value, which can’t be reassigned (in the same way that you can’t write 1 = 2 since 1 and 2 are both values):
True = 1 # True is a keyword representing the boolean value for something that is true, will throw an error
You get an error:
SyntaxError: cannot assign to True
Testing for data types
Using type()
The type() function tells you what type a variable’s value 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!")
The function .isdigit():
- ✅ Returns
Trueonly for strings containing digits 0-9 - ❌ Returns
Falsefor decimals (because of the.character) - ❌ Returns
Falsefor negative numbers (because of the-sign) - ❌ Returns
Falsefor empty strings
See Getting User Input for more examples of input validation.
Practice Exercises
Solidify your understanding of data types with these exercises.
Q1: Detect data types
Write a program that asks the user for three different inputs and prints the data type of each one. Then convert each input to a different type and print the new type.
Expected output:
Enter your name: Alex
Enter your age: 25
Enter your height: 1.75
name is <class 'str'>
age is <class 'str'>
height is <class 'str'>
After conversion:
age as int: 25 (type: <class 'int'>)
height as float: 1.75 (type: <class 'float'>)
age as string: "25" (type: <class 'str'>)
Example solution
name = input("Enter your name: ")
age = input("Enter your age: ")
height = input("Enter your height: ")
print(f"name is {type(name)}")
print(f"age is {type(age)}")
print(f"height is {type(height)}")
print("\nAfter conversion:")
age_int = int(age)
height_float = float(height)
age_str = str(age_int)
print(f"age as int: {age_int} (type: {type(age_int)})")
print(f"height as float: {height_float} (type: {type(height_float)})")
print(f"age as string: "{age_str}" (type: {type(age_str)})")
Q2: Validate integer user input
Write a program that repeatedly asks the user to enter an integer. Use .isdigit() to check if the input is valid. Keep asking until they enter a valid integer, then print the number doubled.
Expected output:
Enter an integer: 3.14
Not a valid integer! Try again.
Enter an integer: hello
Not a valid integer! Try again.
Enter an integer: 42
Great! 42 × 2 = 84
Example solution
while True:
user_input = input("Enter an integer: ")
if user_input.isdigit():
number = int(user_input)
result = number * 2
print(f"Great! {number} × 2 = {result}")
break
else:
print("Not a valid integer! Try again.")
Alternative solution with a counter:
attempts = 0
max_attempts = 3
while attempts < max_attempts:
user_input = input("Enter an integer: ")
if user_input.isdigit():
number = int(user_input)
result = number * 2
print(f"Great! {number} × 2 = {result}")
break
else:
attempts += 1
if attempts < max_attempts:
print(f"Not a valid integer! Try again. ({max_attempts - attempts} attempts left)")
else:
print("Too many failed attempts!")
Q3: Use boolean logic
Write a program that asks the user three yes/no questions and stores the answers as boolean values. Then print a summary showing how many questions they answered “yes” to.
Expected output:
Do you like Python? (yes/no): yes
Do you have a pet? (yes/no): no
Is it sunny today? (yes/no): yes
Summary:
Question 1: True
Question 2: False
Question 3: True
You answered 'yes' to 2 out of 3 questions!
Example solution
# Ask questions
response1 = input("Do you like Python? (yes/no): ")
response2 = input("Do you have a pet? (yes/no): ")
response3 = input("Is it sunny today? (yes/no): ")
# Convert to boolean
answer1 = response1.lower() == "yes"
answer2 = response2.lower() == "yes"
answer3 = response3.lower() == "yes"
# Print summary
print("\nSummary:")
print(f"Question 1: {answer1}")
print(f"Question 2: {answer2}")
print(f"Question 3: {answer3}")
# Count yes answers
yes_count = 0
if answer1:
yes_count = yes_count + 1
if answer2:
yes_count = yes_count + 1
if answer3:
yes_count = yes_count + 1
print(f"You answered 'yes' to {yes_count} out of 3 questions!")
Alternative using a list to store answers:
questions = [
"Do you like Python? (yes/no): ",
"Do you have a pet? (yes/no): ",
"Is it sunny today? (yes/no): "
]
answers = []
for question in questions:
response = input(question)
answers.append(response.lower() == "yes")
print("\nSummary:")
for i, answer in enumerate(answers):
print(f"Question {i + 1}: {answer}")
yes_count = sum(answers) # True counts as 1, False as 0
print(f"You answered 'yes' to {yes_count} out of {len(answers)} questions!")
