Assignment 1 - Solutions

📝 Data Types & Strings

Complete solutions with detailed explanations

📋 Questions & Solutions

1 Create two numbers. One float another integer. Add two numbers and print the result in integer format.
# Create a float and an integer
float_num = 3.14
int_num = 5

# Add them together
result = float_num + int_num
print("Sum (float):", result)

# Convert to integer and print
result_int = int(result)
print("Sum (integer):", result_int)
Output
Sum (float): 8.14
Sum (integer): 8

🎓 Explanation

int() truncates the decimal part (doesn't round). 8.14 becomes 8, not 8.14 rounded to 8.

2 "i live in india since my childhood". Count number of 'i' in this text.
text = "i live in india since my childhood"

# Count lowercase 'i'
count = text.count('i')
print("Number of 'i':", count)
Output
Number of 'i': 6

🎓 Explanation

.count() is case-sensitive. It counts: "i" (1st word), "i" in live, "i" in in, "i" and "i" in india, "i" in since, "i" in childhood = 6 total.

3 How do you check if a variable is of a certain data type in Python?
# Method 1: type() function
x = 10
print("Type of x:", type(x))
print("Is x an int?", type(x) == int)

# Method 2: isinstance() function (recommended)
y = "Hello"
print("Is y a string?", isinstance(y, str))

# isinstance can check multiple types
z = 3.14
print("Is z int or float?", isinstance(z, (int, float)))
Output
Type of x: <class 'int'>
Is x an int? True
Is y a string? True
Is z int or float? True

🎓 Explanation

type() returns the exact type. isinstance() is preferred because it also works with inheritance and can check multiple types at once.

4 Write a python code to find last 4 characters of a string: 'Machine Learning'
text = "Machine Learning"

# Using negative slicing
last_4 = text[-4:]
print("Last 4 characters:", last_4)
Output
Last 4 characters: ning

🎓 Explanation

[-4:] means start from 4th character from end, go till end. Negative indexing: -1 is last char, -2 is second last, etc.

5 Write a python code to remove trailing space from string: 'Machine Learning. '
text = "Machine Learning. "

# Remove trailing whitespace
cleaned = text.rstrip()
print("Original:", repr(text))
print("Cleaned:", repr(cleaned))

# Alternative: strip() removes from both ends
text2 = "  Hello World  "
print("strip():", repr(text2.strip()))
Output
Original: 'Machine Learning. '
Cleaned: 'Machine Learning.'
strip(): 'Hello World'

🎓 Explanation

rstrip() removes trailing (right) whitespace. lstrip() removes leading (left). strip() removes both ends. repr() shows the string with quotes to visualize spaces.

6 Write a Python program to print every second character from the string: "Data Science with Python"
text = "Data Science with Python"

# Using slicing with step 2
every_second = text[::2]
print("Every second character:", every_second)

# Alternative: manual loop
result = ""
for i in range(0, len(text), 2):
    result += text[i]
print("Loop method:", result)
Output
Every second character: Dt cec ihPto
Loop method: Dt cec ihPto

🎓 Explanation

[::2] means start:end:step. Empty start/end = full string, step 2 = every 2nd char. Characters at index 0, 2, 4, 6... are selected.

7 Write a python code to check given character is digit or not: 265
# Convert to string first if it's an integer
value = 265
value_str = str(value)

# Check if all characters are digits
is_digit = value_str.isdigit()
print(f"'{value}' is digit: {is_digit}")

# Can also check individual characters
text = "Hello123"
for char in text:
    print(f"'{char}' is digit: {char.isdigit()}")
Output
'265' is digit: True
'H' is digit: False
'e' is digit: False
'l' is digit: False
'l' is digit: False
'o' is digit: False
'1' is digit: True
'2' is digit: True
'3' is digit: True

🎓 Explanation

.isdigit() returns True if all characters in the string are digits (0-9). It's a string method, so convert numbers to string first.

8 Write a python code to Convert a string to lowercase: 'MACHINE LEARNING'
text = "MACHINE LEARNING"

# Convert to lowercase
lowercase = text.lower()
print("Lowercase:", lowercase)

# Also useful: upper(), title(), capitalize()
print("Upper:", text.upper())
print("Title:", text.title())
print("Capitalize:", text.capitalize())
Output
Lowercase: machine learning
Upper: MACHINE LEARNING
Title: Machine Learning
Capitalize: Machine learning

🎓 Explanation

.lower() converts all to lowercase. .upper() to uppercase. .title() capitalizes each word. .capitalize() only first letter of string.

9 Write a python code to count the number of occurrences of a character 'e' in a string: 'Machine Learning and Deep Learning'
text = "Machine Learning and Deep Learning"

# Count occurrences of 'e'
count = text.count('e')
print(f"Number of 'e': {count}")

# Case-insensitive count (if needed)
count_all = text.lower().count('e')
print(f"Number of 'e' (case-insensitive): {count_all}")
Output
Number of 'e': 5
Number of 'e' (case-insensitive): 5

🎓 Explanation

.count('e') counts all lowercase 'e'. The 'e' appears in: Machine, Learning (x2), Deep, Learning (x2) = 5 times.

10 Write a python code to check if a string contains only alphabetic characters. String = 'HelloPython'
string1 = "HelloPython"
string2 = "Hello Python"  # has space
string3 = "Hello123"      # has numbers

print(f"'{string1}' is alphabetic: {string1.isalpha()}")
print(f"'{string2}' is alphabetic: {string2.isalpha()}")
print(f"'{string3}' is alphabetic: {string3.isalpha()}")
Output
'HelloPython' is alphabetic: True
'Hello Python' is alphabetic: False
'Hello123' is alphabetic: False

🎓 Explanation

.isalpha() returns True ONLY if ALL characters are letters (a-z, A-Z). Spaces, numbers, and special characters make it False.