Python Data Types and Operations: A Step-by-Step Tutorial
This tutorial provides a comprehensive guide to understanding data types, type conversion, user input, and operators in Python. Each topic is explained with clear examples to facilitate learning for beginners.
1. Data Types in Python
Python supports several built-in data types that define the kind of value a variable can hold. Below are the primary data types with examples.
1.1 Numeric Types
Numeric types include integers, floating-point numbers, and complex numbers.
# Integer: representing the width of a rectangle
width = 25
print("Width (int):", width, "Type:", type(width)) # Output: Width (int): 25 Type: <class 'int'>
# Float: representing the height of a rectangle
height = 5.11
print("Height (float):", height, "Type:", type(height)) # Output: Height (float): 5.11 Type: <class 'float'>
# Complex: representing a complex scaling factor for the rectangle
complex_scale = 3 + 4j
print("Complex scale (complex):", complex_scale, "Type:", type(complex_scale)) # Output: Complex scale (complex): (3+4j) Type: <class 'complex'>
# Using all numeric types together
area = width * height # Integer * Float
scaled_area = area * complex_scale # Float * Complex
print("Rectangle area (float):", area) # Output: Rectangle area (float): 127.75
print("Scaled area (complex):", scaled_area) # Output: Scaled area (complex): (383.25+511j)
1.2 String Type
Strings (str
) represent text data, enclosed in single or double quotes.
name = "Alice"
print(type(name)) # Output: <class 'str'>
print(name.upper()) # Output: ALICE
1.3 Boolean Type
Boolean (bool
) represents True
or False
values.
is_student = True
print(type(is_student)) # Output: <class 'bool'>
1.4 Sequence Types
Sequence types include lists, tuples, and ranges.
1.5 Set Types
Sets are unordered collections of unique items.
- Set (
set
): Mutable, unordered collection with no duplicates.
name = "Pankaj"
print(type(name)) # Output: <class 'str'>
print(name.upper()) # Output: Pankaj
1.6 Mapping Type
- Dictionary (
dict
): Key-value pairs.
is_student = True
print(type(is_student)) # Output: <class 'bool'>
2. Data Type Conversion
Type conversion, or type casting, allows you to convert one data type to another. Python provides built-in functions for this purpose.
2.1 Converting to Integer
Use int()
to convert to an integer.
float_num = 10.5
str_num = "15"
print(int(float_num)) # Output: 10
print(int(str_num)) # Output: 15
2.2 Converting to Float
Use float()
to convert to a floating-point number.
int_num = 10
str_float = "3.14"
print(float(int_num)) # Output: 10.0
print(float(str_float)) # Output: 3.14
2.3 Converting to String
Use str()
to convert to a string.
num = 42
bool_val = True
print(str(num)) # Output: "42"
print(str(bool_val)) # Output: "True"
2.4 Converting to List, Tuple, or Set
Convert between sequence types using list()
, tuple()
, or set()
.
tuple_data = (1, 2, 3)
str_data = "hello"
print(list(tuple_data)) # Output: [1, 2, 3]
print(tuple(str_data)) # Output: ('h', 'e', 'l', 'l', 'o')
print(set(str_data)) # Output: {'h', 'e', 'l', 'o'}
3. Taking User Input
The input()
function allows you to capture user input as a string. You can convert the input to other types as needed.
3.1 Basic Input
name = input("Enter your name: ")
print("Hello, " + name)
3.2 Converting Input to Other Types
Since input()
returns a string, convert it for numerical operations.
age = int(input("Enter your age: "))
print("Next year, you will be", age + 1)
4. Operators in Python
Operators are symbols that perform operations on variables and values. Below are the main categories of operators.
4.1 Arithmetic Operators
Perform mathematical operations.
Operator | Description | Example |
---|---|---|
+ | Addition | 5 + 3 → 8 |
- | Subtraction | 5 - 3 → 2 |
* | Multiplication | 5 * 3 → 15 |
/ | Division | 5 / 2 → 2.5 |
// | Floor Division | 5 // 2 → 2 |
% | Modulus | 5 % 2 → 1 |
** | Exponentiation | 2 ** 3 → 8 |
a = 10
b = 3
print(a + b) # Output: 13
print(a // b) # Output: 3
print(a ** 2) # Output: 100
4.2 Comparison Operators
Compare two values and return a boolean.
Operator | Description | Example |
---|---|---|
== | Equal to | 5 == 5 → True |
!= | Not equal to | 5 != 3 → True |
> | Greater than | 5 > 3 → True |
< | Less than | 5 < 3 → False |
>= | Greater than or equal to | 5 >= 5 → True |
<= | Less than or equal to | 3 <= 5 → True |
x = 7
y = 4
print(x > y) # Output: True
print(x == y) # Output: False
4.3 Logical Operators
Combine boolean expressions.
Operator | Description | Example |
---|---|---|
and | True if both are true | True and False → False |
or | True if at least one is true | True or False → True |
not | Negates the boolean value | not True → False |
a = True
b = False
print(a and b) # Output: False
print(a or b) # Output: True
print(not a) # Output: False
4.4 Assignment Operators
Assign values to variables.
Operator | Description | Example |
---|---|---|
= | Assign | x = 5 |
+= | Add and assign | x += 3 → x = x + 3 |
-= | Subtract and assign | x -= 2 → x = x - 2 |
x = 10
x += 5
print(x) # Output: 15
x *= 2
print(x) # Output: 15
4.5 Membership Operators
Check if a value is in a sequence.
Operator | Description | Example |
---|---|---|
in | True if value is in sequence | "a" in "cat" → True |
not in | True if value is not in sequence | "z" not in "cat" → True |
text = "hello"
print("h" in text) # Output: True
print("z" not in text) # Output: True
4.6 Identity Operators
Check if two variables refer to the same object.
Operator | Description | Example |
---|---|---|
is | True if same object | x is y |
is not | True if not same object | x is not y |
a = [1, 2, 3]
b = a
c = [1, 2, 3]
print(a is b) # Output: True
print(a is c) # Output: False
Example :
# Example Task: Shopping Cost Calculator
# This program calculates the total cost of items with a discount based on user input,
# using only data types, type conversion, user input, and operators, without lists or dictionaries.
# User Input: Taking input for item prices and discount percentage
# String input for customer name
customer_name = input("Enter your name: ")
# Float input for price of first item
item1_price = float(input("Enter price of first item: "))
# Float input for price of second item
item2_price = float(input("Enter price of second item: "))
# Integer input for discount percentage
discount_percent = int(input("Enter discount percentage: "))
# Data Types
# Integer: number of items
num_items = 2
# Float: total price before discount
total_price = item1_price + item2_price
# Complex: representing a promotional multiplier (for demonstration)
promo_multiplier = 1 + 0.1j
# Boolean: check if discount is applied
is_discounted = discount_percent > 0
# String: store customer name (already defined above)
name_type = type(customer_name)
# Type Conversion
# Convert discount percentage to decimal (e.g., 10% -> 0.1)
discount_decimal = float(discount_percent) / 100
# Convert total price to string for display
total_price_str = str(total_price)
# Operators
# Arithmetic: Calculate discounted price
discount_amount = total_price * discount_decimal
final_price = total_price - discount_amount
# Comparison: Check if final price is non-negative
is_reasonable = final_price >= 0
# Logical: Combine conditions for output
can_proceed = is_reasonable and is_discounted
# Output results using normal print
print("Customer Name:", customer_name)
print("Customer Name Type (string):", name_type)
print("Number of Items (int):", num_items, "Type:", type(num_items))
print("Price of First Item (float):", item1_price, "Type:", type(item1_price))
print("Price of Second Item (float):", item2_price, "Type:", type(item2_price))
print("Total Price Before Discount (float):", total_price, "Type:", type(total_price))
print("Discount Applied (boolean):", is_discounted, "Type:", type(is_discounted))
print("Promotional Multiplier (complex):", promo_multiplier, "Type:", type(promo_multiplier))
print("Discount Amount (float):", discount_amount)
print("Final Price (float):", final_price)
print("Is Final Price Non-Negative? (comparison):", is_reasonable)
print("Can Proceed with Discount? (logical):", can_proceed)
print("Total Price as String (type conversion):", total_price_str)
# Example of using complex number (for demonstration)
complex_result = final_price * promo_multiplier
print("Promotional Price (complex, for demo):", complex_result)