text = input("Enter a string: ")
if len(text) > 0:
print("First character:", text[0])
print("Last character:", text[-1])
else:
print("The string is empty!")
#source code --> clcoding.com
Code Explanation:
Take user input
input("Enter a string: ") → Asks the user to enter a string.
Check if the string is not empty
if len(text) > 0: → Ensures the input is not empty before accessing characters.
Print the first character
text[0] → Index 0 gives the first character of the string.
Print the last character
text[-1] → Index -1 gives the last character of the string.
Handle empty string cases
If the user enters an empty string, the program prints "The string is empty!" instead of throwing an error.
0 Comments:
Post a Comment