Python: If (user_input) in dictionary - python

Having an issue with checking if user input is in a dictionary.
Basics of program is there's a shop inventory. The items are stored in a dictionary with corresponding values e.g. {'kettle': 3,.....}
Then I want user to write what they want. So if the user has entered 'kettle' I want to remove the item from the shop inventory and put in user inventory.
The main problem right now is just getting an if statement together. This is what I'm trying:
user_choice = input('What would you like to buy? ')
if user_choice in shop_inventory:
print('Complete')
else:
print('Fail')
How can I get the program to print "Complete"?

You can use pop() to remove the item from the shop_inventory.
shop_inventory = {'kettle': 3}
user_choice = input('What would you like to buy? ')
if user_choice in shop_inventory:
shop_inventory.pop(user_choice)
print(shop_inventory)
print('Complete')
else:
print('Fail')

Instead of input(), use raw_input:
user_choice = raw_input('What would you like to buy? ')
if user_choice in shop_inventory:
print('Complete')
else:
print('Fail')
Explanation:
In Python 2, raw_input() returns a string, and input() tries to run the input as a Python expression.
In Python 3 there is only raw_input(). It was renamed in input().
As statet here

Related

Appending and inserting user input values to a list which dose not already have them included

drinksList = ["Fanta", "CocaCoal", "7up"]
userDrink = input("What soft drink are you looking for?")
if userDrink in drinksList:
print(userDrink,"is in stock!")
elif userDrink not in drinksList:
print("Sorry,", userDrink,"is currently not is stock.")
From here I would like to ask the user whether or not they would like to order the named soda in. If they answer yes I want to append or insert their named soda into my list.
order = input("Would you like us to order some for you?")
if order == "yes" or order == "Yes":
drinksList.append("userDrink")
print("Ok, we have added", userDrink,"to our stock!")
print(drinksList)
I would also want the code to end if the user does not want to order their drink. But at the end display the message "Thank-you for coming!". I only want this message to appear through this path and not at the end of the code, which keeps happening.
else:
print("Ok, thank-you for coming!")
print("Ok, we have added", userDrink," to our stock!")
Here it does not print what the user has inputted but instead prints the word userDrink.
Not entirely sure what you're going for but maybe something like this:
drinksList = ["Fanta", "CocaCoal", "7up"]
userDrink = input("What soft drink are you looking for?")
if userDrink in drinksList:
print(userDrink,"is in stock!")
else:
print("Sorry,", userDrink,"is currently not is stock.")
order = input("Would you like us to order some for you?")
if order.lower() == 'yes':
drinksList.append(userDrink)
print("Ok, we have added", userDrink,"to our stock!")
print(drinksList)
else:
print('Thank you for coming')

Running if-else statements more than once

