试图弄清楚如何将用户输入整数列表分成不同的类别,然后将这些类别加在一起,这很困难。这是我到目前为止的内容:
def main():
again = 'y'
while again == 'y':
pos_values = []
neg_values = []
value = int(input("Please enter value: "))
if value > 0:
pos_values.append(value)
print('Would you like to add another value?')
again = input('y = yes; n = no: ')
elif value < 0:
neg_values.append(value)
print('Would you like to add another value?')
again = input('y = yes; n = no: ')
else:
print(sum.pos_values)
print(sum.neg_values)
print('Would you like to add another value?')
again = input('y = yes; n = no: ')
total = 0
all_values = neg_values + pos_values
print[all_values]
print(total + pos_values)
print(total + neg_values)
main()
我只是一年级的学生,没有任何经验,所以请保持谦虚!
答案 0 :(得分:0)
一旦修复了Mike Scotty指出的逻辑错误,其他问题实际上就是语法错误。 sum.pos_values
会给您AttributeError: 'builtin_function_or_method' object has no attribute 'pos_values'
(因为sum
是内置函数,因此需要()
而不是.
);和print[all_values]
会给您带来语法错误(因为print
也是内置函数,因此需要()
而不是[]
)。您的原始代码在任何一个列表中都没有存储零:我没有更改它。输出格式是我的猜测。
def main():
again = 'y'
pos_values = []
neg_values = []
while again == 'y':
value = int(input("Please enter value: "))
if value > 0:
pos_values.append(value)
elif value < 0:
neg_values.append(value)
else: #edit: terminate also on 0 input
break
print('Would you like to add another value?')
again = input('y = yes; n = no: ')
all_values = neg_values + pos_values
print(sum(all_values),all_values)
print(sum(pos_values),pos_values)
print(sum(neg_values),neg_values)