Python Variables and Data Types: Complete Guide with Examples

1. What are variables and data types in Python?

Q: What are variables in Python?

Variables: Named containers for storing data values. Python variables are dynamically typed, meaning they don't require explicit type declarations and can change types during execution.

Q: What are data types in Python?

Data Types: Categories of data that define the kind of value a variable holds and the operations that can be performed on it.

Common Data Types:

Q: How to check the type of a variable?

Use type() function: type(variable).

Use Case: Storing user data, performing calculations, or managing collections.

2. Can you give an example of variables and data types?

# Variables with different data types
age = 30  # int
salary = 75000.50  # float
name = "Krishna"  # str
skills = ["Python", "SQL"]  # list
coordinates = (10, 20)  # tuple
employee = {"id": 1, "name": "Krishna"}  # dict
unique_ids = {101, 102, 103}  # set
is_active = True  # bool
no_value = None  # NoneType

# Display variables and types
print(f"Age: {age}, Type: {type(age)}")
print(f"Salary: {salary}, Type: {type(salary)}")
print(f"Name: {name}, Type: {type(name)}")
print(f"Skills: {skills}, Type: {type(skills)}")
print(f"Coordinates: {coordinates}, Type: {type(coordinates)}")
print(f"Employee: {employee}, Type: {type(employee)}")
print(f"Unique IDs: {unique_ids}, Type: {type(unique_ids)}")
print(f"Is Active: {is_active}, Type: {type(is_active)}")
print(f"No Value: {no_value}, Type: {type(no_value)}")
      

Output:

Age: 30, Type: <class 'int'>
Salary: 75000.5, Type: <class 'float'>
Name: Krishna, Type: <class 'str'>
Skills: ['Python', 'SQL'], Type: <class 'list'>
Coordinates: (10, 20), Type: <class 'tuple'>
Employee: {'id': 1, 'name': 'Krishna'}, Type: <class 'dict'>
Unique IDs: {101, 102, 103}, Type: <class 'set'>
Is Active: True, Type: <class 'bool'>
No Value: None, Type: <class 'NoneType'>
      

Note:

3. What is type conversion and casting in Python?

Q: What is type conversion/casting?

Type Conversion/Casting: The process of converting a value from one data type to another, either implicitly (automatic) or explicitly (manual).

Use Case: Converting user input (string) to a number for calculations or formatting numbers as strings for display.

Common Functions:

4. Can you give an example of type conversion and casting?

# Implicit conversion
num_int = 10
num_float = 3.5
result = num_int + num_float  # int + float → float
print(f"Implicit: {num_int} + {num_float} = {result}, Type: {type(result)}")

# Explicit conversion
user_input = "42"  # string from input
num = int(user_input)  # convert to int
print(f"String to int: {num}, Type: {type(num)}")

price = 99.99
price_str = str(price)  # convert to string
print(f"Float to string: {price_str}, Type: {type(price_str)}")

numbers = [1, 2, 3]
numbers_tuple = tuple(numbers)  # convert to tuple
print(f"List to tuple: {numbers_tuple}, Type: {type(numbers_tuple)}")

# Error handling for invalid conversion
try:
    invalid = int("abc")  # Raises ValueError
except ValueError as e:
    print(f"Conversion error: {e}")
      

Output:

Implicit: 10 + 3.5 = 13.5, Type: <class 'float'>
String to int: 42, Type: <class 'int'>
Float to string: 99.99, Type: <class 'str'>
List to tuple: (1, 2, 3), Type: <class 'tuple'>
Conversion error: invalid literal for int() with base 10: 'abc'
      

Note:

5. What are input/output functions in Python?

Q: What are input/output functions?

Input Functions: Allow user interaction by reading input from the console.

Output Functions: Display data to the console.

Use Case: Collecting user data (e.g., name, numbers) and displaying results or reports.

6. Can you give an example of input/output functions?

# Input: Get user data
name = input("Enter your name: ")
age = int(input("Enter your age: "))  # Convert input string to int

# Output: Display formatted results
print(f"Welcome, {name}! You are {age} years old.")
print("Skills:", "Python", "SQL", sep=", ", end="!\n")

# Calculate and display
years_to_retire = 65 - age
print(f"Years until retirement: {years_to_retire}")

# Multiple inputs
numbers = input("Enter two numbers (separated by space): ").split()
num1, num2 = map(float, numbers)  # Convert strings to floats
print(f"Sum of {num1} and {num2} is {num1 + num2}")
      

Output (Sample):

Enter your name: Krishna
Enter your age: 30
Welcome, Krishna! You are 30 years old.
Skills: Python, SQL!
Years until retirement: 35
Enter two numbers (separated by space): 5.5 3.2
Sum of 5.5 and 3.2 is 8.7
      

Note:

7. What are comments and indentation in Python?

Q: What are comments in Python?

Comments: Non-executable text used to document code, improving readability and maintainability.

Q: What is indentation in Python?

Indentation: Defines the scope and hierarchy of code blocks (e.g., functions, loops) using spaces or tabs (typically 4 spaces). Python enforces indentation, unlike languages like C/C++ that use braces {}.

Use Case: Documenting code logic and structuring code blocks for functions or conditionals.

Q: Best practices?