Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

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
229,732 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)