Python Type Conversion, Data Structures and Example Programs

Type Conversion in Python: Types and Examples

Answer:
Type conversion means converting one data type into another. There are two types:

Implicit Type Conversion

Python automatically converts smaller or compatible data types into larger or compatible types to prevent data loss.

x = 10    # int
y = 5.5   # float
z = x + y
print(z)        # 15.5
print(type(z))  # <class 'float'>

Explicit Type Conversion

The user manually converts one data type to another using functions like int(), float(), str(), etc.

Example:

x = "100"
y = int(x)
print(y + 20)   # 120
print(type(y))  # <class 'int'>

Q2: Print with sep and end

print(10, 20, 30, 40, sep='hello', end='\t')

Explanation:

  • sep='hello' → Adds “hello” between values.
  • end='\t' → Ends the print statement with a tab instead of a newline.

Output:

10hello20hello30hello40	

Q3: Boolean and Numeric Conversions

(i)

a = True
b = int(a)
print(a)
print(b)

Output:

True
1

(Because True1 in Python.)


(ii)

print(True + True)

Output:

2

(Because True = 1 and 1 + 1 = 2.)

(iii)

print(True + 5)

Output:

6

(Because True = 1, so 1 + 5 = 6.)


(iv)

a = '9.8'
b = float(a)
print(a)
print(b)

Output:

9.8
9.8

(The string "9.8" is converted to a float.)


(v)

print(4 + 3.4)
print(4 + int(3.4))

Output:

7.4
7

Q4: Count Total Number of Digits in a Number

num = 758691
count = len(str(num))
print("Total digits:", count)

Output:

Total digits: 6

Q5: Print Integers 100 to 200 Whose Sum of Digits Is Even

for num in range(100, 201):
    digits_sum = sum(int(d) for d in str(num))
    if digits_sum % 2 == 0:
        print(num, end=" ")

Output:
It will print numbers like:

101 110 112 121 130 132 ... up to 200

Q1(a): Define Module, Package, Framework

  • Module → A single .py file that contains Python functions, classes, or variables.

    # example: math module
    import math
    print(math.sqrt(16))  # 4.0
    
  • Package → A collection of modules stored in a directory with an __init__.py file.

    # example: using numpy package
    import numpy
    print(numpy.array([1, 2, 3]))
    
  • Framework → A collection of packages and libraries that provides a structured environment for developing applications.
    Examples: Django, Flask, TensorFlow

Q1(b): Method Chaining with Example

Definition:
Method chaining allows us to call multiple methods on the same object in a single line.

Input: aBcDeF
Output: ZBCDEF

Using method chaining:

s = "aBcDeF"
result = s.upper().replace("A", "Z")
print(result)

Without method chaining:

s = "aBcDeF"
s = s.upper()
s = s.replace("A", "Z")
print(s)

Output:

ZBCDEF

Q1(c): List Extend Example

li = [10, 20, 30]
li.extend([0, -5, 100])
print(li)

Output:

[10, 20, 30, 0, -5, 100]

Q1(d): Valid / Invalid Python Statements

StatementValid / InvalidReason
x = input("enter a number")✅ ValidCorrect syntax
x = input()✅ ValidDefault input accepted
x = input("")✅ ValidEmpty prompt allowed
x = input(" ")✅ ValidSpace prompt allowed
x = input(2)❌ InvalidPrompt must be a string, not an int
x = input("2" + "3")✅ Valid"2" + "3" = "23" prompt

Q1(e): List Slicing Outputs

(i)

lst = [10, 20, 30, 40, 50]
print(lst[1:4])

Output: [20, 30, 40]

(ii)

lst = [5, 10, 15, 20, 25, 30]
print(lst[:2])

Output: [5, 10]

(iii)

st1 = "good morning"
print(st1[::-1])

Output: gninrom doog

Q1(f): Generate a 4-Digit OTP

import random
otp = random.randint(1000, 9999)
print("Your 4-digit OTP is:", otp)

Sample Output:

Your 4-digit OTP is: 4721

Q2: Set Operations Examples

S1 = {10, 20, 30}
S2 = {20, 30, 50}

print("Union:", S1 | S2)
print("Intersection:", S1 & S2)
print("Difference:", S1 - S2)
print("Symmetric Difference:", S1 ^ S2)

Output:

