May-11-2021, 10:35 PM
(This post was last modified: May-12-2021, 03:48 PM by deanhystad.)
When your program repeats the same code or pattern over an over you should step back and rethink the logic. The code below takes the repeated code and turns it into a function.
For example, I used a dictionary instead of a list of food names and a list of food scores. This lets me use the food name as an index instead of using integers. foods['bagel'] is obviously a bagel, but score[5] requires you read the code.
If you aren't writing functions you aren't writing Python. Functions let you make programming language features customized to solving your problem. Sure you can write any program only using the built-in functions, but the code will be much longer and difficult to maintain. In my example 1 simple function lets me replace 7 lines of code in your program.
foods = {'donuts':0, 'pancakes':0, 'bacon':0, 'waffles':0, 'eggs':0, 'bagels':0} def ask(question, good_foods, score=1): """Ask quesiton. If input is 'y', add score to each food item in good_foods""" if input(question) == 'y': for food in good_foods: foods[food] += score print('Please answer each question with "y" for "yes" and "n" for "no".') # Add one to the foods if you answer yes to these questions ask('Do you like food with holes? ', ('donuts', 'bagels')) ask('Do you like stuff made from animals? ', ('bacon', 'eggs')) ask('Do you like sweets? ', ('donuts', 'pancakes', 'waffles')) # Subtract 1 from these foods if you are gluten sensitive ask('Are you gluten sensitive?', ('donuts', 'pancakes', 'waffles', 'bagels'), -1) for item, score in foods.items(): print(item, '=', score)This code does not implement the same logic as your program. I don't want to accidentally do your homework. But it is full of ideas that you could use to solve your problem.
For example, I used a dictionary instead of a list of food names and a list of food scores. This lets me use the food name as an index instead of using integers. foods['bagel'] is obviously a bagel, but score[5] requires you read the code.
If you aren't writing functions you aren't writing Python. Functions let you make programming language features customized to solving your problem. Sure you can write any program only using the built-in functions, but the code will be much longer and difficult to maintain. In my example 1 simple function lets me replace 7 lines of code in your program.