[Tutor] Input to correct data type

Dennis Lee Bieber wlfraed at ix.netcom.com
Sat Oct 9 20:39:11 EDT 2021


On Sat, 9 Oct 2021 23:58:34 +0200, Julius Hamilton
<juliushamilton100 at gmail.com> declaimed the following:

>Hey,
>
>Is there any built-in function which guesses the data type of input or a
>variable? For example, it would take integer input as an integer, and
>anything non-numerical as a string, perhaps?
>
	That description is a bit vague... after all...

>>> def stupidExample(a, b):
... 	return a + b
... 
>>> stupidExample(5.25, 123)
128.25
>>> stupidExample("hello ", "goodbye [pump out the septic tank]")
'hello goodbye [pump out the septic tank]'
>>> 

	If you mean the use of input() to obtain interactive values, it is up
to you to determine what is expected at that point -- input() itself
returns a string.

>>> "123.5".isdecimal()
False
>>> "123".isdecimal()
True
>>> 

	For floats you'll have to use a try/except block

>>> x = "123.75"
>>> try:
... 	xval = int(x)
... except ValueError:
... 	try:
... 		xval = float(x)
... 	except ValueError:
... 		xval = x
... 		
>>> xval
123.75
>>> x = 123
>>> try:
... 	xval = int(x)
... except ValueError:
... 	try:
... 		xval = float(x)
... 	except ValueError:
... 		xval = x
... 
>>> xval
123
>>> x = "123"
>>> try:
... 	xval = int(x)
... except ValueError:
... 	try:
... 		xval = float(x)
... 	except ValueError:
... 		xval = x
... 
>>> xval
123
>>> x = "something wicked this way comes"
>>> try:
... 	xval = int(x)
... except ValueError:
... 	try:
... 		xval = float(x)
... 	except ValueError:
... 		xval = x
... 
>>> xval
'something wicked this way comes'
>>> 


-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/



More information about the Tutor mailing list