【问题标题】:How can you restrict user to only input alphabets in Python?如何限制用户在 Python 中只输入字母?
【发布时间】:2021-06-03 05:12:04
【问题描述】:

我是一名尝试学习 Python 的初学者。第一个问题。

试图找到一种方法让用户只输入字母。 写了这个,但是不行! 它返回True,然后在继续else 子句之前跳过其余部分。 break 也不起作用。

有人能指出原因吗? 我认为这是非常初级的,但我被困住了,如果有人能把我拉出来,我会很感激。

while True:
    n = input("write something")
    if print(n.isalpha()) == True:
        print(n)
        break
    else:
        print("Has to be in alphabets only.")

【问题讨论】:

  • if n.isalpha() is True:(或只是if n.isalpha():)。你检查print 的返回值是None....

标签: python loops break restrict isalpha


【解决方案1】:

您的问题是print 函数。 print 不返回任何内容,因此您的 if 语句始终将 NoneTrue 进行比较。

while True:
    n = input("write something")
    if n.isalpha():
        print(n)
        break
    else:
        print("Has to be in alphabets only.")

【讨论】:

  • 谢谢!没想到这么短的时间就有这么大的帮助!谢谢。
【解决方案2】:

你的声明应该是if n.isalpha() == True:print 不会返回任何内容,因此值为None。然后,您将NoneTrue 进行比较

while True:
    n = input("write something")
    if n.isalpha() == True:
        print(n)
        break
    else:
        print("Has to be in alphabets only.")

【讨论】:

  • 哇!如此迅速和伟大!有用!非常感谢!
  • 最欢迎@Zane
【解决方案3】:

我已经修复了这个错误,下面是更新的代码:

while True:
    n = input("write something: ")
    if n.isalpha() == True:
        print(n)
        break
    else:
        print("Has to be in alphabets only.")

【讨论】:

  • 谢谢!我已经为此苦苦挣扎了好几个小时。太开心了!
  • 这可以通过删除== True 部分来优化。 if 条件可以写成if n.isalpha():
【解决方案4】:

不要使用print(n.isaplha()),它永远是True。删除 print() 并仅使用 n.isalpha()
试试这个:-

while True:
    n = input("write something")
    if print(n.isalpha()) == True:
        print(n)
        break
    else:
        print("Has to be in alphabets only.")

【讨论】:

  • print 返回None (正如大多数其他答案所指出的那样)。它不会总是为真(这意味着什么?)。
  • 它不会返回任何内容。试试看:a = 'Hi'print(a.isalpha()),不是返回true吗?如果我仍然错了,对不起
  • 我的意思是:a = print("something"),然后是a is None。您在示例中打印的是isalpha 的返回值(实际上是bool)。
  • 谢谢!我现在很解放了......经过几个小时的挠头!谢谢。
  • 这段代码与问题中的代码有何不同?
猜你喜欢
  • 1970-01-01
  • 2022-01-19
  • 2019-04-12
  • 2020-12-30
  • 2014-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多