在我的代码中出现“'NoneType' Object 没有属性 'isdigit'”错误

Getting " 'NoneType' Object has no attribute 'isdigit' " error on my code

使用我要完成的代码是,我要求用户输入 1 到 12 之间的数字,然后显示该数字的次数 table。 while 循环检查它是否不是数字,或者它是否小于 1 或大于 12,然后它将循环直到输入正确。但是我得到了错误(写在标题上) 有什么解决办法吗?

user_input = print('Input number between 1-12: ')


#While loop to keep checking the following conditions
while (not user_input.isdigit()) or (int(user_input < 1) or int(user_input > 12)):
  print("Please input a number between 1-12")
  user_input = print("Input selection >>  ")

#Now convert user_input into an int
user_input = int(user_input)
print('------------------------------------------')
print()
print(f'This is the {user_input} times table')
print()
for i in range(1,13):
  print(f'{i} x {user_input} = {i*user_input}')
user_input = print('Input number between 1-12:')

上面的行只向控制台打印出Input number between 1-12: ,它不要求用户输入任何内容。由于 print() 函数显示其中的字符串和 returns None,您会得到您遇到的错误。

如果您想获取用户输入,请使用 input() 函数,例如,

user_input = input("Input number between 1-12: ")

上面一行会提示用户输入一些东西,同时也会显示文本

user_input = input('Input number between 1-12: ')


#While loop to keep checking the following conditions
while (not user_input.isdigit()) or (int(user_input)< 1 or int(user_input) > 12):

问题列表:

  • 您打印而不是 input 来接收用户的输入
  • 您试图在 strint 的实例上使用 <,您应该在 int 转换之外检查它,以确保您尝试使用< 这两个操作数都是 int