Write a Python Function That Compares Between Two Strings And Return The Longest One

Given two strings as input to the Python program the Python program should evaluate the string length and try to compare the length of a string with another string.

After comparing Length of the string return the string that is longest.

Write a Python Function That Compares Between Two Strings And Return The Longest One




Write a Python Function That Compares Between Two Strings And Return The Longest One

Define a function named compare strings and give the input as X and Y,  these x and y are the two strings that are provided as an input to the Python program.  In the  function get the length of each string and use the if statement to compare the length of two things.  return the string that is Greater in length

def compare_strings(x, y):
   if len(x) > len(y):
       return x
   return y


Once we define a function and get the longest string.  in the main program  take two strings string 1 and string 2,  to ask a user to enter  both the strings using input function call.

string1 = input("Enter First String : ")
string2 = input("Enter Second String : ")




Take another variable named as long_string and call the function by passing string 1 and string 2 as input  arguments to the function.

Once we get the longest string from the function as a return value print the the longest string on to the console using printf function call.
 
longest_string = compare_strings(string1, string2)
print("Longest string is : ", longest_string)




Final  program
====================

def compare_strings(x, y):
   if len(x) > len(y):
       return x
   return y


string1 = input("Enter First String : ")
string2 = input("Enter Second String : ")

longest_string = compare_strings(string1, string2)

print("Longest string is : ", longest_string)





Output
================


Enter First String : hi
Enter Second String : hello
Longest string is :  hello




Output
==================

Enter First String : hello world
Enter Second String : how are you
Longest string is :  how are you



Conclusion
===================

Try running the program by yourself by providing the input argument random strings and see the result.




Post a Comment

0 Comments