简体   繁体   English

最小/最大数字程序,一旦插入负数就必须停止输入

[英]Smallest/largest numbers program, input must stop once negative number is inserted

The purpose of this program is to find the smallest and largest values in a list.该程序的目的是查找列表中的最小值和最大值。 The moment the user inputs a negative number, the program should stop.用户输入负数的那一刻,程序应该停止。 Here is the code I have written so far:这是我到目前为止编写的代码:

user_inputs = []
number = int(input())

for i in range(number):
    value = int(input())
    if i >= 0:
        user_inputs.append(value)
    else:
        break

print(min(user_inputs))
print(max(user_inputs))

As you can see, I am new to programming and still struggling to find the logic behind loops.如您所见,我是编程新手,仍在努力寻找循环背后的逻辑。 Surely, this code is ridden with mistakes and any helpful improvements is much appreciated.当然,这段代码充满了错误,非常感谢任何有用的改进。 Thanks in advance.提前致谢。

Brother one mistake that you have done is that you are using兄弟你犯的一个错误是你正在使用

for i in range(number):

basically by doing this you are telling compiler that repeat the code in for loop for "number" of times and obviously number would change every time user inputs a new number resulting in error The right way to make the code do what you want is:基本上通过这样做,您告诉编译器在 for 循环中重复代码“次数”,并且显然每次用户输入新数字时数字都会改变导致错误使代码执行您想要的正确方法是:

user_inputs = []
while True:
   number = int(input('Enter a positive number : '))
   if number >= 0 :
      user_inputs.append(number)
   else:
      print(user_inputs)
      print('Smallest number in list is : ',min(user_inputs))
      print('Largest number in list is : ',max(user_inputs))
      break

Here while loop will run continuously until a negative number has been input, so when a negative number is input the while loop woulb break.这里的while循环会一直运行,直到输入一个负数,所以当输入一个负数时,while循环就会中断。

You are checking你正在检查

i一世

when you should be checking你什么时候应该检查

value价值

you have to compare value ie if value >= 0 you are using i which is the number of iteration你必须比较值,即如果 value >= 0 你正在使用 i 这是迭代次数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM