As an exercise I am converting numbers to hexadecimal values. Is there a more professional way of doing it?
def hexayacheviren(reqem):
if reqem==10:
return "A"
elif reqem==11:
return "B"
elif reqem==12:
return "C"
elif reqem==13:
return "D"
elif reqem==14:
return "E"
elif reqem==15:
return "F"
else:
return reqem
def hexadecimal(n):
cavab=[ ]
i=0
while (n>0):
netice=n%16
cavab.append(hexayacheviren(netice))
i=i+1
n=n//16
string=''.join(str(e) for e in cavab)
cvbstrng = string[::-1]
print (cvbstrng)
hexadecimal(3200)
Here's my solution using some of Python's more interesting features, like yield, generator comprehension, ternary operator, string indexing, and various bit twiddling miscellanea:
use the builtin function:
hex
. Python comes batteries includedYou could simply your first function using a
dict
and possibly throw in a bit of error handling, eg:If the value is one of 10, 11, 12... then it returns the corresponding letter, otherwise, it returns the original number as a string. This will lead to you being able to simplify your second functions as its inputs always take an int, and its outputs will always be a string.