Union: {10, 20, 30, 50}
Intersection: {20, 30}
Difference: {10}
Symmetric Difference: {10, 50}

Python Arithmetic Operators Program

a = 15
b = 4

print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Floor Division:", a // b)
print("Modulus:", a % b)
print("Exponent:", a ** b)

Output:

Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3.75
Floor Division: 3
Modulus: 3
Exponent: 50625

elif Statement: Syntax and Example

Syntax

if condition1:
    # Code block 1
elif condition2:
    # Code block 2
else:
    # Code block 3

Example

marks = 78
if marks >= 90:
    print("Grade A")
elif marks >= 75:
    print("Grade B")
elif marks >= 50:
    print("Grade C")
else:
    print("Fail")

Output

Grade B

Tabulate Numbers and Squares

Let’s assume you need to tabulate results of numbers and their squares:

print("Number\tSquare")
for i in range(1, 6):
    print(i, "\t", i**2)
Output:
Number	Square
1	1
2	4
3	9
4	16
5	25

Q6: Six Assignment Operators with Examples

OperatorDescriptionExampleOutput
=Assigns valuex = 10x = 10
+=Adds and assignsx = 5; x += 3x = 8
-=Subtracts and assignsx = 10; x -= 4x = 6
*=Multiplies and assignsx = 4; x *= 3x = 12
/=Divides and assignsx = 20; x /= 5x = 4.0
//=Floor division and assignsx = 9; x //= 2x = 4

Q7: Find the Error / Output and Correction

(a)

thistuple = ("apple", "banana", "cherry")
thistuple[1] = "lime"
print(thistuple)

Error

TypeError: ‘tuple’ object does not support item assignment

Reason: Tuples are immutable → cannot modify elements.

Correction

thistuple = list(thistuple)
thistuple[1] = "lime"
thistuple = tuple(thistuple)
print(thistuple)

Output:

('apple', 'lime', 'cherry')
(b)
thistuple = ("a", "-b", "c")
print(thistuple[-2])
print(thistuple[-1])

Output:

-b
c

Explanation:

  • thistuple[-2] → second last element → "-b"
  • thistuple[-1] → last element → "c"

Q8: Python Lists — Accessing, Updating & Deleting

Definition

A list is an ordered, mutable collection of elements in Python. Created using [].

Example Program

# Creating a list
fruits = ["apple", "banana", "cherry"]

# Accessing values
print(fruits[0])   # apple
print(fruits[-1])  # cherry

# Updating values
fruits[1] = "mango"
print(fruits)      # ['apple', 'mango', 'cherry']

# Deleting elements
del fruits[2]
print(fruits)      # ['apple', 'mango']

Output

apple
cherry
['apple', 'mango', 'cherry']
['apple', 'mango']

Q9: Basic List Operations, Indexing, Slicing, Matrices & Methods

1. Basic Operations

list1 = [1, 2, 3]
list2 = [4, 5]
print(list1 + list2)  # Concatenation → [1, 2, 3, 4, 5]
print(list1 * 2)      # Repetition → [1, 2, 3, 1, 2, 3]
print(2 in list1)     # Membership → True

2. Indexing

nums = [10, 20, 30]
print(nums[0])   # 10
print(nums[-1])  # 30

3. Slicing

nums = [10, 20, 30, 40, 50]
print(nums[1:4])    # [20, 30, 40]
print(nums[::-1])   # Reverse list

4. Matrix Representation

matrix = [[1, 2], [3, 4]]
print(matrix[1][0])   # 3

6. List Methods

fruits = ["apple", "banana"]
fruits.append("cherry")    # Add element
fruits.insert(1, "mango")  # Insert at index
fruits.remove("banana")    # Remove element
fruits.pop()                 # Remove last element
fruits.clear()               # Empty list

Q10: Create a Class Dog with Attributes & Instances

class Dog:
    def __init__(self, breed, max_age, favorite_place):
        self.breed = breed
        self.max_age = max_age
        self.favorite_place = favorite_place

# Creating objects
dog1 = Dog("Labrador", 12, "Park")
dog2 = Dog("German Shepherd", 14, "Beach")

# Accessing attributes
print(dog1.breed, dog1.max_age, dog1.favorite_place)
print(dog2.breed, dog2.max_age, dog2.favorite_place)

Output

Labrador 12 Park
German Shepherd 14 Beach