Help! My Python Code Isn’t Working as Expected

0
42
Asked By CodeNinja99 On

I'm new to coding and recently started learning Python. I'm experimenting with some basic code, but I'm stuck because it seems to skip line 10 and jumps directly to line 12. I haven't learned all the terminology yet, so any help would be appreciated.

Here's my code:

food = []
price = []
total = 0
while True:
if food == 'q':
break
else:
if food == '[]':
input('What food do you want? (press q to quit) ')
else:
input('What other food items do you want? (press q to quit) ')

4 Answers

Answered By HelpfulCoder42 On

It looks like you're running into some issues with how you're checking your `food` variable. First, comparing the list `food` against a string '[]' will always fail because they're not the same type. You should be checking if `food` is an empty list instead. Also, your `input` calls aren't storing the user input anywhere, which means you're not actually keeping track of what the user is entering.

Answered By CrispyCodeExpert On

Here's a cleaned-up version of your code:

food = []
price = []
total = 0

while True:
input_taken = input('What food do you want? (press q to exit): ')
if input_taken == 'q':
break
else:
price_input = int(input('Enter the price of the food: '))
food.append(input_taken)
price.append(price_input)
total += price_input
print('Your total cost of the food is: ' + str(total))

This way, the user can add multiple items and their costs, and it computes the total at the end. If they type 'q', it exits the loop.

Answered By LearningToCode88 On

Yeah, you need to make sure you're checking if the list is empty properly. Instead of `if food == '[]':`, use `if food == []:` to check if the list has items. Also, make sure to store the user's input when they enter their food. For example, you can do `food.append(input('...'))` to add their input into the list.

Answered By SavvyDev21 On

You might want to change the way you're checking for the quit command. Right now, your loop exits when you check if `food` equals 'q', but since `food` is a list, this will never be true. It's a good idea to create a separate variable for user input and check that against 'q' instead.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.