Python : 别名错误

Python : Another Name Error

我有两组代码,它们本质上具有相同的目标,但都无法正常工作并出现同名错误。我正在努力做到这一点,所以他们只接受字母作为答案,而不是数字。当输入数字作为输入时,程序可以正常工作,但字母则不能。另请注意,我还是 python 的新手,如果可能的话,我正在寻找基本命令。我知道他们还有很多其他问题,但我发现 none 回答了我的问题。出现的错误专门指出了 Name = input("What's your name?\n") 行。提前致谢!

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)

错误

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

此处的目标是检查字符串是否包含数字。

如果是,再问一次。
否则,退出

# 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))
if "0" or "1" or "2" or "3" or "4" or "5" or "6" or "7" or "8" or "9" in str(Name):

这将始终告诉您您的名字中有一个数字,因为 "0" 是一个非零长度的字符串,因此是真实的。 Python 看到 if "0" or 并停在那里,因为它已经知道整个事情一定是真的。

您可能想要的更像是:

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

或者,可以说更好:

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

另一个尝试将名称转换为整数的转换只有在名称为 所有 位数字时才会成功转换,如果它包含数字则不会。那不是你想要的,所以你不应该那样做。

我只想指出几点:

首先,"1" or "2" or "3" or "4" 将评估 "1" or "2",即 true 并停止。您必须在名称中写出“1”或在名称中写出“2”等。这是非常低效的,您应该查看 has_int() 的发布函数,因为这将是实现它的更好方法。

此外,名称可能包含数字,但仍可能不会被解析为 int() 并引发错误,因此第二次检查无法有效确定字符串是否包含任何数字,仅当字符串仅数字

最后,这不是必需的,但用小写字母命名变量是个好习惯。

此外,如果您 python 版本不是 3,则您的名称错误可能是因为输入。如果是这种情况,请尝试使用 raw_input()。

很高兴您决定伸出援手。

我认为正则表达式(python 模块 re)(更多信息在这里:https://docs.python.org/2/library/re.html)正合您的口味。正则表达式将允许您确定您的字符串是否匹配 "mold" 或您可以自己定义的模式

正则表达式是一个非常广泛和深入的主题,需要一些时间来适应,但我认为它们绝对值得您花时间。学习这个介绍性的、友好的教程:http://regexone.com/

那么,在python中,你可以试试这个:

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()

这里重要的是[0-9]+的部分,也就是"one or more numbers, any of them from 0 to 9".

好吧,我知道我搞砸了我以前的代码,但为了弥补它,我提出了一个可行的替代方案,OP 可以像下面这样重构他们的程序:

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"

祝你好运!

你是 运行 Python2 中的这个。在 Python2 中,input 评估用户的输入 AS CODE。这意味着当您这样做时:

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

它试图评估一些名为 Will 的变量。没有这样的变量,所以它抛出一个NameError。您可以通过输入 "Will"(注意引号)来对此进行测试。现在它将它评估为一个字符串并且应该可以正常工作。但当然你也可以写 import os; os.listdir() 并获得当前目录的列表,后面可能是 TypeErrorinput 在 Python2 中不安全。

相反(在 Python2 中),使用 raw_input