Python Forum

Full Version: Changing Data Types
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am writing a program to change the given data type.
Here is my code:
a = input("Type the data which you would like to convert: ")
dtype = input("Type the data type which you would like to convert it to: ").lower()
if dtype == "integer" or dtype == "int":
	a = int(a)
	print(f"The data converted to {dtype}: {a}")

elif dtype == "boolean" or dtype == "bool":
	a = bool(a)
	print(f"The data converted to {dtype}: {a}")

elif dtype == "floating" or dtype == "float":
	a = float(a)
	print(f"The data converted to {dtype}: {a}")

elif dtype == "string" or dtype == "str":
	a = str(a)
	print(f"The data converted to {dtype}: {a}")

elif dtype == "complex":
	a = complex(a)
	print(f"The data converted to {dtype}: {a}")

else:
	print("Invalid Input")

print(type(a))
This is the error I get when I try to convert float to integer:
Error:
File "grp_tasks.py", line 25, in <module> a = int(a) ValueError: invalid literal for int() with base 10: '12.5'
Also when I input "0" and try to convert it to boolean. It shows up as True
Output:
Type the data which you would like to convert: 0 Type the data type which you would like to convert it to: boolean The data converted to boolean: True
What is wrong with my code?

PS. Changing line 4 to:
a = int(round(a))
solves the error
input() returns a string. So dtype is always a string. Your error results from trying to convert a string with a decimal to int which it cannot do (at least as a string). You would either need to convert it to a float first, or parse out the decimal and after.
>>> int('12.5')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '12.5'
>>> int(12.5)
12
Any object that contains data is considered True, and if it is empty, is False. And string is just another object.
>>> a = ''
>>> bool(a)
False
>>> b = '0'
>>> bool(b)
True
>>> 
You would first have to convert the string '0' to a int 0 to be considered False.
>>> bool(int(b))
False
(Jun-27-2019, 12:43 PM)metulburr Wrote: [ -> ]input() returns a string. So dtype is always a string. Your error results from trying to convert a string with a decimal to int which it cannot do (at least as a string). You would either need to convert it to a float first, or parse out the decimal and after.
>>> int('12.5')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '12.5'
>>> int(12.5)
12
Any object that contains data is considered True, and if it is empty, is False. And string is just another object.
>>> a = ''
>>> bool(a)
False
>>> b = '0'
>>> bool(b)
True
>>> 
You would first have to convert the string '0' to a int 0 to be considered False.
>>> bool(int(b))
False
Thanks a lot for the explanation!