47.6k views
2 votes
longest string write a program that takes two strings and returns the longest string. if they are the same length then return the second string. ex. if the input is: almond pistachio

User Daniex
by
8.6k points

1 Answer

5 votes

Final answer:

To return the longest string out of two input strings, compare their lengths using an if-else statement. If they are the same length, return the second string. Otherwise, return the longer string.

Step-by-step explanation:

To write a program that returns the longest string out of two input strings, you can use an if-else statement to compare the lengths of the two strings. If the first string is longer than the second string, return the first string. If the second string is longer or if the two strings have the same length, return the second string.

Here's the code in Python:

def longest_string(str1, str2):

if len(str1) > len(str2):

return str1

else:

return str2

# Testing the function

string1 = "almond"

string2 = "pistachio"

result = longest_string(string1, string2)

print(result) # Output: pistachio

User Inas
by
8.1k points