While loop, how do I condition for when input equals nothing? - python

Create a program that will keep track of items for a shopping list. The program should keep asking for new items until nothing is entered (no input followed by enter key). The program should then display the full shopping list
How do I write the condition so it works?
The code I'm writing looks like this:
x = []
i = 0
while i != '':
x.append(input('what u want?'))
i = i + 1
print(x)
```
`

Hitting Enter only on input() returns an empty string. Values such as empty containers, zero-length strings, or numerically equivalent to zero are considered false in conditional statements.
Python >= 3.8 (supports := operator):
items = []
while item := input('Item? '):
items.append(item)
print(items)
Python < 3.8:
items = []
while True:
item = input('Item? ')
if not item: break
items.append(item)
print(items)
Demo:
Item? one
Item? two
Item? three
Item?
['one', 'two', 'three']

Find len of user input & check with if accordingly
x = []
while 1:
ask= input('what u want?')
if len(ask)>0:
x.append(ask)
else:
print("Good bye")
break
print(x)
output #
what u want?rice
what u want?sugar
what u want?
Good bye
['rice', 'sugar']
Code correction
It is not ideal to choose hit enter to exit the loop. You need to assign keyword to make sure user really wants to exit.
x = []
while 1:
ask= input('what u want?')
if len(ask)>0 and ask !="finish":
x.append(ask)
else:
print("Good bye")
break
print(x)
With this user will have clarity when to checkout.
More interactive way:
x = []
while 1:
ask= input('what u want?')
if len(ask)>0 and ask !="finish":
x.append(ask)
else:
confirmation = input('Do you really want to exit? - yes or no')
if confirmation =="yes":
print("Good bye")
break
else:
print("Let's continue shopping")
pass
print(x)

Related

Doesn't remove duplicate strings in the list in one instance

How do I make a for loop in elif choice == 2?
let's say I have the list ["egg, "eGG", "radish", "pork", "meat"] from user input, if the user decides to remove egg, both egg and eGG should be removed.
Here's my code:
print(" MY GROCERY LIST ")
#function that adds items, removes items, prints the list of items, exits the program with the user's will.
def grocerylist():
grocery_list = [""]
grocery = True
#while loop
while grocery:
choice = str(input("=====================\nWhat would you like to do? \n1 - Add an item\n2 - Remove an item \n3 - Print entire list\n4 - Exit program\n\nChoice: "))
#conditionals
#adds an item
if choice == "1":
print("=====================\nADD AN ITEM\n")
add_item = str(input("What would you like to add? \nItem name: ")).format() #format function
grocery_list.append(add_item)
#removes an item
elif choice == "2":
print("=====================\nREMOVE AN ITEM\n")
remove_item = str(input("What would you like to remove? \nItem name: ")).format() #format function
grocery_list.remove(remove_item)
#prints the entire list
elif choice == "3":
print("=====================\nPRINTING LIST...")
#for loop to iterate grocery_list
for i in grocery_list:
print(i)
#terminates the program
elif choice == "4":
print("=====================\nTerminating program...")
break
else:
pass
#calling of function
grocerylist()
I tried using a for loop but it didn't work.
You can use a while loop to loop over all the items in the array, and then use call the lower() function on each element in the array list. This will make all the characters in an element lowercase and then you can compare. You would also have to lowercase the user input to compare correctly.
elif choice == "2":
print("=====================\nREMOVE AN ITEM\n")
remove_item = str(input("What would you like to remove? \nItem name: "))
i = 0
while i < len(grocery_list):
if grocery_list[i].lower() == remove_item.lower():
grocery_list.pop(i)
else:
i += 1
However, I would recommend using another array, and then appending the results that do not match the item you are trying to remove. The resulting tempArray will contain only the remaining items.
Modifying a list while iterating over it is a bad idea. It leads to unexpected behavior. Instead, generate a new list with a list comprehension, and if you want to, assign that back to your original variable.
E.g.
>>> lst = ["egg", "eGG", "radish", "pork", "meat"]
>>> lst = [item for item in lst if item.lower() != "egg"]
>>> lst
['radish', 'pork', 'meat']
>>>

