How to use for comparing a specific index?

Asked

Viewed 38 times

1

In function bonAppetit, i want to pick up only the content k (in the case k=1 and the value is 10), and see if that number is less than or equal to b.

Only my program is running the whole list.

def bonAppetit(bill, k, b):
    n = len(bill)

    for k in range(n):
        if bill[k] >= b:
            print('Bon Appetit')
    del(bill[k])
    x = sum(bill)
    if x / 2 < b:
        y = (b - (x / 2))
        print(f'{y:.0f}')
print(bonAppetit([3, 10, 2, 9], 1, 7))

desired output:

Bon Appetit

output that I’m having:

Bon Appetit
Bon Appetit

1 answer

3

If you only want a specific index instead of the entire list, then access the element directly instead of making one for:

def bonAppetit(bill, k, b):
    if bill[k] >= b: # <-- **AQUI** - não precisa de for, acesse o índice diretamente
        print('Bon Appetit')
    del(bill[k])
    x = sum(bill)
    if x / 2 < b:
        y = (b - (x / 2))
        print(f'{y:.0f}')

bonAppetit([3, 10, 2, 9], 1, 7)

I also removed the variable n now unused, and upon calling the function I removed the print, because the function does not return any value, so there is nothing to print.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.