|
| 1 | +# Day 3: Data Types in Detail & Checking Types |
| 2 | + |
| 3 | +# Understanding data types is crucial because different operations |
| 4 | +# can be performed on different types of data. |
| 5 | +# Python is dynamically typed, meaning it automatically assigns the type, |
| 6 | +# but knowing the type helps prevent errors and write correct logic. |
| 7 | + |
| 8 | +# 1. Integers (int): Whole numbers, positive or negative, without decimals. |
| 9 | +product_count = 100 |
| 10 | +customer_id = 12345 |
| 11 | +year = 2025 |
| 12 | +print(f"Product Count: {product_count}, Type: {type(product_count)}") |
| 13 | +print(f"Customer ID: {customer_id}, Type: {type(customer_id)}") |
| 14 | + |
| 15 | +# 2. Floats (float): Numbers with a decimal point, positive or negative. |
| 16 | +temperature = 25.5 |
| 17 | +exchange_rate = 110.75 |
| 18 | +pi_value = 3.14159 |
| 19 | +print(f"Temperature: {temperature}, Type: {type(temperature)}") |
| 20 | +print(f"Exchange Rate: {exchange_rate}, Type: {type(exchange_rate)}") |
| 21 | + |
| 22 | +# 3. Strings (str): Sequences of characters (text). Enclosed in single or double quotes. |
| 23 | +user_name = "Alice Smith" |
| 24 | +greeting = 'Hello, world!' |
| 25 | +address = "123 Python St." |
| 26 | +print(f"User Name: {user_name}, Type: {type(user_name)}") |
| 27 | +print(f"Greeting: {greeting}, Type: {type(greeting)}") |
| 28 | + |
| 29 | +# 4. Booleans (bool): Represents truth values - True or False. |
| 30 | +# Used for conditional logic. |
| 31 | +is_admin = True |
| 32 | +has_discount = False |
| 33 | +is_logged_in = True |
| 34 | +print(f"Is Admin: {is_admin}, Type: {type(is_admin)}") |
| 35 | +print(f"Has Discount: {has_discount}, Type: {type(has_discount)}") |
| 36 | + |
| 37 | +# Why knowing types matters: |
| 38 | +# Try adding a number and a string directly - it will cause an error! |
| 39 | +# current_year = 2025 |
| 40 | +# message = "The year is " + current_year # This would cause a TypeError |
| 41 | +# print(message) |
| 42 | + |
| 43 | +# You often need to convert types (Type Casting) |
| 44 | +current_year = 2025 |
| 45 | +message = "The year is " + str(current_year) # Convert int to string for concatenation |
| 46 | +print(message) |
| 47 | + |
| 48 | +# Converting string to integer or float for calculations |
| 49 | +str_number_int = "123" |
| 50 | +str_number_float = "45.67" |
| 51 | +int_value = int(str_number_int) |
| 52 | +float_value = float(str_number_float) |
| 53 | +print(f"Converted Integer: {int_value}, Type: {type(int_value)}") |
| 54 | +print(f"Converted Float: {float_value}, Type: {type(float_value)}") |
0 commit comments