-4

I have two sets of code that essentially have the same goal but neither work and come up with the same name error. I'm trying to make it so they only letters are accept as answers, not numbers. When a number is entered as the input the program works fine but letters do not. Pleases also note that I am still new to python and am looking for basic commands if possible. I know their are many other questions like this one but none that I found answered my question. The error that comes up specifically points out the Name = input("What's your name?\n") line. Thank you in advance!

1

LetterCheck = True
while LetterCheck == True:
    Name = input("What's your name?\n")                                                     
    if "0" or "1" or "2" or "3" or "4" or "5" or "6" or "7" or "8" or "9" in str(Name):
        print('Your name must NOT include numbers.')
    else:
       LetterCheck = False
print(Name) 

2

LetterCheck = True
while LetterCheck == True:
    Name = input("What's your name?\n")
    global Name
    try:
        Name = int(Name)
    except ValueError:
        Name = str(Name)
        LetterCheck = False
    else:
        print("Your name must NOT include numbers")
print(Name)

The Error

What's your name?
45
Your name must NOT include numbers
What's your name?
Will

Traceback (most recent call last):
  File "C:/Users/Will/Documents/Python/Task 1 Debugging.py", line 3, in <module>
    Name = input("What's your name?\n")
  File "<string>", line 1, in <module>
NameError: name 'Will' is not defined
Easty679
  • 3
  • 2
  • Is this Python 2 or Python 3? – jwodder Dec 02 '15 at 20:59
  • 1
    please include the full traceback –  Dec 02 '15 at 21:01
  • @jwodder the use of the print function suggests Python 3, so the use of input() should be correct. Unless, indeed, it is Python 3 code run with Python 2. –  Dec 02 '15 at 21:02
  • 1
    This may be useful to you: [Asking the user for input until they give a valid response](http://stackoverflow.com/q/23294658/953482) – Kevin Dec 02 '15 at 21:03
  • Ahhhh, i think i realise why i was having so much trouble. I have been doing this on two devices, one must be running 3 and my main Python 2. I'm guessing i tried all the changes that would/would't work on Python 2/3 whilst switching machines. – Easty679 Dec 02 '15 at 21:26

5 Answers5

2
if "0" or "1" or "2" or "3" or "4" or "5" or "6" or "7" or "8" or "9" in str(Name):

This will always tell you there is a number in your name, because "0" is a non-zero length string and therefore truthy. Python sees if "0" or and stops there because it already knows the whole thing must be true.

What you probably want is something more like:

if any(digit in Name for digit in "0123456789"):

Or, arguably better:

if any(char.isdigit() for char in Name):

The other one where you're trying to convert the name to an integer will only succeed in the conversion if the name is all digits, not if it contains a digit. That's not what you want so you shouldn't do it that way.

kindall
  • 178,883
  • 35
  • 278
  • 309
  • 1
    After updating to Python 3 on this device I found that this work and will use this version. Thanks! – Easty679 Dec 02 '15 at 21:44
1

You're running this in Python2. In Python2, input evaluates the user's input AS CODE. This means when you do:

>>> input("Name: ")
Name: Will

It tries to evaluate to some variable named Will. There is no such variable, so it throws a NameError. You can test this by entering "Will" (note the quotes). Now it evaluates it as a string and should work properly. But of course you could also write import os; os.listdir() and get a list of the current directory followed by what will likely be a TypeError. input is not safe in Python2.

Instead (in Python2), use raw_input.

Adam Smith
  • 52,157
  • 12
  • 73
  • 112
0

I would just like to point out a few things:

First, "1" or "2" or "3" or "4" will evaluate "1" or "2" which is true and stop. You have to write out "1" in name or "2" in name, etc. That's highly inefficient and you should look at the posted function for has_int() as that would be a better way to implement it.

Also a name may have digits and still won't probably be parsed as an int() and raise an error so the second check is not effective at determining if a string has any numbers, only if the string is only numbers

Finally, it's not necessary but it is good practice to name your variables with lowercase letters.

Also, your name error could be because of input if you python version is not 3. Try using raw_input() if that is the case.

-1

The goal here is to check if a string contains numbers.

if it does, ask again.
else, quit

# return true if given string does not have any numbers in them.
def has_int(s):
    return any(char.isdigit() for char in s)

# ask what the name is
name = input('What is your name?')
# check if this user input has int
while has_int(name):
    # if it does, re-prompt
    print('Name cannot include numbers')
    name = input('What is your name?')
# finally, say the name
print('Your name is {}'.format(name))
taesu
  • 4,482
  • 4
  • 23
  • 41
-2

Very glad that you have decided to reach out.

I think regular expressions (python module re) (more info here: https://docs.python.org/2/library/re.html) are right up your alley. Regular expressions will allow you to determine if your string matches a "mold" or a pattern, which you can define by yourself

Regular expressions are a very broad and deep subject that take a bit of time to get used to, but I think they're absolutely worth your time. Take this introductory, friendly tutorial: http://regexone.com/

Then, in python, you can try this:

import re

input_str = raw_input(">?") #reads user input

if re.match('[0-9]+', input_str):     #if the input matches the pattern "one or more numbers in the string"
    print "Only letters a-z allowed!" #error out of the program
    sys.exit()

The thing of importance here is the part with [0-9]+, which means "one or more numbers, any of them from 0 to 9".

Alright, I know I messed up with my previous code but to make up for it I present a working alternative, OP can refactor their program a bit like the following:

import re

while True:
    input_str = raw_input("What's your name? ") #reads user input 
    if ( re.match('[0-9]+', input_str) ):     # while the input doesn't match the pattern "one or more numbers in the string"
        print "Your name must NOT include numbers." #error out of the program
    else:
        break

print "if you see this, the entered name fullfilled the logical condition"

Good luck!

Alfredo Gallegos
  • 613
  • 6
  • 22