[英]How do i find the smallest or largest value in a list in Python
I'm new to programming.我是编程新手。 So lets say i wanted to continuously store a values using a list in python of ages and if I find that someone is the youngest/oldest i want to say that on screen.因此,假设我想使用年龄 python 中的列表连续存储一个值,如果我发现某人是最年轻/最年长的,我想在屏幕上说出来。 I tried this but it doesn't seem to be working, can anyone tell me what's wrong and help me please?我试过了,但它似乎不起作用,谁能告诉我出了什么问题并帮助我?
ageslst= []
while True:
age = int(input('age?'))
ageslst.append(agelst)
if age > max(ages):
print('Oldest')
if age < min (agelst):
print(' Youngest')
This will do what you're trying to do:这将执行您要执行的操作:
ageslst= []
while True:
age = int(input('age?'))
ageslst.append(age)
if age == max(ageslst):
print('Oldest')
if age == min(ageslst):
print('Youngest')
I fixed the indentation of your second if
statement, adjusted your variables to actually be used in the places they're supposed to be used, and I also changed the test conditions from >
and <
to ==
(which tests for equality – =
is the assignment operator).我修复了你的第二个if
语句的缩进,调整了你的变量以在它们应该使用的地方实际使用,我还将测试条件从>
和<
更改为==
(测试相等性 – =
是赋值运算符)。 If the user inputs the largest age so far, it gets added to ageslst
and is now the largest value there.如果用户输入到目前为止最大的年龄,它会被添加到ageslst
并且现在是那里的最大值。 Testing if age > max(ageslst)
will therefore never be True.因此测试if age > max(ageslst)
永远不会为 True。
Finally, you should probably add some sort of termination condition to your loop or it will run forever.最后,您可能应该向循环添加某种终止条件,否则它将永远运行。
Here's a few problems:这里有几个问题:
ageslst.append(age)
if age > max(ages):
print('Oldest')
if age < min (ages):
print(' Youngest')
Each new age is stored in the age
variable, and ageslst
is the list of all ages that you've accumulated.每个新年龄都存储在age
变量中, ageslst
是您累积的所有年龄的列表。 What you wanted to do was compare the new age to the list of all prior ages.您想要做的是将新年龄与所有先前年龄的列表进行比较。
Next, if you append age
to the list prior to checking it then your if
conditions will never be True
, because the new age is always already in the list.接下来,如果您在检查之前将age
附加到列表中,那么您的if
条件将永远不会为True
,因为新的年龄始终已在列表中。
Reworking it to fix these issues:对其进行修改以解决这些问题:
if age > max(ageslst):
print('Oldest')
elif age < min (ageslst):
print(' Youngest')
ageslst.append(age)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.