Question

In Python, revise this code. define convert(s): """ Takes a hex string as input. Returns decimal...

In Python, revise this code.

define convert(s):
""" Takes a hex string as input.
Returns decimal equivalent.
"""

total = 0

for c in s
total = total * 16
ascii = ord(c
if ord('0) <= ascii <= ord('9'):
#It's a decimal number, and return it as decimal:
total = total+ascii - ord('0')
elif ord('A") <= ascii <= ord('F'):
#It's a hex number between 10 and 15, convert and return:
total = total + ascii - ord('A') + 10
else ord('a') =< ascii <= ord('f'):
#Check if they used lower case:
#It's a hex number between 10 and 15, convert and return:
total = total + ascii - ord('a') +++ 10
else:
#Not a valid number!
return(-1)
return(total)

def main()
hexString = input("Enter a number in hex: ')
prnt("The number in decimal is", convert(hexString))


#Allow script to be run directly:
if __name__ == "__main__":
main()

0 0
Add a comment Improve this question Transcribed image text
Answer #1

# hex char to int value
def hexCharValue(c):
        chars = '0123456789ABCDEF'
        return chars.find(c)

def convert(s):
        """ Takes a hex string as input.
        Returns decimal equivalent.
        """
        s = s.upper()
        if s == '':
                return 0
        return 16 * convert(s[:-1]) + hexCharValue(s[-1])

def main():
        hexString = input("Enter a number in hex: ")
        print("The number in decimal is", convert(hexString))

main()


   Please upvote, as i have given the exact answer as asked in question. Still in case of any concerns in code, let me know in comments. Thanks!

Add a comment
Know the answer?
Add Answer to:
In Python, revise this code. define convert(s): """ Takes a hex string as input. Returns decimal...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • [Using Python] I need my code given below to loop the user input, so that you...

    [Using Python] I need my code given below to loop the user input, so that you are asked to input without it stopping after 4 inputs. Code: #A program that converts a hexadecimal number to its decimal value #Define function for hexadecimal to decimal def hexToDec(hexi): result = 0 #For loop to test input for correct values for char in hexi: if 'A' <= char <= 'F' or 'a' <= char <= 'f': if 'a' <= char <= 'f': result...

  • [Using Python] Write a program to convert a hexadecimal number to its decimal value. (Reminder: hexadecimal...

    [Using Python] Write a program to convert a hexadecimal number to its decimal value. (Reminder: hexadecimal numbers are 0 through 9, A,B,C,D,E,F. hex(A) = 10, hex(F) = 15). example outputs: 1. `Enter a hex number: f` `The decimal value for hex number f is 15` 2. `Enter a hex number: g` `Incorrect hex number` 3. `Enter a hex number: 091c` `The decimal value for hex number 091c is 2332` 4. `Enter a hex number: 091g` `Incorrect hex number` Hints: you...

  • Write a python code that takes in an number 0-9 and prints out the word of...

    Write a python code that takes in an number 0-9 and prints out the word of the number. For example 1 would print out one. Below is the skeleton of the code that needs to be filled in. def num2string(num): """ Takes as input a number, num, and returns the corresponding name as a string. Examples: num2string(0) returns "zero", num2string(1)returns "one" Assumes that input is an integer ranging from 0 to 9 """ numString = "" ################################### ### FILL IN...

  • AND logic gate simulation in Python: Please fix the code below so that it efficiently performs...

    AND logic gate simulation in Python: Please fix the code below so that it efficiently performs the operation of the AND logic gate in Python. (Leave comments in the edited code about what you changed) #if both values are 1, return true, other wise return false print ("Logic Gate Simulation: AND gate") def AND(x, y):     if x == True and y == True:         return True        else:         return False    def main():     x = bool(input("Please...

  • Python help! Any help is appreciated, thank you! Fill in the missing function, monthString(), in the...

    Python help! Any help is appreciated, thank you! Fill in the missing function, monthString(), in the program. The function should take number between 1 and 12 as a parameter and returns the corresponding month as a string. For example, if the parameter is 1, your function should return "January". If the parameter is 2, your function should return out "February", etc. def monthString(monthNum): """ Takes as input a number, monthNum, and returns the corresponding month name as a string. Example:...

  • I am currently facing a problem with my python program which i have pasted below where i have to design and implement python classes and record zoo database and takes user input as query. the error i...

    I am currently facing a problem with my python program which i have pasted below where i have to design and implement python classes and record zoo database and takes user input as query. the error i am recieving says that in line 61 list index is out of range. kindly someone help me with it as soon as possible. Below is the program kindly check and correct it. Thanks! class Animal: def __init__(self, name, types, species, mass): self.name=name self.type=types...

  • convert this python code to c++ code def sort(a,b): if a > b: return b,a else:...

    convert this python code to c++ code def sort(a,b): if a > b: return b,a else: return a,b def main(): set1 = input('Enter the first pair of integers: ') set2 = input('Enter the second pair of integers: ') set3 = input('Enter the third pair of integers: ') set1 = set1.split(',') set1_0 = int(set1[0]) set1_1 = int(set1[1]) set2 = set2.split(',') set2_0 = int(set2[0]) set2_1 = int(set2[1]) set3 = set3.split(',') set3_0 = int(set3[0]) set3_1 = int(set3[1])    print(sort(set1_0,set1_1)) print(sort(set2_0,set2_1)) print(sort(set3_0,set3_1))

  • Need help with Python (BinarySearch), code will be below after my statements. Thank you. Have to...

    Need help with Python (BinarySearch), code will be below after my statements. Thank you. Have to "Add a counter to report how many searches have been done for each item searched for." Have to follow this: 1) you'll create a counter variable within the function definition, say after "the top = len(myList)-1" line and initialize it to zero. 2) Then within the while loop, say after the "middle = (bottom+top)//2" line, you'll start counting with "counter += 1" and 3)...

  • Can you please enter this python program code into an IPO Chart? import random def menu():...

    Can you please enter this python program code into an IPO Chart? import random def menu(): print("\n\n1. You guess the number\n2. You type a number and see if the computer can guess it\n3. Exit") while True: #using try-except for the choice will handle the non-numbers #if user enters letters, then except will show the message, Numbers only! try: c=int(input("Enter your choice: ")) if(c>=1 and c<=3): return c else: print("Enter number between 1 and 3 inclusive.") except: #print exception print("Numbers Only!")...

  • python programming: Can you please add comments to describe in detail what the following code does:...

    python programming: Can you please add comments to describe in detail what the following code does: import os,sys,time sl = [] try:    f = open("shopping2.txt","r")    for line in f:        sl.append(line.strip())    f.close() except:    pass def mainScreen():    os.system('cls') # for linux 'clear'    print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")    print(" SHOPPING LIST ")    print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")    print("\n\nYour list contains",len(sl),"items.\n")    print("Please choose from the following options:\n")    print("(a)dd to the list")    print("(d)elete from the list")    print("(v)iew the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT