the loop runs only once - python

I am having a problem with my code. The loop runs only once respective of the number the user enters. Thanks for the help.
#create an empty list and ask the user how many items they want to add
# take the items the user entered and add it to the empty list.
print("enter the number of items")
x = int(input(">")) #take number of user input with the type int
print("thanks")
print("enter your food items")
fitems = [] # empty list
for i in range(x): #range to limit the number of iteration the user entered.
items = input (">") #taking the items from the user
empty = ""
if (items == empty):# checking if the user added nothing
print("no items added")
break
else:
fitems.append(items) #add the list of items the user entered to the
empty list
print("hello here is your food items: \n",fitems) #output user items

You are missing some indentation in your code and there are also some other mistakes. This is (I think) the correct code:
print("enter the number of items")
x = int(input(">"))
print("thanks")
print("enter your food items")
fitems = []
for i in range(x):
items = input(">").strip() # there was a space before first bracket in your code, it's possible to have it there, but this is better
# edit: added .strip(), it removes extra whitespace from beginning and end
if items == "": # no need to create empty string variable, compare simply with empty string,
# edit: you can also use 'if not items:', because empty string evaluates to false
print("no items added")
break # break only if nothing added, so indent break to be only executed if empty
fitems.append(items) # you don't have to have else here, break ends the loop, so this is not executed then
print("hello here are your food items: \n",fitems) # remove 1 indent, print only after loop ended

I took the liberty to make some changes. Try this out:
# create an empty list and ask the user how many items they want to add
# take the items the user entered and add it to the empty list.
fitems = []
# Define valid input for amount of items
valid = [str(i) for i in range(1,10)] # ["1","2"...."9"]
# If item is not in the list of valid, continue asking
while True:
print("enter the number of items [1-9]")
x = input(">")
if x in valid:
break
# Convert to int
itemamount = int(x)
print("thanks\nenter your food items")
# Now ask for inputs using while > 0 and remove itemamount in each loop
while itemamount > 0:
while True:
item = input (">")
if item:
break
print("Blank input")
fitems.append(item)
itemamount-=1
print("hello here is your food items: ")
for ind,i in enumerate(fitems,1):
print("{}. {}".format(ind,i))

This would work, Since you have not indented the "break" inside the for loop
#create an empty list and ask the user how many items they want to add
# take the items the user entered and add it to the empty list.
print("enter the number of items")
x = int(input(">")) #take number of user input with the type int
print("thanks")
print("enter your food items")
fitems = [] # empty list
for i in range(x): #range to limit the number of iteration the user entered.
items = input (">") #taking the items from the user
empty = ""
if (items == empty):# checking if the user added nothing
print("no items added")
break #your error corrected
else:
fitems.append(items) #add the list of items the user entered to the
empty list
print("hello here is your food items: \n",fitems) #output user items

I think the only problem in your code is the identation, so you should change like this:
print("enter the number of items")
x = int(input(">")) #take number of user input with the type int
print("thanks")
print("enter your food items")
fitems = [] # empty list
for i in range(x): #range to limit the number of iteration the user ente red.
items = input (">") #taking the items from the user
empty = ""
if (items == empty):# checking if the user added nothing
print("no items added")
break
else:
fitems.append(items) #add the list of items the user entered to the
print("hello here is your food items: \n",fitems)

First of all break statement and else statement aren't intended properly. Furthermore when you use .append() you should add a i+=1 to loop through x , that the user inputs.
This will work :
for i in range(x): #range to limit the number of iteration the user entered.
items = input (">") #taking the items from the user
empty = ""
if (items == empty):# checking if the user added nothing
print("no items added")
break
else:
fitems.append(items) #add the list of items the user entered to the
i += 1

This will result in a no-print if nothing was entered:
print("enter the number of items")
x = int(input(">")) #take number of user input with the type int
print("thanks")
print("enter your food items")
fitems = [] # empty list
for i in range(x): #range to limit the number of iteration the user entered.
items = input (">") #taking the items from the user
empty = ""
if (items == empty):# checking if the user added nothing
print("no items added")
break
else:
fitems.append(items) #add the list of items the user entered to the\
empty list
if len(fitems)==0:
pass
else:
print("hello here is your food items: \n",fitems)

Related

How to set up user input asking for a list one at a time?

