# -*- 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
这可能是数据类型的问题,但我不知道哪部分是错的。据我所知,python在接收输入时不必声明变量的数据类型,这是与C语言的区别。在使用类或函数或使用format函数时会发生变化吗?
我需要修改什么代码才能让它工作?
发布于 2021-07-26 10:31:09
您使用的是什么版本的Python?
这似乎发生在3之前的版本中,其中输入具有不同的行为:input() error - NameError: name '...' is not defined
您可以尝试使用name = raw_input("name: "),正如答案中所指出的那样。
发布于 2021-07-26 18:36:41
我测试了你的脚本,它在我的系统中运行良好,我也检查了代码,看起来也没问题。以下是输出

我已经在VS Code中使用64-bit系统中的Python 3.8.5对其进行了测试。
所以问题可能出在Python的版本中,因为在Python3之前有一个raw_input的概念。
让我知道你的Python版本。
https://stackoverflow.com/questions/68528199
复制相似问题