我不知道这段代码有什么问题。我希望这个程序打印字符或显示一条消息,例如“你没有只键入1个字符”。你能帮帮我吗?
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")
答案 0 :(得分:1)
for
中CheckIfLitIsNumber
循环的第一次迭代,如果z
不等于lit
;您的代码正在返回False
。换句话说,在您当前的代码中,for
没有任何意义,因为它会根据True
的比较返回False
/ numbers[0]==lit
。
相反,您应该在False
循环完成时返回for
值。因此,您的代码应该是:
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中的input()
始终返回str
。要将其更改为int
类型,您必须进行类型转换。因此,在将值传递给CheckIfLitIsNumber
之前,只有这样您才能执行整数比较。请参阅:How can I read inputs as integers in Python?
但是,您不需要这两个功能。您可以通过以下方式获得相同的结果:
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():
答案 1 :(得分:0)
执行
时出错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 array
,将lit
与string
进行比较,>>> "1" == 1
False
将始终返回false。例如:
catch
相反,你想做的是TypeError
和def CheckIfLitIsNumber(lit):
try:
return isinstance(int(lit), int)
Except TypeError:
return false
,如下所示:
请勿使用此代码,请在下方查看要使用的内容。
lit
在此示例中,如果int(lit)
实际上是一个字符串,则运行TypeError
会生成一个caught
,随后会return false
而lit.isdigit()
运行。
虽然这样可行,但使用def CheckIfLitIsNumber(lit):
return not lit.isdigit()
会更简单,就像这样:
@SubjectRequired