【问题标题】:I can't input/output a character string to make a business card book. numbers become我无法输入/输出字符串来制作名片簿。数字变成
【发布时间】:2021-10-02 07:03:43
【问题描述】:
# -*- coding: utf-8 -*-

class NameCard:
    def __init__(self, name, age, IG, phone):
        self.name = name
        self.age = age
        self.IG = IG
        self.phone = phone

    def __str__(self):
        return "name: {}, age: {}, IG: {}, phone: {}"\
                .format(self.name, self.IG, self.age,
                       self.phone)

def get_menu():
    while True:
        try:
            menu = int(input("menu: "))
            return menu
        except:
            print("You entered the menu incorrectly. Please re-enter.")

def get_namecard_info():
    name = input("name: ")
    age = input("age: ")
    IG = input("IG: ")
    phone = input("phone: ")
    card = NameCard(name, age, IG, phone)
    return card

def find_namecard(namecard_list, phone):
    for i, card in enumerate(namecard_list):
        if phone==card.phone:
            return i
    return -1

namecard_list = []

while True:
    print("INSERT(1), SEARCH(2), MODIFY(3), DELETE(4), EXIT(0)")
    menu = get_menu()
    if menu==1:
        new_card = get_namecard_info()
        namecard_list.append(new_card)
    elif menu==2:
        find_phone = input("The phone number of the person you are looking for : ")
        index = find_namecard(namecard_list, find_phone)
        if index>=0:
            print(namecard_list[index])
        else:
            print("No data found.")
    elif menu==3:
        print("Select menu number 3")
    elif menu==4:
        print("Select menu number 4")
    elif menu==5:
        print("Select menu number 5")
        for card in namecard_list:
            print(card)
    elif menu > 5:
        print("You entered the menu incorrectly. Please re-enter.")
    elif menu==0:
        break

** 如果我输入名称,我会收到此错误。 **

enter image description here

** 但是当我输入一个数字时,它可以正常工作。 ** enter image description here

可能是数据类型的问题,但不知道是哪一部分出错了。据我所知,python在接收​​输入时不必声明变量的数据类型,这是与C语言的区别。使用类或函数或使用格式函数时会发生变化吗?

我需要修改哪些代码才能使其正常工作?

【问题讨论】:

标签: python string input output crud


【解决方案1】:

你使用的是什么版本的 Python?

这似乎发生在 3 之前的版本中,其中输入具有不同的行为:input() error - NameError: name '...' is not defined

您可以尝试使用name = raw_input("name: ") 代替答案中指出的。

【讨论】:

    【解决方案2】:

    我测试了您的脚本,它在我的系统中运行良好,并且我检查了似乎也正常的代码。这是输出

    我已经在VS Code 中使用Python 3.8.564-bit 系统中对其进行了测试。

    所以问题可能出在 Python 版本上,因为在 Python3 之前就有 raw_input 的概念。

    让我知道你的 Python 版本。

    【讨论】:

      猜你喜欢
      • 2022-06-13
      • 1970-01-01
      • 2015-12-02
      • 2021-01-07
      • 1970-01-01
      • 2015-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多