1

I want a way for the user not to make an integer input by using this function:

x = input("Whats your name?") 
while x == int:
y = input("why is there a number in your name? Please re enter your name")

But this does not work. Any idea why?

mjick
  • 11
  • 3

5 Answers5

2

Improving in @persian_dev's answer -

def check_name(string):
    for char in string :
        try:
            int(char)
            return False
        except:
            continue
    return True

This will traverse the string, try to convert each character to int and return False on first success in doing so.

Harshil Sharma
  • 2,016
  • 1
  • 29
  • 54
1

The input function will convert anything user enters to a string.

So you want to instead look whether there is any number contained in x, rather than the type.

See here: check if a string contains a number

Community
  • 1
  • 1
Flying_Banana
  • 2,864
  • 2
  • 22
  • 38
1

here is a check function :

def isnumeric(string):
    try:
        int(string)
        return True
    except:
    return False

def check_name(string):
    for char in string:
        if isnumeric(char):
            return False
    return True
Harshil Sharma
  • 2,016
  • 1
  • 29
  • 54
persian_dev
  • 73
  • 1
  • 10
1

If you just want to make sure the user input contains strings only, you can use isalpha() to check the input:

x = raw_input("Whats your name?") 
while not x.isalpha():
    x = raw_input("why is there a number in your name? Please re enter your name")

I use Python 2 so I used raw_input instead of input. If you use Python 3 you can adjust accordingly.

Joe T. Boka
  • 6,554
  • 6
  • 29
  • 48
-1

int is a type. You're not asking "Does x contain a number?" or even "Is x a number?", you're asking "Is x number?" (integer, more precisely). Makes no sense. Assuming entering names work, you're using Python 3, in which case the result of input is always a string. Even if it's a string of only digits. So isinstance(x, int) won't work, either. You could try casting with int(...), but that won't help if the name contains a number only somewhere among letters.

Here's a good way to test whether there's any digit in a string:

any(map(str.isdigit, x))

In your code, also with the y corrected to x:

x = input("Whats your name? ")
while any(map(str.isdigit, x)):
    x = input("why is there a number in your name? Please re enter your name ")
Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107