Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


Mikkel Bielefeldt
Mikkel Bielefeldt
3,227 Points

How to check for number in name?

Let's say for example that I'm making a program that's only checking your name. How do you make it so it checks for numbers? Cause in my opinion I think it should be like this

if name == float or int:
    print("Unvalid character.")

But that doesn't seem to be right.

2 Answers

Steven Parker
Steven Parker
221,295 Points

First, to check the type of a variable, you would use the type() function along with the "is" operator. So instead of "name == float" you might have "type(name) is float".

And then, logic operators like "or" only combine complete expressions. So for example if you wanted to test if "n" was either 3 or 5 you would not write "n == 3 or 5" (that would always be true, no mater what "n" was), but you could write "n == 3 or n == 5".

And finally, where did "name" come from? If it was assigned from an "input" for example, it would always be a string, even if the user typed only digits. In that case, you'd probably want to check the individual characters for digits as Kris suggested.

A function for checking if a string contains a number from stackoverflow

def hasNumbers(inputString):
    return any(char.isdigit() for char in inputString)