Write a Python program to check the absolute difference between two consecutive digits is two or not. Return true otherwise false


The code you provided defines a Python function has_absolute_difference_of_two and uses it to check if the absolute difference between consecutive digits of a user-input number is always equal to 2. Here's a step-by-step explanation of how this code works:

  • The has_absolute_difference_of_two function takes an integer number as its argument.
  • Inside the function, the integer number is converted to a string num_str using str(number). This allows you to work with individual digits of the number as characters in the string.
  • The function then enters a for loop that iterates over the characters of the string num_str. The loop starts at index 1 (the second character) and goes up to the length of the string. In this loop, the absolute difference between consecutive digits (as integers) is calculated using int(num_str[i]) - int(num_str[i - 1]) .
  • The code checks if the calculated difference is not equal to 2 using the if diff != 2 condition. If any pair of consecutive digits has an absolute difference other than 2, the function immediately returns False, indicating that the absolute difference between consecutive digits is not two for this number.
  • If the loop completes without encountering any non-2 absolute differences, the function returns True, indicating that the absolute difference between consecutive digits is two for the entire number.
  • Outside the function, the code prompts the user to enter a number using input("Enter a number: ") and converts the user's input to an integer num.
  • The has_absolute_difference_of_two function is then called with the user's input number, and the result is stored in the result variable.
  • Finally, the code prints a message based on the value of result. If result is True, it prints "The absolute difference between consecutive digits is two," indicating that the condition is satisfied. Otherwise, it prints "The absolute difference between consecutive digits is not two," indicating that the condition is not met.

Source Code

def has_absolute_difference_of_two(number):
    num_str = str(number)
    for i in range(1, len(num_str)):
        # Calculate the absolute difference between consecutive digits
        diff = abs(int(num_str[i]) - int(num_str[i - 1]))
 
        # Check if the difference is not equal to 2
        if diff != 2:
            return False
 
    return True
 
num = int(input("Enter a number: "))
 
result = has_absolute_difference_of_two(num)
if result:
    print("The absolute difference between consecutive digits is two")
else:
    print("The absolute difference between consecutive digits is not two")

Output

Numbers = 2014
Minimum Numbers = 0124
Maximum Numbers = 4210

Example Programs