How can I convert the sum of my list to an Integer in Python 3? [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 8 months ago.
I don't understand why the code is causing errors. For example, the error says that you can't add an integer and a string together, but I've already converted the string to an Integer. Could you help me fix it? The code is attached. Thanks.
# In this program I will collect data
# values from the user and use python built-in functions
# to display various info about the data set
# Giving user directions
print("In this programme, you can enter")
print("some numbers and it will display the")
print("minimum, maximum, range and average")
print("of the data set you entered.")
# Setup
list = []
loop = True
# Creating function for process of entering number
def enterNumber():
print()
x = input("Enter an integer: ")
y = str.isdigit(x)
if y == True:
list.append(x)
print()
print("Successfully added to list")
print()
print("Here is your list so far")
print(list)
elif y == False:
print()
print("Sorry, this is not an integer")
else:
print("Error. Kill and start again")
while loop == True:
enterNumber()
print()
print("Would you like to add another value?")
print()
a = input("Enter 1 for Yes, enter 0 for No: ")
if a == "0":
loop = False
print()
print()
print("------------------------------------------------")
print()
print("Count:", len(list))
print()
print("Minimum:", min(list))
print()
print("Maximum:", max(list))
print()
print("Range:", int(max(list)) - int(min(list)))
print()
print("Average:", int(sum(list)) / int(len(list)))
It seems like this last line is the problem.
You need to use int() function after checking if y value is True. If not you will be appending an string value always to your list:
def enterNumber():
print()
x = input("Enter an integer: ")
y = str.isdigit(x)
if y == True:
list.append(int(x)) #int(x) converts x to integer
...
The reason for the issue is that you have string values in your list, which doesn't work.
Simple test:
l = ['1', '2']
sum(l)
results in the same error.
Easiest fix is mentioned by Cardstdani.
You have not asked for it. But there is a serious issue in your code:
You should avoid at all cost to name your list list as this overwrites the built-in list() function.
# In this program I will collect data
# values from the user and use python built-in functions
# to display various info about the data set
# Giving user directions
print("In this programme, you can enter")
print("some numbers and it will display the")
print("minimum, maximum, range and average")
print("of the data set you entered.")
# Setup
list1 = []
loop = True
# Creating function for process of entering number
def enterNumber():
print()
x = input("Enter an integer: ")
y = str.isdigit(x)
if y == True:
list1.append(x)
print()
print("Successfully added to list")
print()
print("Here is your list so far")
print(list)
elif y == False:
print()
print("Sorry, this is not an integer")
else:
print("Error. Kill and start again")
while loop == True:
enterNumber()
print()
print("Would you like to add another value?")
print()
a = input("Enter 1 for Yes, enter 0 for No: ")
if a == "0":
loop = False
print()
print()
print("------------------------------------------------")
print()
print("Count:", len(list1))
print()
print("Minimum:", min(list1))
print()
print("Maximum:", max(list1))
print()
print("Range:", int(max(list1)) - int(min(list1)))
print()
list1 = list(map(int, list1))
print("Average:", sum(list1) / len(list1))

Finding whether element entering in a list is duplicate or unique, while the program is running

so, I came across this question, where I have to create a list, take the elements as input from the user. After doing so, I have to check whether the elements entered by the user are 'Unique' or 'Duplicate', and this has to be done while the program is running. i.e if the input entered is duplicate, then I have to terminate the program then and there, otherwise proceed.
I have written the following code (Python):
list = []
num = int(input('enter no. of elements in list: '))
for i in range(0,num):
q = int(input('element %d: '%(i+1)))
list.append(q)
print(list)
cnt = 0
for i in range(0,num):
if(list[i]==q):
cnt = cnt+1
if(cnt>1):
print('Duplicate')
else:
cnt = cnt+0
if(cnt==0):
print('Unique')
print('\nProgram Terminated!')
The thing is that, I know that I might have to use the break statement in the loop where I check whether the values are equal, but I somehow can't place it correctly.
Thank you! :)
If you want to check each time the user puts in a new element, i think this is the solution to your question:
list = []
num = int(input('enter no. of elements in list: '))
for i in range(0, num):
q = int(input('element %d: ' % (i+1)))
if q not in list:
print('Unique')
list.append(q)
else:
print('Duplicate')
break
print(list)
print('\nProgram Terminated!')

