1

This is a homework assignment so if you don't want to help, I understand that. However, I'm not looking for the algorithm as much as help with Python. I am good with C++, but a couple of my classes this semester are using Python so I'd like to practice it some.

This is the work that I have so far... It works, but I would like to add some checks into the program such as checking to make sure the initial input is in hexadecimal format.

Would it be efficient to just convert the string to a list and check from there?

Thank you for your help,

import binascii #used to convert from hexadecimal to binary
import base64   #used to convert from binary to base64


"""
get hexadecimal value
convert to binary
convert to base64
"""

#conversions
hexa = input("Enter a hexadecimal value: ")
bina = binascii.unhexlify(hexa)
Base64 = base64.b64encode(bina)

#print
print(Base64)

#exit program
input("Exit...")
Phillip Sloan
  • 125
  • 1
  • 2
  • 9
  • What currently happens on invalid input? – Josh Lee Jan 20 '17 at 17:43
  • The program just ends. The command prompt shuts without continuing to run. – Phillip Sloan Jan 20 '17 at 19:11
  • You may wish to launch your program from the command line (`python myprogram.py`) instead of from the GUI, so you can read the program's output. https://stackoverflow.com/questions/12375173/how-to-stop-python-closing-immediately-when-executed-in-microsoft-windows – Josh Lee Jan 20 '17 at 19:26
  • Oh, I see... Thank you. This was very helpful. Before, I couldn't tell what was going wrong! – Phillip Sloan Jan 21 '17 at 15:45

1 Answers1

1

Two things:

  1. unhexlify will raise an exception if the input contains an error. You could catch this exception and e.g. continue a loop.

    >>> try:
    ...     binascii.unhexlify('tsst')
    ... except binascii.Error as e:
    ...     print(f'Invalid input ({e}). Please try again:', file=sys.stderr)
    ...
    Invalid input (Non-hexadecimal digit found). Please try again:
    
  2. You can iterate over the characters of a string, so converting it to a list would be unnecessary.

    >>> import string
    >>> all(c in string.hexdigits for c in 'cafebabe')
    True
    
Josh Lee
  • 171,072
  • 38
  • 269
  • 275