Kodeclik Logo

Our Programs

Learn More

Schedule

Kodeclik Blog

You will encounter situations where you will need to compare inputs in Python. In other words, you might get two inputs from the user and then need to compare them and do something different depending on the result of the comparison.

The operator to compare inputs in Python changes depending on the data types you are comparing.

To compare integer inputs entered from the keyboard in Python, we can create a simple program that prompts the user for two integers and then compares them. Here's a program that accomplishes this task:

Note that in this program, we define a function called compare_integers that takes two parameters and returns a string describing their relationship.The main program itself prompts the user to enter two integers using the input() function. The int() function is used to convert the input strings to integers. The compare_integers function is called with the user's inputs, and the result is stored in the result variable. Finally, the program prints the result of the comparison.

The compare_integers function handles three cases. If the first number is greater than the second, it returns a string stating that fact. If the first number is less than the second, it returns a string stating that fact. If the numbers are equal, it returns a string stating that they are equal.

This program will work for various integer inputs, including positive numbers, negative numbers, and zero. But note that this program assumes the inputs are integers. If a user enters a non-integer value, the program will raise a ValueError. To make the program more robust, you could add error handling to deal with invalid inputs.

Here are some sample inputs and outputs for the above program:

It is very easy to modify the above program to compare the inputs assuming they are strings rather than integers:

Note that the program above is almost exactly the previous program except now the semantics of the “>” and “<” operators are different. Here these symbols mean whether a given string appears lexicographically ahead of or behind the other string. If the user enters "apple" and "banana", the output will be '"apple" occurs before "banana" lexicographically.' If the user enters "zebra" and "apple", the output will be '"zebra" occurs after "apple" lexicographically.' If the user enters "grape" and "grape", the output will be '"grape" is equal to "grape".'

Here are some sample outputs:

You can extend the above program to use loops to compare multiple sets of strings in Python. Here's an example of how you can do this:

In this program, we define a compare_string_sets function that takes a list of string sets as input. The function uses nested loops to compare each set with every other set that comes after it in the list. For each pair of sets, it compares every string in the first set with every string in the second set. The compare_strings function is used to determine the lexicographic relationship between each pair of strings. The results of each comparison are printed.

When you run this program with the example string sets, it will output the lexicographic comparisons for each pair of strings across all sets. For example:

Let us try to compare two dictionaries! Note that dictionaries are associative arrays, mapping keys to values. So when comparing them it could be the case that they have different keys, or same keys but different values for those keys. We need to check for all these situations. Thus, the below program identifies the differences between the dictionaries, including keys that exist in only one dictionary and keys that have different values in both dictionaries.

The above program defines a function called compare_dictionaries that compares two dictionaries and identifies their differences. The function uses set operations on dictionary keys to efficiently compare the dictionaries. It first looks at keys present in both dictionaries and checks if their values are different. Then, it identifies keys that are unique to each dictionary. The function stores these differences itself in a new dictionary, where each entry represents a difference, showing the value from each original dictionary or None if the key doesn't exist in one of them.

After defining the function, the program demonstrates its usage with two sample dictionaries. It calls the compare_dictionaries function with these dictionaries and stores the result. The result is a dictionary containing all the differences between the input dictionaries.

Finally, the program prints out the differences in a readable format. For each difference found, it displays the key and the corresponding values from both dictionaries. This output clearly shows which keys are present in only one dictionary and which keys have different values across the two dictionaries. The program provides a comprehensive comparison, making it easy to understand exactly how the two input dictionaries differ from each other.

The output will be:

Let us now write a comparison program to compare two custom objects. Let us create a custom Month object that has information about the name of the month, the index of the month (ie a number from 1-12), and the number of days in the month. Then we will create multiple comparison methods: month name alphabetically, month index in ascending order, or by number of days.

Note that if we are comparing January with February, Jan is “less than” Feb in index but “greater than” Feb alphabetically and in the number of days.

How to compare inputs in Python

Here's the implementation:

The output is:

This output demonstrates how the different comparison methods work. When comparing by name, "January" comes before "February", but "March" does not come before "February". When comparing by index, January (1) comes before April (4), but March (3) does not come before February (2). When comparing by days, January (31 days) does not come before April (30 days), but February (28 days) comes before March (31 days).

The __repr__ method provides a clear string representation of each Month object, making it easy to see all the attributes at once.

This implementation allows for flexible comparisons between Month objects based on different criteria, as requested in the query.

Thus the main takeaway from this blogpost is that it is easy to compare two inputs in Python once you know the data type of the objects being compared. For objects like integers and strings, the built-in comparison operators work with the expected semantics. For more complex structures you should define your comparison operators to achieve the desired semantics.

If you liked this blogpost, checkout our post on control structures in Python and the Python “switch” statement (ie the match-case).

Want to learn Python with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.