Home > Software engineering >  How to run multi parameter function with if, elif and else?
How to run multi parameter function with if, elif and else?

Time:02-11

So, I tried to make a function that adds one to a variable depending on the input, but there's an error.

def food_ch(i, a, b, c, d):
    if a in i.lower():
        first  = 1
    elif b in i.lower():
        second  =   1
    elif c in i.lower():
        third  = 1
    elif d in i.lower():
        fourth  = 1
    else:
        hungry  = 1

 
print ("What cuisine do you like the most?: Italian, Chinese, Japanese or Mexican?")
food = input("I like ")

first = 0
second = 0
third = 0
fourth = 0
hungry = 0

food_ch(food, "italian", "chinese", "japanese", "mexican")

print (first, second, third, fourth, hungry)

CodePudding user response:

Your code won't work, since the variables you are trying to update from inside your function, are not in the scope of that function/are not defined for the function.

But you should ask yourself what you want to accomplish with your code.

It seems like you want to know what option the user has chosen, and you want to make sure it is only one of these you asked for.

You can use the following code, to get the user input, if it macthes your question options, or you will get No food found.

def user_likes_that_food(food, foods):
    if food.lower() in foods:
        return food
    else:
        return "No food found"


print("What cuisine do you like the most?: Italian, Chinese, Japanese or Mexican?")

user_input = input("I like ")

user_likes = user_likes_that_food(
    user_input, ("italian", "chinese", "japanese", "mexican"))

print(user_likes)

CodePudding user response:

Your function is attempting to update global variables defined outside of its scope.

To do this kind of thing, you should use a single variable (list or dictionary) to store your counts. This would allow your function to manipulate the data generically without so many if.

A dictionary is probably the best option:

counts = { "italian":0, "chinese":0, "japanese":0, "mexican":0, "hungry":0 }

print ("What cuisine do you like the most?: Italian, Chinese, Japanese or Mexican?")

food = input("I like ").lower()

if food not in counts:
   food = "hungry"
counts[food]  = 1

print(counts)

Sample run:

What cuisine do you like the most?: Italian, Chinese, Japanese or Mexican?
I like Chinese
{'italian': 0, 'chinese': 1, 'japanese': 0, 'mexican': 0, 'hungry': 0} 
  • Related