Python 输入数字时返回True或False时出错
我不知道这段代码出了什么问题。我希望这个程序打印字符或显示一条消息,例如,您没有只键入一个字符。你能帮我吗Python 输入数字时返回True或False时出错,python,python-3.x,Python,Python 3.x,我不知道这段代码出了什么问题。我希望这个程序打印字符或显示一条消息,例如,您没有只键入一个字符。你能帮我吗 def PrintVariable(lit): variable = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "w", "x", "y", "z"] for i in variable:
def PrintVariable(lit):
variable = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
"n", "o", "p", "q", "r", "s", "t", "u", "w", "x", "y", "z"]
for i in variable:
if(i == lit):
print("Your character is ", i)
def CheckIfLitIsNumber(lit):
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for z in numbers:
if (z == lit):
return True
else:
return False
lit = (input("Give a character "))
if len(lit) == 1 and (CheckIfLitIsNumber(lit) is False):
PrintVariable(lit)
else:
print("You didn't give a character or you've entered a word")
如果z不等于lit,则在CheckIfLitIsNumber中for循环的第一次迭代中;您的代码返回False。换句话说,在您当前的代码中,for没有任何意义,因为它根据数字[0]==lit的比较返回真/假 相反,您应该在for循环完成时返回False值。因此,您的代码应该如下所示:
def CheckIfLitIsNumber(lit):
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for z in numbers:
if (z == lit):
return True
else:
return False
# ^ ^ please note the indentation
还要注意的是,Python中的输入总是返回str。要将其更改为int类型,必须对其进行类型转换。因此,在将值传递给CheckIfLitIsNumber之前,只有这样才能执行整数比较。请参阅:
但是,您不需要这两个函数。您只需执行以下操作即可获得相同的结果:
import string
variable = string.lowercase # string of all the lowercase characters
lit = input("Give a character ")
# v check presence of `lit` in `variable` string
if len(lit) == 1 and lit in variable:
print("Your character is ", lit)
else:
print("You didn't give a character or you've entered a word")
最好将您的if条件更改为:
# v checks whether number is alphabet or not
if len(lit) == 1 and lit.isalpha():
您在执行此操作时出错
def CheckIfLitIsNumber(lit):
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for z in numbers:
if (z == lit):
return True
else:
return False
由于numbers是一个int数组,因此将其与lit(字符串)进行比较时,将始终返回false。例如:
>>> "1" == 1
False
相反,您要做的是捕获一个TypeError,如下所示:
不要使用此代码,请查看下面要使用的代码
在本例中,如果lit实际上是一个字符串,则运行intlit将给出一个TypeError,随后将捕获该错误并运行返回false。
虽然这会起作用,但使用lit.isdigit会简单得多,如下所示:
def CheckIfLitIsNumber(lit):
return not lit.isdigit()
实际输出是什么?两个FOR都不是必需的-如果在变量中点亮:就足够了。此外,lit.isalpha和lit.isdigit是标准的库函数,因此您不需要上述内容。您的问题措辞错误,代码的错误似乎是当它是数字而不是单词时。你确定当你输入多个字符时,它没有给出正确的消息吗?另外,如果他想使用CheckifLitIsNumber并与整数列表进行比较,他需要checkiflitisnumberlight。input在Python3.not lit.isdigit中返回一个字符串,因为当它是数字时,您需要一个try/except语句。Yes。我错过了@安德烈请看临时沃尔夫和史蒂文提到的评论。有关详情,请参阅:
def CheckIfLitIsNumber(lit):
return not lit.isdigit()