I have the following code:
print('WELCOME TO YOUR TASK MANAGER!')
#Asks the user for a filename.
filename = input('What would you like your filename to be: \n(Please type
\'.txt\' at the end of the name)');
#Creates an empty list and asks the user for the tasks needing to be written down and creates a file.
tasks = []
with open(filename, 'w+') as f:
prompt = 'Please enter what you need to do: \n When you are done putting in
tasks please type \'exit\' '
user_input = input(prompt).strip()
while (user_input != 'exit'):
tasks.append(user_input)
user_input = input(prompt).strip()
#Asks the user whether or not he/she would like to add, remove, or exit the program.
prompt1 = input('Would you like to add or remove a task? \nIf add please
type \'add\'. \nIf remove please type \'remove\'.\n If not please type
exit.')
if prompt1 == 'add':
prompt1 = input('Please say what you would like to add:')
tasks.append(prompt1)
if prompt1 == 'remove':
prompt1 = input('Please say what you would like to remove:')
tasks.remove(prompt1)
tasks.sort()
f.write(str(tasks))
else:
tasks.sort()
f.write(str(tasks))
#Outputs the list of the tasks to the user and tells the user where a copy of the list is saved.
print(tasks)
print('A copy of your tasks is in the file \'{}\''.format(filename))
I would like to be able to run the prompt1 input as many times as needed until the user enters exit. However, when running the code it only allows the user to enter one of the 3 choices: add, remove, or exit. Any ideas on how I could write the code to allow multiple entries from prompt 1 after the first entry is submitted?
This should work:
tasks = []
with open(filename, 'w+') as f:
prompt = 'Please enter what you need to do: \n When you are done putting in
tasks please type \'exit\' '
prompt1 = input(prompt).strip()
while (prompt1 != 'exit'):
tasks.append(user_input)
#Asks the user whether or not he/she would like to add, remove, or exit the program.
prompt1 = input('Would you like to add or remove a task? \nIf add please
type \'add\'. \nIf remove please type \'remove\'.\n If not please type
exit.')
prompt1 = prompt1.strip()
if prompt1 == 'add':
prompt1 = input('Please say what you would like to add:')
tasks.append(prompt1)
elif prompt1 == 'remove':
prompt1 = input('Please say what you would like to remove:')
tasks.remove(prompt1)
tasks.sort()
f.write(str(tasks))
else:
tasks.sort()
f.write(str(tasks))
#Outputs the list of the tasks to the user and tells the user where a copy of the list is saved.
print(tasks)
print('A copy of your tasks is in the file \'{}\''.format(filename))
Changes made:
Used elif instead of second if. Else even if first condition satisfies, second condition need also be treated.
replaced the user_input variable with prompt1 itself
Brought printing the tasks outside the user input loop
You can try something like this :
a = input("Enter a file name: ")
task = []
while a != ("stop"):
#if else logic
.....
print(task)
a = input("Enter a word: ")
I hopes this is the code, what are you looking for.
#!/usr/bin/python3
import sys
print('WELCOME TO YOUR TASK MANAGER!')
#Asks the user for a filename.
filename = input("What would you like your filename to be: \n(Please type\.txt\' at the end of the name)");
#Creates an empty list and asks the user for the tasks needing to be written down and creates a file.
tasks = []
while True:
prompt = 'Please enter what you need to do: \n When you are done putting in tasks please type \"exit\"" '
user_input = input(prompt).strip()
if user_input == 'exit':
with open(filename, 'w+') as f:
f.write(tasks)
sys.exit()
else:
tasks.append(user_input)
#Asks the user whether or not he/she would like to add, remove, or exit the program.
prompt1 = input('Would you like to add or remove a task? \nIf add please type \'add\'. \nIf remove please type \"remove\".\n If not please type exit.')
if prompt1 == 'add':
prompt1 = input('Please say what you would like to add:')
tasks.append(prompt1)
elif prompt1 == 'remove':
prompt1 = input('Please say what you would like to remove:')
tasks.remove(prompt1)
tasks.sort()
f.write(str(tasks))
else:
if user_input == 'exit':
with open(filename, 'w+') as f:
f.write(tasks)
sys.exit()

Break if input left blank inside of an if statement

I have a school assignment for Python in which I have a backpack of items and need to make code to ask the user if they want to: a) add an item to the backpack, b) check the items in the backpack, and c) quit the program.
For my code, I want to make it so that if the user at input for adding a new item just hits return and leaves the input blank, it will re-prompt to the input again rather than continuing the code if no item is actually added. Here's what I have so far:
import sys
itemsInBackpack = ["book", "computer", "keys", "travel mug"]
while True:
print("Would you like to:")
print("1. Add an item to the backpack?")
print("2. Check if an item is in the backpack?")
print("3. Quit")
userChoice = input()
if (userChoice == "1"):
print("What item do you want to add to the backpack?")
itemAddNew = input()
if itemAddNew == "":
break
else:
itemsInBackpack.insert(0, itemAddNew)
print("Added to backpack.")
With my code here, even if I hit return in a test and leave the input blank, the code still continues onward and doesn't break to re-prompt input again. Is it because I'm using an if statement inside of an if statement already? I'm sure in general there's a better way to do this, but as a beginner I'm stumped and could use a shove in the right direction.
The break stops everything in your loop and causes your program to end.
If you want to prompt for input until the user gives you something, change this:
print("What item do you want to add to the backpack?")
itemAddNew = input()
if itemAddNew == "":
break
to this:
print("What item do you want to add to the backpack?")
itemAddNew = input()
while itemAddNew == "":
#Added some output text to tell the user what went wrong.
itemAddNew = input("You didn't enter anything. Try again.\n")
This will keep going WHILE the text is empty.

