排序问题
a = raw_input("Do you know the number of inputs ?(y/n)")
if a == 'y':
n = int(input("Enter the number of inputs : "))
total = 0
i = 1
while i <= n:
s = input()
total = total + int(s)
i = i + 1
s.sort()
print s
print('The sum is ' + str(total))
答案 0 :(得分:0)
n = int(input("Enter the number of inputs : "))
total = 0
i = 1
array = []
while i <= n:
s = int(input())
array.append(s)
total = total + int(s)
i = i + 1
array.sort()
print(array)
print('The sum is ' + str(total))
这将解决您的问题,排序适用于列表而不是str对象
答案 1 :(得分:0)
因为您在输入时尝试sort
。 sort
仅适用于迭代列表和元组。
我只是重写你的代码,
a = raw_input("Do you know the number of inputs ?(y/n)")
if a == 'y':
n = int(input("Enter the number of inputs : "))
inputs = []
for i in range(n):
s = input()
inputs.append(int(s))
inputs.sort()
print inputs
print('The sum is ',sum(inputs))
<强> 修改 强>
只需将整个操作更改为一个函数,并在while循环中输入yes / no question,并从程序中退出错误的输入。
def foo():
n = int(input("Enter the number of inputs : "))
inputs = []
for i in range(n):
s = input()
inputs.append(int(s))
inputs.sort()
print inputs
print('The sum is ',sum(inputs))
while True:
a = raw_input("Do you know the number of inputs ?(y/n)")
if a == 'y':
foo()
elif a == 'n':
print 'We are giving one more option.'
continue
else:
print 'Wrong entry'
break
答案 2 :(得分:0)
将数字存储在列表中。然后使用sum(list)获取列表中元素的总和,并排序(list)以获得按升序排序的列表。
n = int(input("Enter the number of inputs: "))
l=[]
for i in range(n):
s = input()
l.append(int(s))
print('The sum is', sum(l))
print('Sorted values', sorted(l))
你在找这个吗?