In Python, you can handle different data types using various methods and functions. Here’s a brief overview of common data types and how to work with them:
-
Strings: Text data enclosed in quotes.
name = "Alice" -
Integers: Whole numbers.
age = 30 -
Floats: Decimal numbers.
height = 5.5 -
Lists: Ordered collections of items.
fruits = ["apple", "banana", "cherry"] -
Tuples: Immutable ordered collections.
coordinates = (10.0, 20.0) -
Dictionaries: Key-value pairs.
person = {"name": "Alice", "age": 30} -
Booleans: True or False values.
is_student = True
Type Conversion
You can convert between data types using built-in functions:
-
To String:
str()age_str = str(age) -
To Integer:
int()height_int = int(height) -
To Float:
float()age_float = float(age)
Checking Data Types
Use the type() function to check the data type of a variable:
print(type(name)) # Output: <class 'str'>
Example of Handling Different Data Types
Here’s a simple example that combines different data types:
name = input("What is your name? ")
age = int(input("What is your age? "))
height = float(input("What is your height in meters? "))
print(f"{name} is {age} years old and {height} meters tall.")
This example demonstrates how to gather and handle different data types from user input. If you have more specific questions or need further examples, feel free to ask!
