我正在写一些蟒蛇代码来计算出一个人的总薪水。
我可以通过让用户输入他们的工资来做到这一点,但我希望他们能够输入他们的名字,然后在列表的位置0搜索名称(例如.0,1 0 ,2 0,2等)。
我尝试过使用元组,但它不可调用,字典和列表对我也不起作用。
counter = 0
valid = 0
employeelist = [["thomas","2","500"], ["jake","1","750"]]
while True:
while True:
try:
name = str(input("Name:"))
except ValueError:
print("Error")
continue
else:
break
while True:
if name == employeelist[counter,0]:
print(employeelist[counter])
break
valid = 1
elif counter = 3:
print("invalid name")
break
else:
counter = counter + 1
if valid == 1:
break
months = employeelist[counter,1]
pay = employeelist[counter,1]
totalpay = int(months) * int(pay)
编辑:
我不再使用字典的代码,但是我只是编辑了[counter,1]和[0,1]到[counter] [1]的代码并且工作正常,谢谢你:D
答案 0 :(得分:0)
以下代码适用于内循环
employeelist = [["thomas","2","500"], ["jake","1","750"]]
name = ""
while True:
try:
name = input("Name:")
break
except:
print "Error"
position = -1
for i, element in enumerate(employeelist):
if element[0] == name:
position = i
break
if position == -1:
print "Invalid Name"
else:
totalpay = int(employeelist[position][1]) * int(employeelist[position][2])
答案 1 :(得分:0)
您的代码有多个错误。首先,valid=1
,在打破循环后设置 - 意味着valid=1
,永远不会设置。您也正在以这种方式检查elif counter = 3
,您应该使用两个等号,如下所示:elif counter == 3
你得到的错误,列表索引必须是整数或切片,而不是元组,因为你以错误的方式访问多维数组。而不是name == employeelist[counter, 0]
,它应该是name == employeelist[counter][0]
。
您可以通过数组迭代,但使用for循环则相当简单。
试试这种方式。
for employees in employeelist:
if name == employees[0]:
print(employee)
valid = 1
break
如果它在没有if
- 阻止运行valid = 1
的情况下遍历孔雇员列表,则永远不会被设置。
工作代码:
counter = 0
valid = 0
employeelist = [["thomas","2","500"], ["jake","1","750"]]
while True:
while True:
try:
name = str(input("Name: "))
except ValueError:
print("Error")
continue
else:
break
for employees in employeelist:
if name == employees[0]:
print(employees)
valid = 1
break
if valid == 1:
break
months = employeelist[counter][1]
pay = employeelist[counter][2]
totalpay = int(months) * int(pay)
print(totalpay)