How do you convert to base 10 in python?

import math 




def baseencode(number, base):
    ##Converting a number of any base to base10

    if number == 0:
        return '0'

    for i in range(0,len(number)):
        if number[i]!= [A-Z]:
            num = num + number[i]*pow(i,base)
        else :
            num = num + (9 + ord(number[i])) *pow(i,base)
    return num

a = baseencode('20',5)
print a 

Errors I get are

Traceback (most recent call last):
  File "doubtrob.py", line 19, in 
    a = baseencode('20',5)
  File "doubtrob.py", line 13, in baseencode
    if number[i]!= [A-Z]:
NameError: global name 'A' is not defined

asked Feb 9, 2011 at 15:09

1

Isn't int(x, base) what you need?

int('20',5) # returns the integer 10

answered Feb 9, 2011 at 15:15

eumiroeumiro

198k33 gold badges294 silver badges259 bronze badges

2

You're confusing Python with... Perl or something...

if not ('A' <= number[i] <= 'Z'):

answered Feb 9, 2011 at 15:12

2

A more comprehensive solution to this problem may look like this:

import string

# Possible digits from the lowest to the highest
DIGITS = '%s%s' % (string.digits, string.lowercase)

def baseencode(num, base):
    result = 0
    positive = True
    # If a number is negative let's remove the minus sign
    if num[0] == '-':
        positive = False
        num = num[1:]

    for i, n in enumerate(num[::-1]):
        # Since 0xff == 0xFF
        n = n.lower()
        result += DIGITS.index(n) * base ** i

    if not positive:
        result = -1 * result

    return result

Basically whilst converting a number to base 10 it's easiest to start from the last digit, multiply it by the base raised to the current position (DIGITS.index(n) * base ** i).

BTW, in my understanding it's a Python exercise, but if it's not there's a builtin function for that - int:

int(x[, base]) -> integer

answered Feb 9, 2011 at 16:59

Other bugs in the code:
1. You didn't initialize variable num that you used to store results.
2. you need to convert number[i] from char to int before you can apply multiplication/addition.

    num = num + int(number[i]) * pow(i,base)

answered Feb 9, 2011 at 15:21

kefeizhoukefeizhou

6,06410 gold badges40 silver badges55 bronze badges

There are many errors in your code. To begin with,

number[i] != [A-Z]

is not Python syntax at all. What you probably want is

number[i].isdigit()

Furthermore, the

if number == 0:
    return '0'

part should probably be

if number == '0':
    return 0

but actually, there is no need to special-case this at all. Another problem is that you interpreting the first character as "ones", i.e. lowest significant. There are a few more problems, but maybe this will get you going...

That said, you could simply use

int('20',5)

answered Feb 9, 2011 at 15:17

Sven MarnachSven Marnach

544k114 gold badges914 silver badges816 bronze badges

2

import math

def base_encode(number, base):
    """Convert number in given base to equivalent in base10

    @param number: string, value to convert (case-insensitive)
    @param base:   integer, numeric base of strNumber

    @retval: integer, x base(10) == number base(base)
    """
    # sanitize inputs
    number = str(number).lower()
    base = int(base)

    # legal characters
    known_digits = '0123456789abcdefghijklmnopqrstuvwxyz'
    value  = { ch:val for val,ch in enumerate(known_digits) if val  10
base_encode('-zzz', 36)  -> -46655

answered Feb 9, 2011 at 21:18

Hugh BothwellHugh Bothwell

53.7k7 gold badges81 silver badges98 bronze badges

You probably want

if number[i] not in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":

or

import string
# ...
if number[i] not in string.ascii_uppercase:

answered Feb 9, 2011 at 15:13

Tim PietzckerTim Pietzcker

318k56 gold badges494 silver badges550 bronze badges

How do you do base 10 in python?

Description. The log10() method returns base-10 logarithm of x for x > 0..
Syntax. Following is the syntax for log10() method − import math math.log10( x ) ... .
Parameters. x − This is a numeric expression..
Return Value. This method returns the base-10 logarithm of x for x > 0..
Example. ... .
Output..

How do you convert binary to base 10 in python?

In Python, you can simply use the bin() function to convert from a decimal value to its corresponding binary value. And similarly, the int() function to convert a binary to its decimal value. The int() function takes as second argument the base of the number to be converted, which is 2 in case of binary numbers.

How do you convert base 8 to base 10?

If you have a sequence of base 8 digits you want to convert to a base 10 number, process them from left to right, keeping a total you initialize at zero. For each digit x, set the total to 8*total+x. After processing the last digit, the total will be the base ten value of the base 8 sequence.