寻找最小的数字

时间:2016-10-27 15:49:18

标签: python

我正在尝试找到最小的数字,您可以输入尽可能多的数字,当您输入-1时,它会中断。

a=int(input("What is your number of choice? "))
b=int(input("What is your number of choice? "))
c=int(input("What is your number of choice? "))
d=int(input("What is your number of choice? "))
smallest=a

if (b < smallest):
    smallest=b
    while(True):
    smallest =int( input("What is your number of choice? "))

    if (smallest == -1):
       break
if (c < smallest):
    smallest=c
    while(True):
    smallest =int( input("What is your number of choice? "))

    if (smallest == -1):
       break
if (d < smallest):
    smallest=d
    while(True):
    smallest =int( input("What is your number of choice? "))

    if (smallest == -1):
       break
print(smallest, " is smallest of the numbers you chose")

我无法弄清楚如何修复它。

2 个答案:

答案 0 :(得分:1)

您需要设置一个循环以允许用户输入多个值。跟踪这些值可以使用列表完成,并按如下方式将每个输入附加到它:

all_inputs = []
val = int(input('Enter a number (or -1 to finish):'))

while val != -1:
    all_inputs.append(val)
    val = int(input('Enter a number (or -1 to finish):'))

print(str(min(all_inputs)) + ' is the smallest of your numbers')

min可以有效地找到最小值输入。

答案 1 :(得分:0)

如果c小于bb小于a,则您永远无法访问c<smallest代码,因为您输入了前一个bucle。

您还需要正确缩进代码。

if (b < smallest):
    smallest=b
    while(True):
        smallest =int( input("What is your number of choice? "))

        if (smallest == -1):
            break

最后,break退出方法而不执行las打印行。