简体   繁体   中英

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. 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 the user inputs the largest age so far, it gets added to ageslst and is now the largest value there. Testing if age > max(ageslst) will therefore never be 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. 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.

Reworking it to fix these issues:

if age > max(ageslst):
        print('Oldest')    
elif age < min (ageslst):
        print(' Youngest')
ageslst.append(age)
  1. Check if age exceeds the maximum age in the list
  2. Otherwise, check if age is smaller than the minimum age in the list
  3. Finally, append age to the list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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