# Solved: base conversion python

The main problem with base conversion in Python is that it can be very slow.

```
def convert_to_base(num, base):

if base < 2 or (base > 10 and base != 16):

print("Invalid Base")

return -1
else:

converted_string, mod = "", num % base

while num != 0:

mod = num % base

num = int(num / base)

converted_string = chr(48 + mod + 7*(mod > 10)) + converted_string

return converted_string```

This is a function definition for a function that converts a number to a given base. If the base is less than 2 or greater than 10 and not equal to 16, it prints an error message. Otherwise, it calculates the modulus of the number and the base, and stores that in the variable “mod”. It then enters a while loop where it continues to calculate the modulus of the number and the base until the number is equal to 0. It stores each result in the variable “converted_string” as it goes. Finally, it returns the string “converted_string”.

## Data Type Conversion

There are a few ways to convert data types in Python. The simplest way is to use the type() function. For example, to convert a number to a string, you could use the following code:

str = type(number)

Another way to do this is using the str() function. For example, to convert a string to a number, you could use the following code:

number = str(string)

Related posts: