简体   繁体   中英

Allow python program to accept input with decimal input

I'm actually a beginner in Python and this program that I am working on does not accept decimal input. Every time I change int to input or float it does not run. Also if possible, help me to make my code cleaner.

def convert_number_system(input_number, input_base, output_base):
    '''
    returns: int, converted number
    '''
    remainder_list = []
    
    sum_base_10 = 0

    if output_base == 2:
        binary_repr = bin(input_number)
        return (binary_repr[2:])
  
    elif input_base != 10:

        reversed_input_number = input_number[::-1]

        hex_helper_dict = {'a' : 10 , 'b' : 11 , 'c' : 12 , 'd' : 13 , 'e' : 14 , 'f' : 15}

        for index, number in enumerate(reversed_input_number):
            for key,value in hex_helper_dict.items():
                if str(number).lower() == key:
                    number = value
            sum_base_10 += (int(number)*(int(input_base)**index))

    elif input_base == 10:
        sum_base_10 = int(input_number)

    while sum_base_10 > 0:

        divided = sum_base_10// int(output_base)

        remainder_list.append(str(sum_base_10 % int(output_base)))

        sum_base_10 = divided

    return_number = ''

    if output_base == 16:
        hex_dict = {10 : 'a' , 11 : 'b' , 12 : 'c' , 13 : 'd' , 14 : 'e' , 15 : 'f'}

        for index, each in enumerate(remainder_list):
            for key, value in hex_dict.items():
                if each == str(key):
                    remainder_list[index] = value
    else:
        for each in remainder_list[::-1]:
            return_number += each

        return (return_number)

Edit: These instructions was added as an alternative. How can I implement this to the code?

  1. store input in a character array. note: the characters before the decimal point is the integer part and after the decimal point is the fractional part
  2. you can now multiply each element of the array with the corresponding powers of R,
  3. compute the sum of the products --the sum is the converted value

To change an input string into a decimal, you could do float(input()) and to check if the input is actually a decimal, you could do

if not (type(input_number) is float):
  break;

If this is in a while loop that repeats until the user enters a valid float, otherwise the program would just terminate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM