我试图在python中为数组添加值。
def inputUser():
name.append(raw_input("Enter name = "))
age.append(raw_input("Enter age = "))
typeService.append(raw_input("Enter code of service type = "))
action=raw_input("Do you want to add another kitten = ")
while action != "n":
name.append(raw_input("Enter name = "))
age.append(raw_input("Enter age = "))
typeService.append(raw_input("Enter code of service type = "))
action=raw_input("Do you want to add another kitten = ")
def calcFee():
for i in range(len(name)):
if age[i] <= 5:
if typeService[i] == 1:
price.append(15)
elif typeService[i] == 2:
price.append(50)
elif age[i] > 5:
if typeService[i] == 1:
price.append(20)
elif typeService[i] == 2:
price.append(60)
def display():
for i in range(len(name)):
print(name[i])
print(age[i])
print(typeService[i])
print(price[i])
inputUser()
display()
我使用的数组是
name=[]
age=[]
typeService=[]
price=[]
错误是列表索引超出价格范围。 如何向数组添加项?只有价格数组没有得到价值。我错误地编码了吗?
答案 0 :(得分:1)
您永远不会致电calcFee()
,因此price
列表仍为空。在致电inputUser()
inputUser()
calcFee()
display()
另一个问题是calcFee
中的测试无法正常工作。 age
和serviceType
包含字符串,而不是数字。您需要将这些输入转换为inputUser()
def inputUser():
name.append(raw_input("Enter name = "))
age.append(int(raw_input("Enter age = ")))
typeService.append(int(raw_input("Enter code of service type = ")))
action=raw_input("Do you want to add another kitten = ")
while action != "n":
name.append(raw_input("Enter name = "))
age.append(int(raw_input("Enter age = ")))
typeService.append(int(raw_input("Enter code of service type = ")))
action=raw_input("Do you want to add another kitten = ")
如果serviceType
不是1
或2
,则calcFee()
不会附加到price
。您应该添加else
命令来处理它。
def calcFee():
for i in range(len(name)):
if age[i] <= 5:
if typeService[i] == 1:
price.append(15)
elif typeService[i] == 2:
price.append(50)
else:
price.append(0)
else:
if typeService[i] == 1:
price.append(20)
elif typeService[i] == 2:
price.append(60)
else:
price.append(0)
顺便说一下,您还应该使用else:
作为if age[i] <= 5:
命令的第二部分,因为您的elif
条件正好相反。
答案 1 :(得分:0)
使用python2.x作为raw_input进行一些清理。注意将年龄保持为int的'input'。
def inputUser():
action = 'y'
while action != "n":
name.append(raw_input("Enter name = "))
age.append(input("Enter age = "))
typeService.append(raw_input("Enter code of service type = "))
action=raw_input("Do you want to add another kitten = ")
def calcFee():
for i in range(len(name)):
if age[i] <= 5:
if typeService[i] == 1:
price.append(15)
elif typeService[i] == 2:
price.append(50)
elif age[i] > 5:
if typeService[i] == 1:
price.append(20)
elif typeService[i] == 2:
price.append(60)
def display():
for i in range(len(name)):
print(name[i])
print(age[i])
print(typeService[i])
print(price[i])
inputUser()
calcFee()
display()