1

I wrote the code below:

try:
    nums=input("Write a name:")
    print (nums)
except ValueError:
    print ("You didn't type a name")

The problem is that even the user enter a number the program prints it `

3 Answers 3

1

You can use the function yourstring.isalpha() it will return true if all characters in the string are from the alphabet. So for your example:

nums = input("write a name:")
if(not nums.isalpha()):
    print("you did not write a name!")
    return
print(nums)
Sign up to request clarification or add additional context in comments.

Comments

0

You can use the builtin Python function type() to determine the type of a variable.

1 Comment

The input type will be always an str because, input() will return always a string.
0

You can use regex like this example:

import re

while True:
    try:
        name = input('Enter your name: ')
        validate = re.findall(r'^[a-zA-Z]+$', name)
        if not validate:
            raise ValueError
        else:
            print('You have entered:', validate[0])
            break
    except ValueError:
        print('Enter a valid name!')

2 Comments

Isn't this a bit over complicated, unless one wants to ensure only very specific characters have been entered?
@zezollo the characters must be in the range of a -> z and A -> Z So, for example foo123 will throw ValueError exception.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.