【问题标题】:Capital In User Input Creating Traceback Error?用户输入中的资本创建追溯错误?
【发布时间】:2018-01-23 12:02:08
【问题描述】:

我有一段简单的代码,您可以在其中输入姓名以接收有关此人的更多信息。例如,您输入“john”以获取有关 John 的信息。但是,例如,如果用户输入“John”或“JOHN”,我会收到以下回溯错误。

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    John
NameError: name 'John' is not defined

我已经能够将.lower() 插入到我的代码中的位置(当前已删除)而没有错误,但它仍然不接受“John”/“JOHN”等,并以小写形式返回有关 John 的所有信息 - 其中不是我想要的。

是否可以允许用户使用大写字母输入?我对 Python 很陌生,很欣赏这是非常直接的,我已经看到类似的线程与 .lower()input().lower() 回复和类似的,但努力找出将其包含在我的代码中以允许用户输入“约翰”等。谢谢。

class Employees:

    def __init__(self, name, lastname, age, department):
        self.name = name
        self.lastname = lastname
        self.age = age
        self.department = department
    def displayEmployees(self):
        return("The employee is called " + self.name + ' ' + self.lastname + " and is " + str(self.age) + " years old, and works in the " + self.department + " department.")

employee1 = Employees("Sam", "Smith", 25, "Office")

employee2 = Employees("John", "Smith", 23, "Admin")

employee3 = Employees("Amy", "Smith", 28, "Admin")

employee4 = Employees("Alice", "Smith", 30, "Reception")

employee5 = Employees("Chris", "Smith", 51, "Managers")

sam = employee1.displayEmployees()

john = employee2.displayEmployees()

amy = employee3.displayEmployees()

alice = employee4.displayEmployees()

chris = employee5.displayEmployees()


print("Please input the first name of the employee you wish to find out more about the employee")

【问题讨论】:

    标签: python python-3.x input lowercase


    【解决方案1】:

    你需要使用:

    name = input('Please enter the persons name').lower()
    

    【讨论】:

    • 感谢您的回复,我已将 print("请输入...") 替换为那个,但它仍然不起作用。它在运行时以蓝色生成“请输入人员姓名”,然后我输入他们的姓名并按回车键,然后我以“>>>”结束,只有当我以小写输入时,我才能获得人员信息,如果我做“约翰”等,我仍然会得到回溯错误。
    • 您需要编写一个函数来搜索正确的对象并打印所需的值。
    • 当我在 shell 中的 '>>>' 后面写上小写的名字时,我已经可以让它输出信息了。所以我猜我需要从输入函数中以某种方式引用它?我有点不确定该怎么做,因为到目前为止这是我做过的最复杂的事情,我知道所有的小细节,但现在试图把它们放在一起
    • Python 使用区分大小写的变量名,因此您不能使用 John 和 john 来表示相同的意思。我建议如果你想从用户那里得到输入,你应该使用输入功能然后搜索。使用提示符不是与程序交互的合适方式。
    猜你喜欢
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 2019-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-05
    • 2012-11-07
    相关资源
    最近更新 更多