Removing values in lists by user input (Python)

First time poster and I am very new to programming in general, (so please go easy on me) although I have worked in the IT industry as a help desk technician and field engineer.
I am in my first year at university and and have been asked to add a section on to a program to allow the user to remove entries that they have inputted into a list.
This is my code.
values = []
def programMenu():
print('This program will accept values until 0 is entered.')
choice = continueChoice()
if choice == 'Y':
ages = collectValues()
print('There are ', len(values),' in the data set.')
print('The values are as follows:', end ='')
print(values)
else:
return
def continueChoice():
print('Would you like to continue(Y/N):', end ='')
choice = str(input()).upper()
print(choice)
while choice != 'Y' and choice != 'N':
print('Invalid option. Would you like to continue(Y/N):', end ='')
choice = str(input()).upper()
return choice
def collectValues():
values = []
while True:
print ('Please enter each value:', end ="")
valValue = (int(input()))
if (valValue ==0):
break
values.append(valValue)
return values
def removeValues():
print(values)
print('Would you like to delete any entries?')
reage = str(input()).upper()
while reage == 'Y':
print('Which ages would you like to remove')
delVal = (int(input()))
values.remove(delVal)
else:
programMenu()
programMenu()
removeValues()
I have been trying to solve this for two days but I am getting an error "ValueError: list.remove(x): x not in list"
I have tried writing the removeValues code at the end of the operation to add values, I have tried to move the values = [] call around etc and have had no luck.
I checked the removeValues definition was actually taking the input by editing to get the program to print the value the user entered that they wished to be removed and that worked.
Any help is appreciated, I've only been coding a few months and I have emailed my lecturer but giving what's happening in the world at the moment the university are understaffed.
Thanks in advance.
before deleting the value from the list you need to add a if condition to check if value is present in the list or not for example:
if delVal in values:
values.remove(delVal)
else:
print('Value Not Found in the list')
and your while loop is in infinite loop as value of reage = 'Y' and you are not changing it inside the loop to stop.
you can use if statement instead of while.
def removeValues():
print(values)
print('Would you like to delete any entries?')
reage = str(input()).upper()
# if reage == 'Y'
if reage == 'Y':
print('Which ages would you like to remove')
delVal = (int(input()))
# check if delVal is present in the list or not
if delVal in values:
values.remove(delVal)
print('Deleted Age : '+ str(delVal))
print(values)
# if not then print the msg.
else:
print(str(delVal)+' Not Found in the list: ',str(values))
# you can uncomment the below code to again call removeValues function to ask for correct value to delete
#removeValues()
# if reage is not equal to 'Y' then it calls the programMenu again.
else:
programMenu()
You are not able to remove it because you are initializing the values in collectValues function each time. So the list is storing any value - just comment on this line and should work. Anyway, you also need to have exit criteria for each other functions.
values = []
def programMenu():
print('This program will accept values until 0 is entered.')
choice = continueChoice()
if choice == 'Y':
ages = collectValues()
print('There are ', len(values),' in the data set.')
print('The values are as follows:', end ='')
print(values)
else:
return
def continueChoice():
print('Would you like to continue(Y/N):', end ='')
choice = str(input()).upper()
print(choice)
while choice != 'Y' and choice != 'N':
print('Invalid option. Would you like to continue(Y/N):', end ='')
choice = str(input()).upper()
return choice
def collectValues():
#values = []
while True:
print ('Please enter each value:', end ="")
valValue = (int(input()))
if (valValue ==0):
break
values.append(valValue)
return values
def removeValues():
print(values)
print('Would you like to delete any entries?')
reage = str(input()).upper()
while reage == 'Y':
print('Which ages would you like to remove')
delVal = (int(input()))
values.remove(delVal)
else:
programMenu()
programMenu()
removeValues()
There are a few things that can be improved but I will try to keep the interface more or less the same.
The biggest issue is that functions in python have their own scope. That is, when you create a variable or list in a function, it is not shared in other functions.
What you need to do instead, (i think you had the right idea), is to create the list outside the functions and pass a reference to it as a parameter to each function:
values = []
def programMenu(values):
print('This program will accept values until 0 is entered.')
choice = continueChoice()
if choice == 'Y':
temp = collectValues()
values += temp # Append new values elementwise
print('There are ', len(values), ' in the data set.')
print('The values are as follows:', end='')
print(values)
else:
return
def removeValues(values):
print(values)
print('Would you like to delete any entries? (Y to continue)')
while str(input()).upper() == 'Y':
print('Which ages would you like to remove')
delVal = (int(input()))
values.remove(delVal)
print('Would you like to delete any entries? (pressY to continue)')
else:
programMenu(values)
programMenu(values)
removeValues(values)
The above functions need a reference to the initial list in order to manipulate it. Finally, a small change, in the removeValues() function, i moved the input in the while loop so that the question persists.
def collectValues():
values = [] # Not the same "values" list (not passed from reference)
while True:
print ('Please enter each value:', end="")
valValue = (int(input()))
if (valValue ==0):
break
values.append(valValue)
return values
If you have noticed, the collectValues() function does not need a reference since it only gets new values and later adds them to the values list. Also, by creating a new list in collectValues(), the other list is not affected ( it is entirely independent).

