RE: A Simple Hex Address Calculator in Python - [Coding]

You are viewing a single comment's thread from:

A Simple Hex Address Calculator in Python - [Coding]

in science •  7 years ago 

Interesting.

You do seem to be going about it slightly inefficiently, though. There are some built-in methods in Python to help with these sorts of things.

Firstly there is the eval() function, if you pass it a string it attempts to run it as Python code, then there's hex() which takes an integer and converts it to hex.

So if you modify the code you can turn your try block into just:

a = sys.argv[1]
b = sys.argv[2]
c = sys.argv[3]
if b == "add":
    b = "+"
elif b ==  "sub":
    b = "-"
elif b == "mul":
    b = "*"
elif b == "div":
    b = "/"

print(hex(eval(a + b + c)))

Which has a lot less munging of strings to get them working.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

I very rarely write any Python programs that need command line arguments, so haven't used argparse, but it's one of those modules that's on my radar if I ever need to write one.

Thanks! Appreciate the addendum.