fork download
  1. def validate_imei(imei: str) -> bool:
  2. """
  3. Function to validate the International Mobile Equipment Identity (IMEI) number.
  4.  
  5. IMEI is a unique identifier for mobile devices, consisting of 15 digits.
  6. The last digit is a check digit calculated using the Luhn algorithm.
  7.  
  8. Parameters:
  9. - imei: str
  10. The IMEI number to be validated.
  11.  
  12. Returns:
  13. - bool:
  14. True if the IMEI is valid, False otherwise.
  15.  
  16. Raises:
  17. - ValueError:
  18. Raises an error if the IMEI is not a string or if it does not consist of exactly 15 digits.
  19. """
  20.  
  21. # Checking if the IMEI is a string and consists of exactly 15 digits
  22. if not isinstance(imei, str) or not imei.isdigit() or len(imei) != 15:
  23. raise ValueError("IMEI should be a string consisting of exactly 15 digits.")
  24.  
  25. # Calculating the check digit using the Luhn algorithm
  26. check_digit = int(imei[-1])
  27. imei_digits = [int(digit) for digit in imei[:-1]]
  28. imei_digits.reverse()
  29.  
  30. for i in range(len(imei_digits)):
  31. if i % 2 == 0:
  32. imei_digits[i] *= 2
  33. if imei_digits[i] > 9:
  34. imei_digits[i] -= 9
  35.  
  36. calculated_check_digit = (10 - sum(imei_digits) % 10) % 10
  37.  
  38. # Validating the check digit
  39. return check_digit == calculated_check_digit
  40.  
  41. # Example usage:
  42. imei_number = "123456789012345"
  43. is_valid = validate_imei(imei_number)
  44. print(f"The IMEI number {imei_number} is valid: {is_valid}")
Success #stdin #stdout #stderr 0.02s 6864KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
ERROR: /home/whFcj9/prog:44:59: Syntax error: Unexpected end of file
ERROR: '$runtoplevel'/0: Undefined procedure: program/0
   Exception: (3) program ? EOF: exit