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.
- Naming Rules: Start with a letter or underscore, followed by letters, digits, or underscores; case-sensitive; no reserved keywords (e.g.,
if,for). - Best Practice: Use snake_case (e.g.,
user_age) for readability.
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:
- Numeric:
int(integers, e.g., 42),float(decimals, e.g., 3.14),complex(e.g., 3+4j). - Sequence:
str(strings, e.g., "Hello"),list(ordered, mutable, e.g., [1, 2, 3]),tuple(ordered, immutable, e.g., (1, 2, 3)). - Mapping:
dict(key-value pairs, e.g., {"name": "Krishna", "age": 30}). - Set:
set(unordered, unique elements, e.g., {1, 2, 3}),frozenset(immutable set). - Boolean:
bool(True/False). - NoneType:
None(represents absence of a value).
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:
- Uses
type()to display variable types. - Demonstrates Python's dynamic typing (no explicit type declarations).
- Shows common data types with practical examples.
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).
- Implicit Conversion: Python automatically converts types (e.g.,
inttofloatin arithmetic). - Explicit Conversion: Uses built-in functions like
int(),float(),str(), etc., to manually convert types.
Use Case: Converting user input (string) to a number for calculations or formatting numbers as strings for display.
Common Functions:
int(x): Converts to integer (e.g.,int("42")→ 42).float(x): Converts to float (e.g.,float("3.14")→ 3.14).str(x): Converts to string (e.g.,str(42)→ "42").list(x),tuple(x),set(x): Converts to list, tuple, or set.
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:
- Demonstrates implicit conversion (
inttofloat) and explicit casting (strtoint,floattostr,listtotuple). - Includes error handling for invalid conversions.
- Shows practical use cases (e.g., processing user input).
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.
input(prompt): Reads a string from user input; prompt is an optional message.
Output Functions: Display data to the console.
print(*objects, sep=' ', end='\n'): Outputs objects with customizable separator and end character.
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:
- Uses
input()for user interaction andint()for type conversion. - Demonstrates
print()with customsepandendparameters. - Shows
split()andmap()for handling multiple inputs.
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.
- Single-line: Start with
#(e.g.,# This is a comment). - Multi-line: Use triple quotes (
"""or''') for docstrings or comments spanning multiple lines.
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?
- Use 4 spaces for indentation (PEP 8 recommendation).
- Add meaningful comments without over-commenting obvious code.