Skip to content

Instantly share code, notes, and snippets.

@rvente
Last active April 1, 2022 03:31
Show Gist options
  • Save rvente/03e6da27ae0d0f72b7d4fe28f95f4a6f to your computer and use it in GitHub Desktop.
Save rvente/03e6da27ae0d0f72b7d4fe28f95f4a6f to your computer and use it in GitHub Desktop.
prompt = "Enter a hex digit: "
reject_too_long = "Only one number must be input."
reject_invalid_input = "Invalid input"
hex_candidate = input(prompt).upper()
if len(hex_candidate) != 1:
print(reject_too_long)
elif not hex_candidate.isalnum():
print(reject_invalid_input)
elif not "A" <= hex_candidate <= "F":
# by this point digit is alphanumeric
# so we only have to check if it's in range [A, F]
print(reject_invalid_input)
else:
numeric = int(hex_candidate, 16)
print(bin(numeric)[2:])
prompt = "Enter the first 9 digits of an ISBN string: "
reject_non_nine = "Incorrect Input. It must have exact 9 digits"
reject_non_numeric = "Incorrect Input. All should be digits."
accept_msg = "The ISBN-10 number is"
nine_digits = input(prompt)
if len(nine_digits) != 9:
print(reject_non_nine)
elif not nine_digits.isdecimal():
# should not be needed but required for safety
print(reject_non_numeric)
else: # numeric and length 9
running_total = 0
for index,digit in enumerate(nine_digits):
running_total += (index+1) * int(digit)
checksum_string = str(running_total % 11)
if checksum_string == "10":
checksum_string = "X"
print(accept_msg, nine_digits+checksum_string)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment