fork download
  1. import re
  2.  
  3. def validate(cpf: str) -> bool:
  4. """ Valida o CPF """
  5. # Verifica a formatação do CPF
  6. if not re.match(r'\d{3}\.\d{3}\.\d{3}-\d{2}', cpf):
  7. return False
  8. numbers = [int(digit) for digit in cpf if digit.isdigit()]
  9. # Verifica se o CPF possui 11 números:
  10. if len(numbers) != 11:
  11. return False
  12. # Validação do primeiro dígito verificador:
  13. sum_of_products = sum(a*b for a, b in zip(numbers[0:9], range(10, 1, -1)))
  14. expected_digit = (sum_of_products * 10 % 11) % 10
  15. if numbers[9] != expected_digit:
  16. return False
  17. # Validação do segundo dígito verificador:
  18. sum_of_products = sum(a*b for a, b in zip(numbers[0:10], range(11, 1, -1)))
  19. expected_digit = (sum_of_products * 10 % 11) % 10
  20. if numbers[10] != expected_digit:
  21. return False
  22. return True
  23.  
  24. try:
  25. cpf = '529.982.247-25'
  26. assert validate(cpf), 'O CPF informado não é válido'
  27. except AssertionError as error:
  28. print(error)
Success #stdin #stdout 0.04s 9528KB
stdin
Standard input is empty
stdout
Standard output is empty