[英]How to find the second smallest/biggest number from a user input using python 3.x?
Very new to python, tried to complete a task which requires to find a summ of two biggest and two smallest numbers which were inputted by the user, the number 0 means the input is over, couldn't figure out why the code doesn't work python的新手,试图完成一个任务,需要找到用户输入的两个最大和两个最小数字的总和,数字0表示输入结束,无法弄清楚为什么代码没有工作
b = 0
c = 0
b2 = 0
c2 = 0
for i in range(-30000, 30000):
a = int(input())
if a == 0:
break
elif a > b:
b = a
elif a < c:
c = a
elif a >= b-1:
b2 = a
elif a <= c+1:
c2 = a
print(b, b2, c, c2)
summ1 = b + b2
summ2 = c + c2
print(summ1, summ2)
b - biggest number, c - smallest number, b2 - second biggest number, c2 - second smallest number b - 最大数,c - 最小数,b2 - 第二大数,c2 - 第二小数
After inputting the numbers and running the code the variables b2 and c2 are always 0, the biggest and smallest numbers work though输入数字并运行代码后,变量 b2 和 c2 始终为 0,但最大和最小数字有效
If a value is larger than b
, you don't only have to set the new b
but also move the old b
to b2
:如果 a 值大于b
,您不仅要设置新的b
还要将旧的b
移动到b2
:
elif a > b:
b, b2 = a, b
elif a < c:
c, c2 = a, c
elif a >= b2:
b2 = a
elif a <= c2:
c2 = a
The remaining elif
statements were wrong.其余的elif
语句是错误的。 The number has to be higher than b2
or smaller than c2
.该数字必须大于b2
或小于c2
。
I see that you are trying to learn Python here, so let me give you some general tips on how to solve your problem more simply:我看到你正在尝试在这里学习 Python,所以让我给你一些关于如何更简单地解决你的问题的一般提示:
max()
and min()
functions.请记住,python 具有max()
和min()
函数。One quick python tip: Your for i in range(-30000, 30000):
is really a "for forever:" In Python, we do that with while True:
一个快速的 python 提示:您for i in range(-30000, 30000):
真的是一个“永远:”在 Python 中,我们用while True:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.