我正在尝试在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=[]
错误是列表索引超出价格范围。如何向数组添加项?只有价格数组没有得到价值。我错误地编码了吗?
你永远不会打电话给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
条件正好相反。
假设使用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()