How to check if a variable is a number in Python

You can check if a variable is an integer using the type() function, passing the variable as an argument, and then comparing the result to the int class:
age = 1
type(age) == int #True
Or using isinstance(), passing 2 arguments: the variable, …


This content originally appeared on flaviocopes.com and was authored by flaviocopes.com

You can check if a variable is an integer using the type() function, passing the variable as an argument, and then comparing the result to the int class:

age = 1
type(age) == int #True

Or using isinstance(), passing 2 arguments: the variable, and the int class:

age = 1
isinstance(age, int) #True

You can check if the number is a floating point number by comparing it to float instead of int:

fraction = 0.1
type(fraction) == float #True


This content originally appeared on flaviocopes.com and was authored by flaviocopes.com


Print Share Comment Cite Upload Translate Updates
APA

flaviocopes.com | Sciencx (2021-03-02T05:00:00+00:00) How to check if a variable is a number in Python. Retrieved from https://www.scien.cx/2021/03/02/how-to-check-if-a-variable-is-a-number-in-python/

MLA
" » How to check if a variable is a number in Python." flaviocopes.com | Sciencx - Tuesday March 2, 2021, https://www.scien.cx/2021/03/02/how-to-check-if-a-variable-is-a-number-in-python/
HARVARD
flaviocopes.com | Sciencx Tuesday March 2, 2021 » How to check if a variable is a number in Python., viewed ,<https://www.scien.cx/2021/03/02/how-to-check-if-a-variable-is-a-number-in-python/>
VANCOUVER
flaviocopes.com | Sciencx - » How to check if a variable is a number in Python. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/03/02/how-to-check-if-a-variable-is-a-number-in-python/
CHICAGO
" » How to check if a variable is a number in Python." flaviocopes.com | Sciencx - Accessed . https://www.scien.cx/2021/03/02/how-to-check-if-a-variable-is-a-number-in-python/
IEEE
" » How to check if a variable is a number in Python." flaviocopes.com | Sciencx [Online]. Available: https://www.scien.cx/2021/03/02/how-to-check-if-a-variable-is-a-number-in-python/. [Accessed: ]
rf:citation
» How to check if a variable is a number in Python | flaviocopes.com | Sciencx | https://www.scien.cx/2021/03/02/how-to-check-if-a-variable-is-a-number-in-python/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.