Kodeclik Blog
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.
Popular Classes
Scratch Coding
Minecraft Coding
TinkerCAD
Roblox Studio
Python for Kids
Javascript for Kids
Pre-Algebra
Geometry for Kids
Copyright @ Kodeclik 2024. All rights reserved.
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.
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.
def compare_integers(num1, num2):
if num1 > num2:
return f"{num1} is greater than {num2}"
elif num1 < num2:
return f"{num1} is less than {num2}"
else:
return f"{num1} is equal to {num2}"
# Get input from the user
input1 = int(input("Enter the first integer: "))
input2 = int(input("Enter the second integer: "))
# Compare the integers and print the result
result = compare_integers(input1, input2)
print(result)
Enter the first integer: 10
Enter the second integer: 5
10 is greater than 5
Enter the first integer: -7
Enter the second integer: -3
-7 is less than -3
Enter the first integer: 6
Enter the second integer: 6
6 is equal to 6
Enter the first integer: 0
Enter the second integer: -9
0 is greater than -9
def compare_strings(str1, str2):
if str1 < str2:
return f'"{str1}" occurs before "{str2}" lexicographically.'
elif str1 > str2:
return f'"{str1}" occurs after "{str2}" lexicographically.'
else:
return f'"{str1}" is equal to "{str2}".'
# Get input from the user
input1 = input("Enter the first string: ")
input2 = input("Enter the second string: ")
# Compare the strings and print the result
result = compare_strings(input1, input2)
print(result)
Enter the first string: zebra
Enter the second string: aardvark
"zebra" occurs after "aardvark" lexicographically.
Enter the first string: mouse
Enter the second string: Cat
"mouse" occurs after "Cat" lexicographically.
Enter the first string: new york
Enter the second string: paris
"new york" occurs before "paris" lexicographically.
def compare_string_sets(sets):
for i, set1 in enumerate(sets):
for j, set2 in enumerate(sets[i+1:], start=i+1):
print(f"Comparing Set {i+1} and Set {j+1}:")
for str1 in set1:
for str2 in set2:
comparison = compare_strings(str1, str2)
print(f" {comparison}")
print() # Add a blank line between set comparisons
def compare_strings(str1, str2):
if str1 < str2:
return f'"{str1}" occurs before "{str2}" lexicographically'
elif str1 > str2:
return f'"{str1}" occurs after "{str2}" lexicographically'
else:
return f'"{str1}" is equal to "{str2}"'
# Example usage
string_sets = [
["dog", "tiger"],
["cat", "lion"],
["aardvark", "goat"]
]
compare_string_sets(string_sets)
Comparing Set 1 and Set 2:
"dog" occurs after "cat" lexicographically
"dog" occurs before "lion" lexicographically
"tiger" occurs after "cat" lexicographically
"tiger" occurs after "lion" lexicographically
Comparing Set 1 and Set 3:
"dog" occurs after "aardvark" lexicographically
"dog" occurs before "goat" lexicographically
"tiger" occurs after "aardvark" lexicographically
"tiger" occurs after "goat" lexicographically
Comparing Set 2 and Set 3:
"cat" occurs after "aardvark" lexicographically
"cat" occurs before "goat" lexicographically
"lion" occurs after "aardvark" lexicographically
"lion" occurs after "goat" lexicographically
def compare_dictionaries(dict1, dict2):
differences = {}
# Compare keys that are in both dictionaries
for key in dict1.keys() & dict2.keys():
if dict1[key] != dict2[key]:
differences[key] = {'dict1': dict1[key], 'dict2': dict2[key]}
# Find keys that are only in dict1
for key in dict1.keys() - dict2.keys():
differences[key] = {'dict1': dict1[key], 'dict2': None}
# Find keys that are only in dict2
for key in dict2.keys() - dict1.keys():
differences[key] = {'dict1': None, 'dict2': dict2[key]}
return differences
# Example usage
dictionary1 = {'a': 1, 'b': 2, 'c': 3}
dictionary2 = {'a': 1, 'b': 4, 'd': 5}
# Compare the dictionaries and get differences
result = compare_dictionaries(dictionary1, dictionary2)
# Print the results
print("Differences between the dictionaries:")
for key, value in result.items():
print(f"Key: {key}")
print(f" Dictionary 1: {value['dict1']}")
print(f" Dictionary 2: {value['dict2']}")
print()
Differences between the dictionaries:
Key: b
Dictionary 1: 2
Dictionary 2: 4
Key: c
Dictionary 1: 3
Dictionary 2: None
Key: d
Dictionary 1: None
Dictionary 2: 5
class Month:
def __init__(self, name, index, days):
self.name = name
self.index = index
self.days = days
def compare_by_name(self, other):
return self.name < other.name
def compare_by_index(self, other):
return self.index < other.index
def compare_by_days(self, other):
return self.days < other.days
def __repr__(self):
return f"Month(name='{self.name}', index={self.index}, days={self.days})"
# Create some Month objects
january = Month("January", 1, 31)
february = Month("February", 2, 28)
march = Month("March", 3, 31)
april = Month("April", 4, 30)
# Compare months by name
print("Comparing by name:")
print(f"{january.name} < {february.name}:", january.compare_by_name(february))
print(f"{march.name} < {february.name}:", march.compare_by_name(february))
# Compare months by index
print("\nComparing by index:")
print(f"{january.name} < {april.name}:", january.compare_by_index(april))
print(f"{march.name} < {february.name}:", march.compare_by_index(february))
# Compare months by number of days
print("\nComparing by number of days:")
print(f"{january.name} < {april.name}:", january.compare_by_days(april))
print(f"{february.name} < {march.name}:", february.compare_by_days(march))
# Demonstrate the __repr__ method
print("\nMonth representations:")
print(january)
print(february)
print(march)
print(april)
Comparing by name:
January < February: False
March < February: False
Comparing by index:
January < April: True
March < February: False
Comparing by number of days:
January < April: False
February < March: True
Month representations:
Month(name='January', index=1, days=31)
Month(name='February', index=2, days=28)
Month(name='March', index=3, days=31)
Month(name='April', index=4, days=30)