Coursera Python:为每个人分配编程5.2

时间:2016-12-28 12:30:34

标签: python numbers variable-assignment

我一直在学习Coursera的课程,用Python编写每个人的程序。但第7周的任务5.2之一引起了我的注意。

目标是让用户输入一些数字并输入完成,当他输入他想要的所有数字时。之后,输出应该是他输入的最大数字和最小数字。

这是问题所在。如果我输入负数,则不会显示。我们输入:32,55,10,-2 76.输出应为76和-2。但真正发生的是76和10打印出来。

你知道为什么会这样吗?

这是代码。

largest = None
smallest = None
while True:
    try:
        num = input("Enter a number: ")
        if num == "done":
            break
        print (num)

        num = int(num)

        for number in range(num):

            if largest is None or largest < num:
                largest = num
                continue
            elif smallest is None or smallest > num:
                smallest = num       
    except ValueError:
        print("Please, enter only numbers.")

print ("Maximum", largest)
print ("Minimum", smallest)

3 个答案:

答案 0 :(得分:3)

嗯,问题是如果它不是一个列表,为什么要迭代一个int? 你宁愿用循环来做这件事:

largest = None
smallest = None
while True:
    try:
        num = input("Enter a number: ")
        if num == "done":
            break
        print (num)
        num = int(num)
        if largest is None or largest < num:
            largest = num
        elif smallest is None or smallest > num:
             smallest = num
    except ValueError:
        print("Please, enter only numbers.")

print ("Maximum", largest)
print ("Minimum", smallest)

输出:

Enter a number: 12
12
Enter a number: 56
56
Enter a number: 34
34
Enter a number: -2
-2
Enter a number: 17
17
Enter a number: done
Maximum 56
Minimum -2

答案 1 :(得分:0)

嗯,这就是我的答案。尝试这个。让我知道您不了解的内容。

largest = None
smallest = None

while True:
    try:
        num = input("Enter a number: ")
        if num == "done" :
            break
        num = int(num)
        if largest is None or num > largest:
            largest = num
        elif smallest is None or num < smallest:
            smallest = num
    except ValueError:
        print("Invalid input")

print("Maximum is", largest)
print("Minimum is", smallest)

答案 2 :(得分:0)

此代码适用于您的任务

最大=无 最小=无 而True: 尝试: num = input(“输入数字:”) 如果num ==“ done”: 打破 #打印(数字)

    num = int(num)

    for number in range(num):

        if largest is None or largest < num:
            largest = num
            continue
        elif smallest is None or smallest > num:
            smallest = num
except ValueError:
    print("Invalid input")

打印(“最大为”,最大) 打印(“最小为”,最小)