Python数字处理问题

时间:2016-02-10 15:06:42

标签: python

我想编写一个程序,询问用户他们希望处理多少个数字,然后询问那么多数字。然后它将找到处理的数字的总数和最大值。示例输出:

Enter the number of values to process: 5

First value: 3
Next value: 9.2
Next value: -2.5
Next value: 0.25
Next value: 6

The total is 15.95
The maximum is 9.20

我迷失的一件事是,如果我有代码for num in (1, 3) 并为num分配了多个值,如何提取这两个值?

2 个答案:

答案 0 :(得分:0)

设置example_list = list(),然后在每次请求输入时执行for循环,并通过example_list.append(input_response)将值添加到列表中。

使用相同的for循环将值提取出来以循环显示列表。

example_list = list()
total = 0
max_value = 0

for stored_number in example_list:
    # Ask for input and store in input_response variable
    example_list.append(input_response)

    # Here is where you could add the values to a counter variable, 
    # as well as check whether they are the maximum
    total += stored_number
    if stored_number > max:
        max_value = stored_number

# Display results

对于你想要的,你也可以使用内置函数max和sum:

max_value = max(example_list)
total = sum(example_list)

答案 1 :(得分:0)

# ask how many
quantity = int(raw_input("Enter the number of values to process: "))
# ask for numbers and store them in list
numbers = [float(raw_input("Enter number " + str(each) + " : ")) for each in range(0,quantity)]
#print result
print "The total is " + str(sum(numbers)) + " and the maximum is " + str(max(numbers))