I am trying to replicate this python code but I am unsure how to go about asking for a user inputted list one at a time and then how to present the list in order and then randomly. If anyone could point me in the right direction I would appreciate it
total = 0
while True:
List = input('Enter an item or "done" to stop entering items: ')
if List == 'done':
break
print(List)
This was my original idea but I don't think it makes any sense
Append the input on an array:
all_values = []
while True:
value = input('Enter an item or "done" to stop entering items: ')
if value == 'done':
break
all_values.append(value)
print(all_values)
import random
items = []
while True:
x = input('Enter an item or "done" to stop entering items: ')
if x == 'done':
break
items.append(x)
original = ' '.join(items)
print(f'Your items in original order: {original}')
random.shuffle(items)
shuffled = ' '.join(items)
print(f'Your items in random order: {shuffled}')

Taking user input and appending it to a tuple? Python

So basically I'm trying to create a list of movies with their budgets, but I don't know how to take the input and place it into a tuple
movie_list = ()
while True:
title = print("Enter movie: ")
budget = print("Enter budget: ")
movie_list.append(title, budget)
user = input("Would you like to add more movies? (y) or (n)").upper
if user == 'N':
break
if user != 'N' and 'Y':
print("Invalid entry, please re-enter!\nContinue? (y) or (n)")
print(movie_list)
Tuples don't handle appending well. But lists do:
movie_list = [] # make a list, not a tuple
while True:
title = print("Enter movie: ")
budget = print("Enter budget: ")
movie_list.append( (title, budget) ) # append a 2-tuple to your list, rather than calling `append` with two arguments
user = input("Would you like to add more movies? (y) or (n)").upper
if user == 'N':
break
if user != 'N' and 'Y':
print("Invalid entry, please re-enter!\nContinue? (y) or (n)")
print(movie_list)
You can’t add elements to a tuple due to their immutable property. You can’t append for tuples.
Tuples are immutable in Python. You cannot add to a tuple.
A tuple is not a data structure like a list or an array. It's meant to hold a group of values together, not a list of the same kind of values.
I think I get what you want, my guess would be that you want a list of tuples. In that case, just change the first line variable to be a list.
I improved your code so your logic works:
movie_list = [] # movie_list is a list
while True:
title = input("Enter movie: ") # Use input() to get user input
budget = input("Enter budget: ")
movie_list.append((title, budget)) # Append a tuple to the list
# movie_list is now a list of tuples
# Check if the user wants to add another movie
more = None
# Loop until the user enters a valid response
while True:
more = input("Add another? (Y/N): ").upper()
if more in ("Y", "N"):
break
print("Invalid input")
# If the user doesn't want to add another movie, break out of the loop
if more == "N":
break
# Else, continue the loop
print(movie_list)
Coding apart, to write any program, first one should know the purpose of the program and its outcome. It would be better, if you can show here what the exact output you want, out of the created or appended list. As far as I understood your requirement, you should go with dictionary concept so that you can store data as pairs, like, movie and its budget.
{"movie":budget}
While taking input of budget, be sure whether you want to restrict the input value to an integer or you want to allow this as a string, like in crores. Hope this will help you.

How do you keep a list looping, whilst removing a number the user inputs each time? (Python + Jupyter Notebook)

Made a list where I want the user to insert x followed by a number. once they have inputted, say x1, I would like x1 to be removed from the list as they are asked to input another number starting with x.
I want the list to be on loop as well, only stopping until one of the groups (of three number) has been chosen.
Disclaimer - I am a beginner at Python + Jupyter Notebook
allwins = (('x1','x2','x3'),
('x4','x5','x6'),
('x7','x8','x9'),
('x1','x4','x7'),
('x2','x5','x8'),
('x3','x6','x9'),
('x1','x5','x9'),
('x7','x5','x3'))
in_item = input("Please enter x followed by a number 1-9: ")
if in_item in allsolutions:
input("Good choice. Now pick another number starting with x: ")
else in_item not in allsolutions:
input("That did not work. Try again: ")
Idk how to keep loop for atleast a few times until the user inputs 3 diff numbers that makes a group.
You can't remove something from a tuple, so you need to make the inner tuples lists.
Then you need to loop over the main tuple, removing the input from each of them if it exists. After you do this you can check if the list is empty.
allwins = (
['x1','x2','x3'],
['x4','x5','x6'],
['x7','x8','x9'],
['x1','x4','x7'],
['x2','x5','x8'],
['x3','x6','x9'],
['x1','x5','x9'],
['x7','x5','x3'])
while True:
in_item = input("Please enter x followed by a number 1-9: ")
item_found = False
solution_found = False
for sublist in allwins:
if in_item in sublist:
sublist.remove(in_item)
item_found = True
if sublist == []:
solution_found = True
if solution_found:
print("You found all of them, congratulations!")
break
elif item_found:
print("Good choice, now pick another")
else:
print("That did not work, now try again")

