Python Homework: Assignment Operators and
String Operations
# Homework: Assignment Operators and String Operations
# 1. Assign a value 50 to a variable and use different assignment operators step
by step
a = 50
print("Initial a =", a)
a += 10
print("After a += 10:", a)
a -= 5
print("After a -= 5:", a)
a *= 2
print("After a *= 2:", a)
a /= 3
print("After a /= 3:", a)
a //= 4
print("After a //= 4:", a)
a %= 7
print("After a %= 7:", a)
print()
# 2. Take a number from the user and update it using **= to square it
num = int(input("Enter a number: "))
num **= 2
print("Square of the number:", num)
print()
# 3. Take two numbers from the user and apply assignment operators
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
temp = x
x += y
print("x += y:", x)
x = temp
x -= y
print("x -= y:", x)
x = temp
x *= y
print("x *= y:", x)
x = temp
x /= y
print("x /= y:", x)
x = temp
x //= y
print("x //= y:", x)
x = temp
x %= y
print("x %= y:", x)
x = temp
x **= y
print("x **= y:", x)
print()
# 4. Get a string and print first, middle, last character
s = input("Enter a string: ")
if len(s) > 0:
print("First:", s[0])
print("Middle:", s[len(s)//2])
print("Last:", s[-1])
print()
# 5. Print string in reverse using slicing
s = input("Enter a string to reverse: ")
print("Reversed string:", s[::-1])
print()
# 6. Take a string input and print every second character
s = input("Enter a string: ")
print("Every second character:", s[::2])
print()
# 7. Take a word and print first 3 and last 3 characters
word = input("Enter a word: ")
if len(word) < 3:
print("Word is too short:", word)
else:
print("First three:", word[:3])
print("Last three:", word[-3:])
print()
# 8. Find length of a given sentence
sentence = input("Enter a sentence: ")
print("Length of the sentence:", len(sentence))
print()
# 9. Display string in different cases
s = input("Enter a string: ")
print("Lowercase:", [Link]())
print("Uppercase:", [Link]())
print("Title case:", [Link]())
print("Capitalize:", [Link]())
print()
# 10. Remove spaces from start and end of string
s = input("Enter a string with spaces at start/end: ")
print("After strip:", [Link]())
print()
# 11. Apply .strip(), .lstrip(), .rstrip()
s = input("Enter a string with extra spaces: ")
print("strip():", [Link]())
print("lstrip():", [Link]())
print("rstrip():", [Link]())
print()
# 12. Find index of 'Python'
s = "I love Python programming"
print("Index of 'Python':", [Link]("Python"))
print()
# 13. Replace 'Python' with 'Java'
s = "Python is powerful"
print("Before:", s)
print("After:", [Link]("Python", "Java"))
print()
# 14. Check if 'data' exists in sentence
sentence = input("Enter a sentence: ")
if "data" in [Link]():
print("The word 'data' exists in the sentence.")
else:
print("The word 'data' does not exist.")
print()
# 15. Replace all occurrences of 'ai' with 'ML'
s = "ai is the future of ai world"
print("Before:", s)
print("After:", [Link]("ai", "ML"))