我让程序循环运行并要求用户输入。问题是...当我尝试打印时,它一直给我一个错误。我需要将其设置为特定格式。任何帮助将不胜感激。
这是错误:
Traceback (most recent call last):
File "C:\Users\one\Desktop\Sherry\Python Folder\Week 4\w4_sgomez_assgn.py", line 40, in <module>
print('\t-----' + employee[0:4] + '-----\n')
TypeError: can only concatenate str (not "list") to str
这是代码:
employee=[]
count=0
def addEmpl(employee, count):
if count < 5:
name=input('Enter Employee Name: ')
ssn=input('Enter Employee SSN: ')
phone=input('Enter Employee Phone: ')
email=input('Enter Employee Email: ')
salary=input('Enter Employee Salary: ')
report = name +',' + ssn + ',' + phone +','+ email +',' + salary
employee.insert(count,report)
count=count+1
def printEmpl(employee):
number=int(input('Press 0 to print list: '))
count = len(employee)
if (number>-1) and (number<1):
employee=employee[0]
employee='\n'.join([name,ssn, phone, email, salary])
employee[:]
print('\t-----' + employee[0:4] + '-----\n')
print('SSN: ' + employee[1] + '\n')
print('Phone: ' + employee[2] + '\n')
print('Email: ' + employee[3] + '\n')
print('Salary: $' + employee[4] + '\n')
print('\t-----------')
else:
return;
while True:
addEmp2=int(input('To add employee enter 1; to print enter 2; to search by ssn enter 3: '))
if (addEmp2 > 0)and(addEmp2 < 2):
addEmpl(employee, count)
else:
print('\t-----' + employee[0:4] + '-----\n')
print('SSN: ' + employee[1] + '\n')
print('Phone: ' + employee[2] + '\n')
print('Email: ' + employee[3] + '\n')
print('Salary: $' + employee[4] + '\n')
print('\t-----------')
答案 0 :(得分:0)
请在下面找到函数addEmpl的正确代码
def addEmpl(employee, count):
if count < 5:
name=raw_input('Enter Employee Name: ')
ssn=raw_input('Enter Employee SSN: ')
phone=raw_input('Enter Employee Phone: ')
email=raw_input('Enter Employee Email: ')
salary=raw_input('Enter Employee Salary: ')
report = name +',' + ssn + ',' + phone +','+ email +',' + salary
employee.insert(count,report)
count=count+1
此后,您还没有给出完整的错误,因此,根据我的最佳猜测,我尝试修复它。如果我的理解不正确,请告诉我。
答案 1 :(得分:0)
以下行触发了错误(在2个地方)
print('\t-----' + employee[0:4] + '-----\n')
您正在对字符串使用+
运算符,并且一起列出employee[0:4]
是一个列表。
因此错误
TypeError: can only concatenate str (not "list") to str
答案 2 :(得分:0)
问题是以下几行:
print('\t-----' + employee[0:4] + '-----\n')
您无法按原样打印它,而需要将列表转换为字符串。
string=""
for x in range(len(employee)):
string=string+x
print('\t-----' + string + '-----\n')
这里真正的问题是您实际上应该为此使用类而不是像这样的列表的结构。
class Employee:
def __init__(self,name,ssn,phone,email,salary):
self.name=name
self.ssn=ssn
self.phone=phone
self.email=email
self.salary=salary
empObj=Employee("RandomName",1231231,"444-777-8000","pretendEmail@somewhere.com",4000)
print(empObj.name)