如何从python3中的用户输入计算最小值和最大值

如何从python3中的用户输入计算最小值和最大值,python,max,min,Python,Max,Min,您需要使用列表,并将每个输入的分数附加到列表中: def main(): print("*** High School Diving ***") num_judges=int(input("How many judges are there? ")) for i in range (num_judges): scores=int(input("Ender a score: " )) x=min(scores) y=max(sco

您需要使用列表,并将每个输入的分数附加到列表中:

def main():
    print("*** High School Diving ***")

    num_judges=int(input("How many judges are there? "))

    for i in range (num_judges):
            scores=int(input("Ender a score: " ))
    x=min(scores)
    y=max(scores)

    print("Min: ", x)
    print("Max: ", y)

main()
max()
min()
将分别从该列表中选择最高值和最低值

相反,您所做的是在每次循环时用新值替换
分数
;然后尝试查找一个整数的
min()
,该整数不起作用:

scores = []
for i in range (num_judges):
    scores.append(int(input("Enter a score: " )))

您正在for循环内创建一个变量
scores
,该变量在for循环外不可见。其次,您试图在每次迭代时在
分数中过度写入值,因为
分数
不是
列表
而是
标量
类型

您应该将
分数
声明为
列表
在循环外键入,在循环内,
将每个分数追加到列表中

>>> min([1, 2, 3])
1

你就快到了,你只需要把
分数
列成一个列表并附加到它上面,这样就可以了:

scores = []
for i in range (num_judges):
        scores.append(int(input("Ender a score: " )))
x=min(scores)
y=max(scores)

如果你看一下的文档,他们实际上给了你语法,注意它需要一个iterable类型(例如非空字符串、元组或列表)

这里有更多的方法可以做到这一点

首先,至少有两个人已经发布了与Martijn Pieters的第一个答案完全相同的内容,我不想感到被冷落,所以:

def main():
    print("*** High School Diving ***")

    num_judges=int(input("How many judges are there? "))

    #define scores as a list of values
    scores = []
    for i in range (num_judges):
            scores.append(int(input("Ender a score: " ))) #append each value to scores[]
    x=min(scores)
    y=max(scores)

    print("Min: ", x)
    print("Max: ", y)

main()

现在,无论何时创建空列表并在循环中附加到它,这都与列表理解相同,因此:

scores = []
for i in range(num_judges):
    scores.append(int(input("Enter a score: ")))
x=min(scores)
y=max(scores)

同时,如果
num\u判断值
很大,而您不想构建一个巨大的列表来查找最小值和最大值,该怎么办?好吧,你可以一边走一边跟踪他们:

scores = [int(input("Enter a score: ")) for i in range(num_judges)]
x=min(scores)
y=max(scores)
然而,这并没有真正的帮助,因为在封面下,
tee
将创建与您已经创建的相同的列表。(
tee
在并行遍历两个迭代器时非常有用,但在这样的情况下就不行了。)

因此,您需要编写一个
min_和
函数,它看起来很像上一个示例中的
for
循环:

scores= (int(input("Enter a score: ")) for i in range(num_judges))
scores1, scores2 = itertools.tee(scores)
x = min(scores1)
y = max(scores2)

当然,当你不得不编写一个8行函数使其工作时,它并不是一个真正的单行函数……除了8行函数可能在将来的其他问题中可重用之外。

你到底想取的
min
max
是什么?你的
分数
只是一个
int
@HaiVu:作业是允许的(不再标记为作业)。只要这是一个真正的问题,谁的答案可能对未来的搜索有用,就没有问题。而且用户已经不在了……好吧,我们可以比单个用户更轻松地获取无用户列表的
max
,对吗?
x, y = float('inf'), float('-inf')
for i in range(num_judges):
    score = int(input("Enter a score: "))
    if score < x:
        x = score
    if score > y:
        y = score
scores= (int(input("Enter a score: ")) for i in range(num_judges))
scores1, scores2 = itertools.tee(scores)
x = min(scores1)
y = max(scores2)
def min_and_max(iter):
    x, y = float('inf'), float('-inf')
    for val in iter:
        if val < x:
            x = val
        if val > y:
            y = val
    return x, y
x, y = min_and_max(int(input("Enter a score: ")) for i in range(num_judges))