简体   繁体   中英

If/Else Statement and Lists Within Functions - Python 3.x

So I'm trying to design two functions, one to create a list and one to check certain parameters within that list. The check() function is to see if any of the elements of the price() function's randomly generated list are >100 then inform the user which of those elements need to be recorded. To be honest, I'm not really sure where to begin with the check() function and was hoping someone might have some advice?

def price():
    priceList = [1,2,3,4,5,6,7,8,9,10]
    print ("Price of Item Sold:")
    for i in range (10):
        priceList[i] = random.uniform(1.0,1000.0)
        print("${:7.2f}".format(priceList[i]))
    print("\n")
    return priceList

I know the check() function is way off, but like I said, not exactly sure where to go with it.

def check(priceList):
    if priceList > 100
        print ("This item needs to be recorded")

Thank you in advanced for any help!

The simplest solution is to loop over the values passed to the check function.

def check(priceList, maxprice=100):
    for price in priceList:
        if price > maxprice:
            print("{} is more than {}".format(price, maxprice)
            print ("This item needs to be recorded")

You can generate the pricelist with price() and pass it to check() at once, if you like.

check(price())

This seems to be the best way to go.

def price():
    priceList = [1,2,3,4,5,6,7,8,9,10]
    print ("Price of Item Sold:")
    for i in range (10):
        priceList[i] = random.uniform(1.0,1000.0)
        print("${:7.2f}".format(priceList[i]))
    print("\n")
    return priceList

And for checking the list.

def check(): #Will go through the list and print out any values greater than 100
    plist = price()
    for p in plist:
        if p > 100:
            print("{} needs to be recorded".format(p)) 

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