Exercise 65

Write a Python algorithm which takes a string 's' as input and returns True if the first character is the same as the last character of the string 's', and False otherwise. Example: if s = "render", the function must returns True. If s = "Python" the function returns False.

Solution

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
def first_last_char_same(s):
# Get the first character of the string
first_char = s[0]
# Get the last character of the string
last_char = s[-1]
# Compare the first and last characters
if first_char == last_char:
return True
else:
return False
#Example of use of this function:
"""
In the first example, the first and last characters of the string "render" are both "r", so the function returns True. In the sec
result = first_last_char_same("render")
print(result) # True
result = first_last_char_same("Python")
print(result) # False
ond example, the first and last characters of the string "Python" are different, so the function returns False.
"""
def first_last_char_same(s): # Get the first character of the string first_char = s[0] # Get the last character of the string last_char = s[-1] # Compare the first and last characters if first_char == last_char: return True else: return False #Example of use of this function: """ In the first example, the first and last characters of the string "render" are both "r", so the function returns True. In the sec result = first_last_char_same("render") print(result) # True result = first_last_char_same("Python") print(result) # False ond example, the first and last characters of the string "Python" are different, so the function returns False. """
def first_last_char_same(s):
    # Get the first character of the string
    first_char = s[0]
    # Get the last character of the string
    last_char = s[-1]
    # Compare the first and last characters
    if first_char == last_char:
        return True
    else:
        return False

#Example of use of this function:
"""
In the first example, the first and last characters of the string "render" are both "r", so the function returns True. In the sec
result = first_last_char_same("render")
print(result)  # True

result = first_last_char_same("Python")
print(result)  # False
ond example, the first and last characters of the string "Python" are different, so the function returns False.
"""




 

Younes Derfoufi
my-courses.net

One thought on “Solution Exercise 65: python algorithm that test if the first character is equal to the last”

Leave a Reply