Can't escape while loop - python

I am a beginning programmer writing in Python 3.5 for my Computer Concepts III class. This week we are working on data validation using try/except blocks and Boolean flags, modifying a program we made last week. I've almost completed my weekly assignment except for one thing. I can't figure out why I'm getting stuck in a while loop. This is the loop in question:
while not valid_data:
cont = input("Would you like to order another? (y/n) ")
if cont.lower not in yorn:
valid_data = False
else:
valid_data = True
yorn is ["y", "n"]
Here is the whole program for context:
# Program Lesson 6 Order
# Programmer Wiley J
# Date 2016.02.13
# Purpose The purpose of this program is to take an order for cookies.
# Import Class/Format Currency
import locale
locale.setlocale(locale.LC_ALL, '')
# Define Variables
boxes = 0
cost = 3.50
qty = 0
items = 0
yorn = ["y", "n"]
# Banner
print("Welcome to The Cookie Portal")
# Input
valid_data = False
while not valid_data:
name = input("Please enter your name: ")
if len(name) > 20:
print()
print("Not a valid name")
valid_data = False
elif len(name) == 0:
print("You need to enter a name")
valid_data = False
else:
print("Hello", name)
valid_data = True
cont = input("Would you like to place an order? (y/n) ")
# Process
while cont.lower() not in yorn:
cont = input("Would you like to place an order? (y/n) ")
while cont.lower() == "y":
valid_data = False
while not valid_data:
print("Please choose a flavor:")
print("1. Savannahs")
print("2. Thin Mints")
print("3. Tagalongs")
try:
flavor = int(input("> "))
if flavor in range (1, 4):
items += 1
valid_data = True
else:
valid_data = False
except Exception as detail:
print("Error", detail)
valid_data = False
while not valid_data:
try:
boxes = int(input("How many boxes? (1-10) "))
if boxes not in range (1, 11):
print("Please choose a number between 1 and 10")
valid_data = False
else:
qty += boxes
valid_data = True
except Exception as detail:
print("Error", detail)
print()
print("Please enter a number")
valid_data = False
while not valid_data:
cont = input("Would you like to order another? (y/n) ")
if cont.lower not in yorn:
valid_data = False
else:
valid_data = True
# Output
if cont.lower() == "n":
cost *= qty
print()
print("Order for", name)
print("-------------------")
print("Total Items = {}".format(items))
print("Total Boxes = {}".format(qty))
print("Total Cost = {}".format(locale.currency(cost)))
print()
print("Thank you for your order.")
I wouldn't be surprised if there are other issues with this code but they are most likely by design as per the requirements of the assignment. Any additional feedback is welcome.

It seems you are missing function-paranthesis in the end of "lower", like so:
if cont.lower() not in yorn:

Your problem is here:
if cont.lower not in yorn:
lower is a method, it should be:
if cont.lower() not in yorn:

In your code, you are doing cont.lower not in yorn. [some string].lower is a function, not a property, so you have to call it by putting parentheses after it.
cont = input("Would you like to order another? (y/n) ")
if cont.lower() not in yorn:
valid_data = False
else:
valid_data = True

You are missing a parentheses after .lower:
if cont.lower() not in yorn:

Related

Stuck at WHILE LOOP when pressing N for escaping from the loop

