【问题标题】:How to prevent ValueError in python如何防止python中的ValueError
【发布时间】:2015-12-28 21:21:44
【问题描述】:

我有一个问题,关于在仅输入 一个 字符串作为对 input 的响应时如何防止 ValueError。

elif choice == "2":
    #Input of both name and last name
    while True: #Checks for name and last name characters and their length
        name, name2 = input("Please tell me your name and last name separated by space ").split()
        if name.isalpha() and name2.isalpha() and (len(name) >= 1) and (len(name2) >= 1): 
            print("--------------------")
            print("Nice to meet you! So " + (str(name) + " " + str(name2)) + ", are you ready to begin?")
            break

        else:
            print("ERROR: Choose a name and last name with at least one character and use only letters, please!")
            print("--------------------")

我希望我的程序在要求输入两个字符串时阻止只输入一个字符串。类似于检查 name.isaplha()len(name) >= 1 我希望我的程序检查是否插入了两个字符串。如果只有一个,我希望它print("错误:请选择一个至少包含一个字符并且只使用字母的名字和姓氏!"),所以基本上else: 像输入中的其他错误一样阻止。

Screenshot

谢谢!

【问题讨论】:

标签: python


【解决方案1】:

我建议使用tryexcept

try:
    name, name2 = input("Please tell me your name and last name separated by space ").split()
except ValueError:
    print("Error: you must enter two string")

【讨论】:

  • 谢谢,这解决了我的问题。我只需要弄清楚在哪里放置用于检查长度和 alpha 的 if 语句,但都解决了。再次感谢。 =)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-02-05
  • 2013-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多