Break if input left blank inside of an if statement - python

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.

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')

Python: If (user_input) in dictionary

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

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

Code not printing what I seek

For the first bit, as I print out the "ask2", it prints out "exit" as opposed to the licence plate that it's supposed to be printing.
ask = input("-Would you like to 1 input an existing number plate\n--or 2 view a random number\n1 or 2: ")
ask2 = ""
plate = ""
if int(ask) == 1:
ask2 = ""
print("========================================================================")
while ask2 != 'exit':
ask2 = input ("Please enter it in such form (XX00XXX): ").lower()
# I had no idea that re existed, so I had to look it up.
# As your if-statement with re gave an error, I used this similar method for checking the format.
# I cannot tell you why yours didn't work, sorry.
valid = re.compile("[a-z][a-z]\d\d[a-z][a-z][a-z]\Z")
#b will start and end the program, meaning no more than 3-4 letters will be used.
# The code which tells the user to enter the right format (keeps looping)
# User can exit the loop by typing 'exit'
while (not valid.match(ask2)) and (ask2 != 'exit'):
print("========================================================================")
print("You can exit the validation by typing 'exit'.")
time.sleep(0.5)
print("========================================================================")
ask2 = input("Or stick to the rules, and enter it in such form (XX00XXX): ").lower()
if valid.match(ask2):
print("========================================================================\nVerification Success!")
ask2 = 'exit' # People generally try to avoid 'break' when possible, so I did it this way (same effect)
**print("The program, will determine whether or not the car "+str(plate),str(ask)+" is travelling more than the speed limit")**
Also I am looking for a few good codes that are good for appending (putting the data in a list), and printing.
This is what I've done;
while tryagain not in ["y","n","Y","N"]:
tryagain = input("Please enter y or n")
if tryagain.lower() == ["y","Y"]:
do_the_quiz()
if tryagain==["n","N"]:
cars.append(plate+": "+str(x))
print(cars)
When you print ask2 it prints 'exit' because you set it to exit with ask2 = 'exit', and your loop cannot terminate before ask2 is set to 'exit'.
You could use ask2 for the user's input, and another variable loop to determine when to exit the loop. For example:
loop = True
while loop:
# ...
if valid.match(ask2) or ask2 == 'exit':
loop = False
I am not quite sure what your other block of code is trying to achieve, but the way that you test tryagain is incorrect, it will never be equal to a two element list such as ["y","Y"], perhaps you meant to use in?, This change shows one way to at least fix that problem:
while tryagain not in ["y","n","Y","N"]:
tryagain = input("Please enter y or n")
if tryagain.lower() == "y":
do_the_quiz()
else:
cars.append(plate+": "+str(x))
print(cars)

While loop with multiple conditions

So my while loop just keeps looping even when it shouldn't, if there is only 1 condition the loop works and then proceeds to the next lines of code but when I add the OR statement it wont work, I'm sure it's something very silly but I'm only a beginner and have tried researching this.
Choice = input("What would you like to do? New Game, Continue, or Quit?").upper()
while Choice != "NEW GAME" or Choice != "QUIT":
print ("That input was invalid, please try again.")
Choice = input("What would you like to do? New Game, Continue, or Quit? ").upper()
if Choice == "QUIT":
quit()
The condition
Choice != "NEW GAME" or Choice != "QUIT"
will always be True. Any value of Choice will be either not "NEW GAME" or not "QUIT". Instead, use:
Choice != "NEW GAME" and Choice != "QUIT":
I think you are looking for
while Choice not in ["New Game", "Continue", "Quit"]
or better to allow for alternative capitalization:
while Choice.upper() not in ["NEW GAME", "CONTINUE", "QUIT"]
Also please uncapitalize the variable Choice. When other Python programmers see a variable that starts with a capital letter they assume at first that it is a class name.
I guess you want a and there, not a or…
Because Choice can't be at the same time not different from "NEW GAME" and from "QUIT". In other words, your loop condition is always True whatever the value of Choice is.

Categories

Resources