How do I create a loop in python that will break once user inputs quit?

I've edited my code to the following:
while(True):
#get user to input a noun as a string variable
noun = input()
#get user to input a positive number for the integer variable
number = int(input())
#if the user inputs quit into the string variable stop program
if noun == 'quit':
break
#otherwise print the output
else:
print('Eating {} {} a day keeps the doctor away.'.format(number,noun))
And I get the following error codes:
It looks like you edited the code since these answers, this should work
while(True):
noun, number = input().split()
number = int(number)
#if the user inputs quit into the string variable stop program
if noun == 'quit':
break
#otherwise print the output
else:
print('Eating {} {} a day keeps the doctor away.'.format(number,noun))
Your problem was that you're calling input twice every loop. So, noun was set to 'apples 5' and number was set to 'shoes 2' which cannot be converted to an integer. You can split the input to get your noun and number.
You should be taking the input inside the loop, otherwise it is an endless loop or if you did write quit then it would just run once. Also there is no need for the == 0 condition to break from the loop according to the problem you have presented.
The problem is that you just take the first input, just get the inputs inside the loop insted.
Also the else should be idented with the if statement and you don't need the number == 0 condition, so the resulting code should be somehting like:
while(True):
#get user to input a noun as a string variable
noun = input()
#get user to input a positive number for the integer variable
number = int(input())
if noun == 'quit':
break
else:
print('Eating {} {} a day keeps the doctor away.'.format(number,noun))
Here is how I would write. :)
while True:
noun = input("Enter a noun: ")
if noun == 'quit':
print("Quitting the program...")
break
while True:
number = input("Enter a number: ")
try:
if type(int(number)) == int:
break
except ValueError:
print("Invalid input. Please enter a number.")
if number == '0':
print("Quitting the program...")
break
print("Eating {} {} a day keeps the doctor away.".format(number, noun))

How to accept user input of a sequence?

I'm new to python and I'm trying to help out a friend with her code. The code receives input from a user until the input is 0, using a while loop. I'm not used to the python syntax, so I'm a little confused as to how to receive user input. I don't know what I'm doing wrong. Here's my code:
sum = 0
number = input()
while number != 0:
number = input()
sum += number
if number == 0:
break
In your example, both while number != 0: and if number == 0: break are controlling when to exit the loop. To avoid repeating yourself, you can just replace the first condition with while True and only keep the break.
Also, you're adding, so it is a good idea to turn the read input (which is a character string) into a number with something like int(input()).
Finally, using a variable name like sum is a bad idea, since this 'shadows' the built-in name sum.
Taking all that together, here's an alternative:
total = 0
while True:
number = int(input())
total += number
if number == 0:
break
print(total)
No need last if, and also make inputs int typed:
sum = 0
number = int(input())
while number != 0:
number = int(input())
sum += number
You can actually do:
number=1
while number!=0:
number = int(input())
# Declare list for all inputs
input_list = []
# start the loop
while True:
# prompt user input
user_input = int(input("Input an element: "))
# print user input
print("Your current input is: ", user_input)
# if user input not equal to 0
if user_input != 0:
# append user input into the list
input_list.append(user_input)
# else stop the loop
else:
break
# sum up all the inputs in the list and print the result out
input_sum = sum(input_list)
print ("The sum is: ", input_sum)
Or
If you don't want to use list.
input_list = 0
while True:
user_input = int(input("Input an element: "))
print("Your current input is: ", user_input)
if user_input != 0:
input_list += user_input
else:
break
print ("The sum is: ", input_list)
Note:
raw_input('Text here') # Python 2.x
input('Text here') # Python 3.x

Categories