How do I ask the user if they want to play again and repeat the while loop?

Running on Python, this is an example of my code:
import random
comp = random.choice([1,2,3])
while True:
user = input("Please enter 1, 2, or 3: ")
if user == comp
print("Tie game!")
elif (user == "1") and (comp == "2")
print("You lose!")
break
else:
print("Your choice is not valid.")
So this part works. However, how do I exit out of this loop because after entering a correct input it keeps asking "Please input 1,2,3".
I also want to ask if the player wants to play again:
Psuedocode:
play_again = input("If you'd like to play again, please type 'yes'")
if play_again == "yes"
start loop again
else:
exit program
Is this related to a nested loop somehow?
Points for your code:
Code you have pasted don't have ':' after if,elif and else.
Whatever you want can be achived using Control Flow Statements like continue and break. Please check here for more detail.
You need to remove break from "YOU LOSE" since you want to ask user whether he wants to play.
Code you have written will never hit "Tie Game" since you are comparing string with integer. User input which is saved in variable will be string and comp which is output of random will be integer. You have convert user input to integer as int(user).
Checking user input is valid or not can be simply check using in operator.
Code:
import random
while True:
comp = random.choice([1,2,3])
user = raw_input("Please enter 1, 2, or 3: ")
if int(user) in [1,2,3]:
if int(user) == comp:
print("Tie game!")
else:
print("You lose!")
else:
print("Your choice is not valid.")
play_again = raw_input("If you'd like to play again, please type 'yes'")
if play_again == "yes":
continue
else:
break

I want to have a yes/no loop in my code, but I'm having trouble doing it (python 3.3)

Sorry I'm just a beginner at python so this is probably a very simple question, but I have a code and I want to loop it so after the code asks the user if they want to play again and the user inputs 'yes' to restart the code and 'no' to end the code. If they input anything other than yes or no it should ask tell them to enter yes or no then ask the question again. How would I do this exactly? (I do know about while and for loops but I'm not sure how I would use them in this way)
This is a simple one:
while True:
a = input("Enter yes/no to continue")
if a=="yes":
gameplay()
continue
elif a=="no":
break
else:
print("Enter either yes/no")
Where gameplay function contains the code to be executed
I would do it the following way:
while True:
# your code
cont = raw_input("Another one? yes/no > ")
while cont.lower() not in ("yes","no"):
cont = raw_input("Another one? yes/no > ")
if cont == "no":
break
If you use Python3 change raw_input to input.
My approach to this:
# Sets to simplify if/else in determining correct answers.
yesChoice = ['yes', 'y']
noChoice = ['no', 'n']
# Prompt the user with a message and get their input.
# Convert their input to lowercase.
input = raw_input("Would you like to play again? (y/N) ").lower()
# Check if our answer is in one of two sets.
if input in yesChoice:
# call method
elif input in noChoice:
# exit game
exit 0
else:
print "Invalid input.\nExiting."
exit 1
I think this is what you are looking for
def playGame():
# your code to play
if __name__ == '__main__':
play_again = 'start_string'
while not play_again in ['yes', 'no']:
play_again = raw_input('Play Again? (type yes or no) ')
if play_again == 'yes':
playGame()
I tried this short boolean script that will maintain the loop until the if statement is satisfied:
something = False
while not something:
inout = raw_input('type "Hello" to break the loop: ')
if inout == 'Hello':
something = True
my approach is to just have a while loop
y_or_n = input("Do you want to validate another email or not? y/n: ")
while y_or_n == 'y' or email_again == 'yes':
name = input("Enter another name ")#adapt this to your needs
name = name.lower()#adapt this to your needs
#your code etc
y_or_n = input("Do you want to validate another email or not? y/n: ")

Categories

Resources