Write a function (decTohex) that converts a decimal number into a hexadecimal number as a string.

 Python - Question Solving : 

 


Question  = Write a function (decTohex) that converts a decimal number into a hexadecimal
number as a string.
Write a test program that asks the user to enter an integer value and displays the
corresponding hexadecimal value. Check whether the user enters only positive
or negative integers, and warn the user to enter an integer value if he/she makes
a mistake.

# SAMET SARIAL 64170037 COE QUESTION 1 - HOMEWORK 3 

def decTohex(dec):
    digits = "0123456789ABCDEF"
    hexa = []
    x = (dec % 16) #4
    rest = dec // 16 #floor division 15/2 = 7 
    if (rest == 0):
        hexa.append(digits[x])
        listToStr = ''.join(map(str, hexa)) 
        return listToStr
    else:
        hexa.append(decTohex(rest))
        hexa.append(digits[x])
        listToStr = ''.join(map(str, hexa)) 
        return listToStr

while True: #test program that asks the user to enter an integer value
    try: # Check whether the user enters only positive
         #or negative integers, and warn the user to enter an integer value if he/she makes
         #a mistake.
        number = int(input("Please enter your number: "))
    except ValueError:
        print("Sorry, I didn't understand that. Please enter integer")
        continue
    else:
        if number > 0:
            print("Hexadecimal values is :",decTohex(number))
        elif number < 0:
            a = hex((number + (1 << 64)) % (1 << 64))
            print("Hexadecimal values is :",a)

Yorum Gönderme

0 Yorumlar