# Feature to ask the user to type numbers and store them in lists
def asking_numbers_from_users():
active = True
while active:
user_list = []
message = input("\nPlease put number in the list: ")
try:
num = int(message)
user_list.append(message)
except ValueError:
print("Only number is accepted")
continue
# Asking the user if they wish to add more
message_1 = input("Do you want to add more? Y/N: ")
if message_1 == "Y" or "y":
continue
elif message_1 == "N" or "n":
# Length of list must be more or equal to 3
if len(user_list) < 3:
print("Insufficint numbers")
continue
# Escaping WHILE loop when the length of the list is more than 3
else:
active = False
else:
print("Unrecognised character")
print("Merging all the numbers into a list........./n")
print(user_list)
def swap_two_elements(user_list, loc1, loc2):
loc1 = input("Select the first element you want to move: ")
loc1 -= 1
loc2 = input("Select the location you want to fit in: ")
loc2 -= 1
loc1, loc2 = loc2, loc1
return user_list
# Releasing the features of the program
asking_numbers_from_users()
swap_two_elements
I would break this up into more manageable chunks. Each type of user input can be placed in its own method where retries on invalid text can be assessed.
Let's start with the yes-or-no input.
def ask_yes_no(prompt):
while True:
message = input(prompt)
if message in ("Y", "y"):
return True
if message in ("N", "n"):
return False
print("Invalid input, try again")
Note: In your original code you had if message_1 == "Y" or "y". This does not do what you think it does. See here.
Now lets do one for getting a number:
def ask_number(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("Invalid input, try again")
Now we can use these method to create you logic in a much more simplified way
def asking_numbers_from_users():
user_list = []
while True:
number = ask_number("\nPlease put number in the list: ")
user_list.append(number)
if len(user_list) >= 3:
if not ask_yes_no("Do you want to add more? Y/N: ")
break
print("Merging all the numbers into a list........./n")
print(user_list)

How to loop same variable with different result

Hi I've got a school project which requires me to code a program that asks a user for their details it will then ask what them what size pizza they want and how many ingredients. It will then ask if they want another pizza. It will repeat this until they say no or they have six pizzas.
I don't really know how to explain my issues but I don't know how to loop the code so it asks for another pizza and each one has a different size and amount of toppings. I also don't know how I would print it.
Sorry if this is asking a lot or its confusing to understand or if the code is just painful to look at ahaha.
Thanks in advance.
CustomerName = input("Please input the customers name: ")
CustomerAddress = input("Please input the customers address: ")
CustomerNumber = input("Please input the customers number: ")
while True:
PizzaSize = input("Please input pizza size, Small/Medium/Large: ")
try:
PizzaSize = str(PizzaSize)
if PizzaSize == "Small" or "Medium" or "Large":
break
else:
print("Size not recognized")
except:
print("Invalid input")
if PizzaSize == "Small":
SizeCost = 3.25
elif PizzaSize == "Medium":
SizeCost = 5.50
elif PizzaSize == "Large":
SizeCost = 7.15
print(SizeCost)
while True:
ExtraToppings = input("Any extra toppings, 0/1/2/3/4+ ? ")
try:
ExtraToppings = float(ExtraToppings)
if ExtraToppings >= 0 and ExtraToppings <= 4:
break
else:
print("Please insert a number over 0")
except:
print("Input not recognised")
if ExtraToppings == 1:
ToppingCost = 0.75
elif ExtraToppings == 2:
ToppingCost = 1.35
elif ExtraToppings == 3:
ToppingCost = 2.00
elif ExtraToppings >= 4:
ToppingCost = 2.50
else:
print("Number not recognized")
print(ToppingCost)
``
First of all, you should put the code from the second while loop in the first. There is no need for two while true loops. Then instead of
while True:
just put
pizza_count = 0 # how many pizzas they have
wantsAnotherPizza = True
while pizza_count < 6 and wantsAnotherPizza: # while they have less than 6 pizzas and they want another one
pizza_count += 1 # increase pizza_count as they order another pizza
# ... your code here from both of the while loops
x = input("Do you want another pizza? (Y/N)")
if x == "N" or x == "n":
global wantsAnotherPizza
wantsAnotherPizza = False:
You can modify your code like this. I thing you can simply your conditionals by using dictionaries. Try this
from collections import defaultdict
customer_order = defaultdict(list)
customer_order['CustomerName'] = input("Please input the customers name: ")
customer_order['CustomerAddress'] = input("Please input the customers address: ")
customer_order['CustomerNumber'] = input("Please input the customers number: ")
pizza_size ={
'small':3.25,
'medium': 5.50,
'large': 7.15
}
toppins= {'1': 0.75,
'2':1.35,
'3':2.00,
'4':2.50,
}
order = int(input("How many orders would you like to make: "))
while order:
PizzaSize = input("Please input pizza size, Small/Medium/Large: ").lower()
ExtraToppings = input("Any extra toppings, 0/1/2/3/4+ ? ")
try:
if PizzaSize in pizza_size:
size_cost= pizza_size[PizzaSize]
if ExtraToppings:
ToppingCost= toppins[ExtraToppings]
else:
print("Number not recognized")
continue
customer_order['order'].extend([{'size':PizzaSize,'toppings': ToppingCost}])
order -= 1
else:
print("Size not recognized")
continue
except Exception as msg:
print("Invalid input", msg)
continue
else:
print('Your order is complete')
print(customer_order)

How to make it my code go back to a specific while loop in python?

I'm new to Python and I am trying to create a simple calculator. Sorry if my code is really messy and unreadable. I tried to get the calculator to do another calculation after the first calculation by trying to make the code jump back to while vi == true loop. I'm hoping it would then ask for the "Enter selection" again and then continue on with the next while loop. How do I do that or is there another way?
vi = True
ag = True
while vi == True: #I want it to loop back to here
op = input("Input selection: ")
if op in ("1", "2", "3", "4"):
vi = False
while vi == False:
x = float(input("insert first number: "))
y = float(input("insert Second Number: "))
break
#Here would be an If elif statement to carry out the calculation
while ag == True:
again = input("Another calculation? ")
if again in ("yes", "no"):
ag = False
else:
print("Please input a 'yes' or a 'no'")
if again == "no":
print("Done, Thank you for using Calculator!")
exit()
elif again == "yes":
print("okay!")
vi = True #I want this part to loop back
Nice start. To answer your question about whether there's another way to do what you're looking for; yes, there is generally more than one way to skin a cat.
Generally, I don't use while vi==True: in one section, then follow that up with while vi==False: in another since, if I'm not in True then False is implied. If I understand your question, then basically a solution is to nest your loops, or call one loop from within the other. Also, it seems to me like you're on the brink of discovering the not keyword as well as functions.
Code
vi = True
while vi:
print("MENU")
print("1-Division")
print("2-Multiplication")
print("3-Subtraction")
print("4-Addition")
print("Any-Exit")
op = input("Input Selection:")
if op != "1":
vi = False
else:
x = float(input("insert first number: "))
y = float(input("insert Second Number: "))
print("Placeholder operation")
ag = True
while ag:
again = input("Another calculation? ")
if again not in ("yes", "no"):
print("Please input a 'yes' or a 'no'")
if again == "no":
print("Done, Thank you for using Calculator!")
ag = False
vi = False
elif again == "yes":
print("okay!")
ag = False
Of course, that's a lot of code to read/follow in one chunk. Here's another version that introduces functions to abstract some of the details into smaller chunks.
def calculator():
vi = True
while vi:
op = mainMenu()
if op == "\n" or op == " ":
return None
x, y = getInputs()
print(x + op + y + " = " + str(eval(x + op + y)))
vi = toContinue()
return None
def mainMenu():
toSelect=True
while toSelect:
print()
print("\tMENU")
print("\t/ = Division; * = Multiplication;")
print("\t- = Subtract; + = Addition;")
print("\t**= Power")
print("\tSpace or Enter to Exit")
print()
option = input("Select from MENU: ")
if option in "/+-%** \n":
toSelect = False
return option
def getInputs():
inpt = True
while inpt:
x = input("insert first number: ")
y = input("insert second number: ")
try:
tmp1 = float(x)
tmp2 = float(y)
if type(tmp1) == float and type(tmp2) == float:
inpt = False
except:
print("Both inputs need to be numbers. Try again.")
return x, y
def toContinue():
ag = True
while ag:
again = input("Another calculation?: ").lower()
if again not in ("yes","no"):
print("Please input a 'yes' or a 'no'.")
if again == "yes":
print("Okay!")
return True
elif again == "no":
print("Done, Thank you for using Calculator!")
return False

When I print my list instead of using the names in the list the output shows the index numbers. Python 2D-Lists

Here is my code the lists are where Im having issues. Im new to python and I do not understand how 2D-lists work but I need to add then in to the program for a grade. Any help will be appreciated.
#Define Vars
import locale
locale.setlocale( locale.LC_ALL, '')
order_total = 0.0
price = 3.5
fmt_price = locale.currency(price, grouping=True)
qty = int(0)
#cookie list
cookie_list = list()
cookie_list = "Savannah Thin-Mints Tag-a-longs Peanut-Butter Sandwich".split()
order_list = list()
#cookie choices
def disp_items():
print("Please choose one of our flavours. Enter the item number to choose")
for c in range(len(cookie_list)):
print("{}. \t{}".format(c+1, cookie_list[c]))
print()
#Menu Choices
def disp_menu():
choice_list = ["a", "d", "m", "q"]
while True:
print("\nWhat would you like to do?")
print("a = add an item")
print("d = delete an item")
print("m = display the meal so far")
print("q = quit")
choice = input("\nmake a selection: ")
if choice in choice_list:
return choice
else:
print("I dont't understand that entry. Please Try again.")
# Math Function**********************
def calc_tot(qty):
#this function is qty * price
return qty * 3.5
def disp_order():
print("\nGirl Scout Cookie Order for", cust)
print()
print("Itm\tName\tQty\tPrice")
print("---\t----\t----\t----")
order_total_items = 0 #accumulator
order_price = 0
for c in range(len(order_list)):
detail_list = [" ", 0]
detail_list.append(order_list)
print("{}.\t{}\t{}\t{}".format(c+1, order_list[c][0], order_list[c][1], price))
order_total_items += order_list[c][1]
order_price += price
print("\nYour Order Contains {} items for total of {} \n".format(order_total_items, order_price))
print("-" * 30)
#ADD Process
def add_process():
valid_data = False
while not valid_data:
disp_items()
try:
item = int(input("Enter item number: "))
if 1 <= item <= len(cookie_list):
valid_data = True
else:
print("\nThat was not a vaild choice, please try again.")
except Exception as detail:
print("error: ", detail)
#Valid Qty
valid_data = False
while not valid_data:
try:
qty = int(input("Enter Quantity: "))
if 1 <= qty <= 10:
valid_data = True
else:
print("\nThat was not a valid quantity, please try again.")
except Exception as detail:
print("Error; ", detail)
print("Please try again")
#Function call for multiplication
item_total = calc_tot(qty)
fmt_total = locale.currency(item_total, grouping=True)
#User Choice
print("\nYou choose: {} boxes of {} for a total of {}".format(qty,
cookie_list[item-1],
fmt_total))
print()
#verify inclusion of this item
valid_data = False
while not valid_data:
incl = input("Would you like to add this to your order? (y/n): ")
print()
if incl.lower() =="y":
#2-D List
inx = item - 1
detail_list = [inx, qty]
order_list.append(detail_list)
valid_data = True
print("{} was added to your order".format(cookie_list[inx]))
elif incl.lower() == "n":
print("{} was not added to your order".format(cookie_list[inx]))
valid_data = True
else:
print("That was not a vaild response, please try again")
#Delete function
def del_item():
if len(order_list) == 0:
print("\n** You have no items in your order to delete **\n")
else:
print("\nDelete an Item")
disp_order()
valid_data = False
while not valid_data:
try:
choice = int(input("Please enter the item number you would like to delete: "))
if 1<= choice <= len(order_list):
choice = choice - 1
print("\nItem {}. {} with {} boxes will be deleted".format(choice +1,
order_list[choice][0],
order_list[choice][1]))
del order_list[choice]
valid_data = True
except Exception as detail:
print("Error: ", detail)
print("Please try again")
#Main program
# Banner
print("Welcome to the Girl Scout Cookie")
print("Order Program")
cust = input("Please enter your name: ")
while True:
choice = disp_menu()
if choice == "a":
add_process()
elif choice == "d":
del_item()
elif choice == "q":
break
disp_order()
disp_order()
print("Thank you for your order")
Here's the output
Girl Scout Cookie Order for *****
Itm Name Qty Price
--- ---- ---- ----
1. **0** 1 3.5
2. **0** 1 3.5
3. **4** 5 3.5
Your Order Contains 7 items for total of 10.5
Under name there should be a name of a girl Scout Cookie and not the index number, how do i fix this?
Many Thanks.
When you print the order in disp_order() you should print from cookie_list[c] in the second column. And print the whole item instead off just the first letter.
print("{}.\t{}\t{}\t{}".format(c+1, cookie_list[c], order_list[c][1], price))
The cookie names are not of equal length, so you'll have to adjust for that.

indentation errors in main function for connect four in python

A few minutes ago my program was fine until I tried adding in a way to make the user be asked to play again. When I put in the loop and indented everything, something got messed up really bad when I took out this part since it didn't work. Now I cant fix the indentation and nothing will work correctly. Can anyone see obvious problems?
def main():
lastRow = 0
won = 0
draw = False
player1turn = True
print("Welcome to Connect Four!")
rows = input("Please enter a number of rows: ")
check = True
while check == True:
try:
if int(rows) <= 4:
while int(rows) <= 4:
rows = input("Please enter a Valid choice: ")
else:
check = False
except ValueError:
rows = input("Please enter a Valid choice: ")
columns = input("Please enter a number of columns: ")
check2 = True
while check2 == True:
try:
if int(columns) <= 4:
while int(columns) <= 4:
columns = input("Please enter a Valid choice: ")
else:
check2 = False
except ValueError:
columns = input("Please enter a Valid choice: ")
myBoard = []
myBoardTemp = []
for i in range(int(columns)):
myBoardTemp.append(0)
for i in range(int(rows)):
myBoard.append([0] * int(columns))
printBoard(myBoard)
check3 = True
while won == 0 and draw == False:
move = input("Please enter a move: ")
while check3 == True:
try:
if int(move) < 0 or int(move) > len(myBoard[0]):
while int(move) < 0 or int(move) > len(myBoard[0]):
move = input("Please enter a valid choice: ")
else:
check3 = False
except ValueError:
move = input("Please enter a valid choice: ")
myBoard, player1turn, lastRow = move2(myBoard,int(move) - 1,player1turn)
printBoard(myBoard)
won = checkWin(myBoard,int(move) - 1, lastRow)
draw = isDraw(myBoard, won)
if won == 1:
print("Player 1 has won!")
elif won == -1:
print("Player 2 has won!")
elif draw == True:
print("It is a draw!")
The line after while check3 == True: is not indented correctly
The try after while check3 == True: isn't properly indented, although I can't tell if that is a transcription error or was in your original code.

Categories