How to find the mean of a list

I'm very new to python and trying to write some code so that the user enters something. If it's an integer it's sorted into the Numbers list, if it's a string it goes into the String list.
I want to be able to find the mean of all the numbers that are in the list and print out the result.
And in the String section I want to be able to print out everything within the string and its length.
User types 'save' to exit and if input is valid that's caught.
Numbers = []
String = []
while(True):
user_input = input("What's your input? ")
if user_input == "save":
break
elif user_input.isdigit():
Numbers.append(user_input)
for i in range(len(Numbers)):
Numbers[i] = int(Numbers[i])
print(sum(Numbers)/len(Numbers)
elif isinstance(user_input, str):
String.append(user_input)
print(String)
print (len(String)-1)
else:
print("Invalid input.")
break
#use isalpha to check enterted input is string or not
#isalpha returns a boolean value
Numbers = []
String = []
while(True):
user_input = input("input : ")
if user_input == "save":
break
elif user_input.isdigit():
Numbers.append(int(user_input))
print(sum(Numbers)/len(Numbers))
elif user_input.isalpha():
String.append(user_input)
print(String)
print (len(String))
else:
print("Invalid input.")
break
There is good thing called statistics.mean:
from statistics import mean
mean(your_list)
You are using Length, which has not been defined. I think what you wanted was
print(sum(Numbers)/len(Numbers))
and you probably don't want it inside the loop, but just after it (although that might be another typo).
I found other more convenient way to produce the mean: Use statistics model and output the mean.
#import useful packages
import statistics
#Create an empty list
user_list = []
#get user request
user_input = input("Welcome to the average game. The computer is clever enough to get the average of the list of numbers you give. Please press enter to have a try.")
#game start
while True:
#user will input their number into a the empty list
user_number = input("Type the number you want to input or type 'a' to get the average and quit the game:")
#help the user to get an average number
if user_number == 'a':
num_average = statistics.mean(user_list)
print("The mean is: {}.".format(num_average))
break #Game break
else:
user_list.append(int(user_number))
print(user_list)

Categories

Resources