Python program to find larger string among two strings

Python program to find larger string among two strings :

In this tutorial, we will learn how to find the larger string among two user input strings in python.The user will enter two strings, our program will read them both and without using any inbuilt function, it will calculate the length of each strings. Then print out the result to the user which one is larger. Let’s take a look at the program first :

Python program to find larger string :

#1
first_string = input("Enter the first string : ")
second_string = input("Enter the second string : ")

length1 = 0
length2 = 0

#2
for i in first_string:
    length1 = length1 + 1

#3
for i in second_string:
    length2 = length2 + 1

#4
if length1 > length2 :
    print("First string is larger than the second")
else :
    print("Second string is larger than the first")

Explanation :

The commented number in the above program denote the step number below :

1. Ask the user to enter the first string. Read it and save it in first_string variable. Similarly, read the second string and save it in second_string variable.
2. To calculate the length of a string, we are using one for loop here. It scan each character of the string. For each character, increment the value of length1 by 1. length1 is holding the size of the first string.
3. Similarly, calculate the length of the second string and store the length in variable length2.
4. After the lengths are calculated, check which one is greater. Also print out the message accordingly.

Sample Output :

Enter the first string : this is the first string
Enter the second string : this is the second string
Second string is larger than the first

Enter the first string : first
Enter the second string : second
Second string is larger than the first

Enter the first string : blahhh
Enter the second string : bla
First string is larger than the second

Leave a Reply