Why is variable showing as undefined on line 67? - python

I am new to python and in this simple code keep getting the undefined error for price1 on line 67 where I am trying to get the order total. But, as far as I can see it is defined for each item. Any help is appreciated.
CODE SCRIPT:
print("Hello! \n" + "Welcome to Longview Coffee!")
name = input("What is your name? \n")
#greeting with custom name, present menu
print("\n Hello " + name + " thank you for coming in today! \n")
print("Here is what we are serving today? \n")
print("Coffee \n" + "Latte\n" + "Frap\n" + "Brownie\n" + "Cookie \n\n")
#end user inputs their selection
print("Please make your selection")
order1 = input()
if order1 == "frap":
price1 = 8
elif order1 == "lattee":
price1 = 6
elif order1 == "coffee":
price1 = 4
elif order1 == "brownie":
price1 = 2
elif order1 == "cookie":
price1 = 2
#end user is requested to tell how many of the item they want
quantity1 = input("How many " + order1 + "s would you like?\n")
#end user is asked if there is anything else to add to order
print("Is there anything else you would like to order today? \n")
answer2 = input()
if answer2 == "yes":
print("Please make your next selection. \n")
order2 = input()
if order2 == "frap":
price2 = 8
elif order2 == "lattee":
price2 = 6
elif order2 == "coffee":
price2 = 4
elif order2 == "brownie":
price2 = 2
elif order2 == "cookie":
price2 = 2
quantity2 = input("How many " + order2 + "s would you like?\n")
print("Alright, " + name + " your order will be ready very soon. \n")
elif answer2 == "no":
total = price1 * int(quantity1)
print("\nOkidoki, your total for todays order of comes to $" + str(total) + "\n")
total = price1 * int(quantity1) + price2 * int(quantity2)
print("\nOkidoki, your total for todays order of comes to $" + str(total) +
"\n")
Checked each line to make sure I didn't leave a item undefined. Made sure indentations were in line with statements (as far as I could tell).

Related

How can I make a "list(range)" work when the quantity is not valid?

So, i'm new to python and trying to learn it, i've watched some clips on youtube and came up with this, but the last part to check in the quantity is or is not in the list range is not working....
print ("Hello, my name is Dave, welcome to our coffe shop!!")
name = input ("What is your name?\n")
print("Hello " + name + ", thank you for comming to our coffe shop!")
print ("What can i get you ?")
menu = str("caffe latte, " + "tea, " + "black coffe")
menu_choice = ["caffe latte","tea","black coffe"]
choice1 = input() # anything
print ("This is our menu:")
print (menu)
unavailable = True
# order loop for the coffe
while unavailable:
order = input ()
if order in menu_choice:
unavailable = False
print ("And how many " + order + " would you like?")
else:
print ("Sorry we dont have " + order + ", this is our menu :\n" + menu)
if order == "caffe latte":
price = 13
elif order == "tea":
price = 9
elif order == "black coffe":
price = 15
#quantity loop
list(range(1, 10))
#here is the problem i'm having RN, the part with if not in in list is skipped
choice_number = True
while choice_number:
quantity = input()
total = price * int(quantity)
if quantity not in {list} :
choice_number = False
if quantity == "1" :
print ("Alright " + name, "that will be " + str(total) +"$,", "a", order + " comming at you!")
elif quantity >= "2" :
print ("Alright " + name, "that will be " + str(total) +"$,", quantity + " " + order + " comming at you!")
else:
print ("Quantity invalid, please select a number from 1 to 10.")
Assign this list(range(1, 10)) in a variable like qty_lst = list(range(1, 10)).
or you can simnply write:
if quantity not in list(range(1, 10)):
quantity = input("Enter Quantity")
total = price * int(quantity)
if quantity not in range(1,10) :
print ("Quantity invalid, please select a number from 1 to 10.")
else:
if quantity == "1":
print("Alright " + name, "that will be " + str(total) + "$,", "a", order + " comming at you!")
elif quantity >= "2":
print("Alright " + name, "that will be " + str(total) + "$,", quantity + " " + order + " comming at you!")
I would recommend getting rid of the listed range and just doing it like this, also you don't need a while True loop its not really needed
if quantity < 1 or quantity > 10:
# not in range
else:
# in range
Dont use if ... in range(), i'm not sure about this, but i think that doing so, python will not know that the sequence is in order and will check your value against all the sequence.
If i'm wrong, let's say i learned something :D

(Python) ELSE is being executed even when IF has been satisfied?

Doing my homework rn and a bit stuck, why does the code execute "else" even thought the "if" has been satisfied? Ignore the sloppy code, I'm very new :/
order1 = input("What would you like to order?: \n \n" + "1: " + orderBurger + "\n" + "2: " + orderFries + "\n" + "3: " + orderDrink + "\n" + "\nAnswer = ")
while order == True:
if order1 == 1:
print("You have selected to order 1: " + orderBurger)
elif order1 == 2:
print("You have selected to order 1: " + orderFries)
elif order1 == 3:
print("You have selected to order 1: " + orderDrink)
else:
print("Invalid Input")
check = input("Is this your final item?:" + "1: " + q1 + "2: " + q2 + "Answer = ")
if check == 1:
print("Your items have been added to the basket")
break
elif check == 2:
check
elif check == 3:
check
else:
print("Invalid input")
This is the output
If you use type(order1), you'll see if your answer is a string or an int. If it's a string (and I think it is), you can convert it into int using int(order1), or replace your code by if order1 == '1'
Indentation is very important in Python. Based on how the indentations are implemented, the code blocks for conditions get executed.
A misplaced indent can lead to unexpected execution of a code block.
Here is a working demo of the ordering program
# File name: order-demo.py
moreItems = True
while (moreItems == True):
order = input("\n What would you like to order?\n"
+ " 1: Burger\n 2: Fries\n 3: Drink\n Answer = ")
if ((order == "1") or (order == "2") or (order == "3")):
print("You have selected to order " + order)
print("Your item has been added to the basket.\n")
else:
print("Invalid Input")
check = input("Is this your final item?: \n 1: Yes \n 2: No \n Answer = ")
if check == "1":
print("\n Thank you. Please proceed to checkout.")
moreItems = False
elif check == "2":
print("Please continue your shopping")
else:
print("Invalid input")
Output
$ python3 order-demo.py
What would you like to order?
1: Burger
2: Fries
3: Drink
Answer = 1
You have selected to order 1
Your item has been added to the basket.
Is this your final item?:
1: Yes
2: No
Answer = 2
Please continue your shopping
What would you like to order?
1: Burger
2: Fries
3: Drink
Answer = 2
You have selected to order 2
Your item has been added to the basket.
Is this your final item?:
1: Yes
2: No
Answer = 1
Thank you. Please proceed to checkout.
$
replace first line with this :
order1 = int( input("What would you like to order?: \n \n" + "1: " + orderBurger + "\n" + "2: " + orderFries + "\n" + "3: " + orderDrink + "\n" + "\nAnswer = ") )

How to add unknown values in python

I am trying to create a cash register program. My objective is for all the products be added and the final price be found. How can I reach this goal without knowing the values previously? Below is my code. Thanks in advance for any help it is greatly appreciated
responses = {}
polling_active = True
print("Welcome to the cash register. Insert your product name and price to be able to calculate your final total")
total = 0
while polling_active:
product = input("\nProduct Name: ")
total += float(input("Price: "))
responses[product] = total
repeat = input("Is this your final checkout? (Yes/No)")
if repeat == 'no':
polling_active = True
elif repeat == 'No':
polling_active = True
elif repeat == 'Yes':
polling_active = False
elif repeat == 'yes':
polling_active = False
else:
print("That operation is invalid")
print("\n---Final Checkout---")
for product, price in responses.items():
print(product + " is $" + str(total))
print("\n---Total Price---")
print("Store Price is: ")
print("$" + str(total))
print("\n---Tax Price---")
print("Your price with tax is: ")
total = total * 1.13
print("$" + "{0:.2f}".format(float(total)))
print("\nThank you for shopping with us! Have a great day!")
I understand the with my current code, total will not allow me to add any products but that is just currently a place holder
Here is the code that you need:
responses = {}
polling_active = True
print("Welcome to the cash register. Insert your product name and price to be able to calculate your final total")
while polling_active:
product = input("\nProduct Name: ")
price = float(input("Price: "))
responses[str(product)] = price
repeat = raw_input("Is this your final checkout? (Yes/No)")
if repeat.lower() == 'no':
polling_active = True
elif repeat.lower() == 'yes':
polling_active = False
else:
print("That operation is invalid")
print("\n---Final Checkout---")
for product, price in responses.items():
print(product + " is $" + str(price))
print("\n---Total Price---")
print("Store Price is: ")
total= sum(responses.values())
print("$" + str(total))
print("\n---Tax Price---")
print("Your price with tax is: ")
total = total * 1.13
print("$" + "{0:.2f}".format(float(total)))
print("\nThank you for shopping with us! Have a great day!")
Output:
integer:
float:

Python - print name shows None

import re
import time
import sys
def main():
name = getName()
getOption()
nameForTicket, done = getTraveling(name)
price, destination = getWay()
fare = getFare()
seat = getSeat()
age = getAge()
totalcost = getTotalCost(price, fare, seat, age)
print("\n" + "Thank you " + name + " for flying us!" + "\n" + "The ticket price is: $" + str(totalcost) + "\n" + "The destination is: " + str(destination) + "\n" + "Ticket is for: " + str(nameForTicket).title())
main2(name, done)
def getName():
name = input("Welcome to Tropical Airlines! Please enter your name >>> ")
if not re.match("^[a-zA-Z ]*$", name):
print("Error, only letters allowed!")
getName()
elif len(name) > 15:
print("Error, Only 15 characters allowed!")
getName()
else:
print ("Welcome " + name.title())
return name
def getOption():
print("(I) Information" + "\n" + "(O) Order" + "\n" + "(E) Exit")
user_choice = input("Choose one of the following option >>> ")
if user_choice.upper() == "I":
displayInfo()
else:
if user_choice.upper() == "O":
return
else:
if user_choice.upper() == "E":
print("Thank you for visiting Tropical Airlines")
exit()
else:
print("Error")
getOption()
def displayInfo():
print("Thank you for choosing Tropical Airlines for your air travel needs." + "\n" + "You will be asked questions regarding what type of ticket you would like to purchase as well as destination information." + "\n" + "We also offer 50% discounted fares for children.")
getOption()
def getTraveling(name):
option = input("Who is the traveling person?" + "\n" + "(Y) You" + "\n" + "(S) Someone else")
if option.upper() == "Y":
nameForTicket = name
done = True
return nameForTicket, done
elif option.upper() == "S":
nameForTicket = getName2()
done = False
return nameForTicket, done
else:
print("Error")
getTraveling(name)
def getName2():
name2 = input("What is the travelling person name?")
if not re.match("^[a-zA-Z ]*$", name2):
print("Error, only letters allowed!")
getName2()
elif len(name2) > 15:
print("Error, Only 15 characters allowed!")
getName2()
else:
return name2
def getWay():
option = input("What kind of trip?" + "\n" + "(1) One way" + "\n" + "(2) Round trip")
if option == "1":
cost, destination = getDest1()
return cost, destination
elif option == "2":
cost, destination = getDest2()
return cost, destination
else:
print("Error")
getWay()
def getDest1():
option = input("Choose one of the following destination: " + "\n" + "(C) Cairns -- $200" + "\n" + "(P) Perth -- $250" + "\n" + "(S) Sydney -- $300")
if option.upper() == "C":
initialCost = 200
dest = "Cairns"
return initialCost, dest
elif option.upper() == "P":
initialCost = 250
dest = "Perth"
return initialCost, dest
elif option.upper() == "S":
initialCost = 300
dest = "Sydney"
return initialCost, dest
else:
print("Error")
getDest1()
def getDest2():
option = input("Choose one of the following destination: " + "\n" + "(C) Cairns -- $300" + "\n" + "(P) Perth -- $400" + "\n" + "(S) Sydney -- $500")
if option.upper() == "C":
initialCost = 300
dest = "Cairns"
return initialCost, dest
elif option.upper() == "P":
initialCost = 400
dest = "Perth"
return initialCost, dest
elif option.upper() == "S":
initialCost = 500
dest = "Sydney"
return initialCost, dest
else:
print("Error")
getDest2()
def getFare():
option = input("Choose one of the following type of fare: " + "\n" + "(B) Business -- Extra $200" + "\n" + "(E) Economy -- Extra $50" + "\n" + "(F) Frugal -- Free")
if option.upper() == "B":
fare = 200
return fare
elif option.upper() == "E":
fare = 50
return fare
elif option.upper() == "F":
fare = 0
return fare
else:
print("Error")
getFare()
def getSeat():
option = input("Choose one of the following type of seat: " + "\n" + "(W) Window -- $20" + "\n" + "(A) Aisle -- $15" + "\n" + "(M)Middle -- $10")
if option.upper() == "W":
seat = 20
return seat
elif option.upper() == "A":
seat = 15
return seat
elif option.upper() == "M":
seat = 10
return seat
else:
print("Error")
getSeat()
def getAge():
age = int(input("Enter the age, if the age is bellow 17, you will get 50% discount >>> "))
while age < 6 or age > 100:
print("Invalid age")
age= int(input("Enter the valid age >>>"))
return age
def getTotalCost(price, fare, seat, age):
if age <18:
finalCost = (price + fare + seat)/2
else:
finalCost = price + fare + seat
return finalCost
def loading():
for i in range(101):
time.sleep(0.02)
sys.stdout.write("\r%d%%" % i)
sys.stdout.flush()
def main2(name, done):
getOption()
nameForTicket = getTraveling2(name, done)
price, destination = getWay()
fare = getFare()
seat = getSeat()
age = getAge()
totalcost = getTotalCost(price, fare, seat, age)
print("\n" + "Thank you " + name + " for flying us!" + "\n" + "The ticket price is: $" + str(totalcost) + "\n" + "The destination is: " + str(destination) + "\n" + "Ticket is for: " + str(nameForTicket2).title())
main2(name, done)
def getTraveling2(name, done):
option = input("Who is the traveling person?" + "\n" + "(Y) You" + "\n" + "(S) Someone else")
if option.upper() == "Y":
if done == True:
print("You have already ordered ticket for you!")
getTraveling2(name, done)
elif done == False:
nameForTicket = name
done = True
return nameForTicket, done
elif option.upper() == "S":
nameForTicket = getName2()
return nameForTicket
else:
print("Error")
getTraveling2(name, done)
main()
Short story I was writing these long codes.
If from def main() in nameForTicket, done = getTraveling(name) I choose Y, the code shows the name instr(nameForTicket).title() for the def main() just fine.
but in def main2(): for the function getTraveling2(name, done) if I choose S, the str(nameForTicket2).title() in def main2(): will show None.
And the same happens if from main() I choose S, the main2() if I choose S will show none, and if I choose Y, it will display (Name, True)
how to fix it so the name will show based on the input for S?
In main2, change
nameForTicket = getTraveling2(name, done)
to
nameForTicket2 = getTraveling2(name, done)
because your print statement in main2 addresses str(nameForTicket2).title(), which is trying to print the title of nameForTicket2 when you set the result of the getTraveling2 method to nameForTicket instead. Therefore, the print statement gives you None since nameForTicket2 was never really defined.

Defining Functions, TypeError

Probably obvious, but for some reason, this code:
import random
import time
def tables():
global tablesUsed
tablesUsed = [int(x) for x in input("Please choose which multiplication tables you wish\nto practice, then type them like this: 2 5 10.\n").split()]
return tablesUsed
def timer():
timer = input("Do you wish to play with the timer? (yes or no)\n")
if timer == "yes":
withTimer()
else:
withoutTimer()
def withTimer():
playAgain = "yes"
total = 0
correct = 0
while playAgain == "yes":
total = total + 1
random1 = random.choice(tablesUsed)
random2 = random.randint(1, 12)
realAnswer = random1 * random2
start = time.time()
humanAnswer = int(input("What is the answer to this multiplication sum?\n" + str(random1) + " * " + str(random2) + "\n"))
if realAnswer == humanAnswer:
elapsed = round((time.time() - start), 1)
correct = correct + 1
score = str(int(correct / total * 100)) + "%"
if elapsed < 2:
print("Congratulations, you got it correct in " + str(elapsed) + " seconds!\nThat is a very good time!\nScore: " + score)
else:
print("Congratulations, you got it correct in " + str(elapsed) + " seconds!\nNow work on your time.\nScore: " + score)
else:
score = str(int(correct / total * 100)) + "%"
print("Unforunately, you got this one incorrect, the actual answer was " + str(realAnswer) + ".\nScore: " + score)
playAgain()
def withoutTimer():
playAgain = "yes"
total = 0
correct = 0
while playAgain == "yes":
total = total + 1
random1 = random.choice(tablesUsed)
random2 = random.randint(1, 12)
realAnswer = random1 * random2
humanAnswer = int(input("What is the answer to this multiplication sum?\n" + str(random1) + " * " + str(random2) + "\n"))
if realAnswer == humanAnswer:
correct = correct + 1
score = str(int(correct / total * 100)) + "%"
print("Congratulations, you got it correct!\nScore: " + score)
else:
score = str(int(correct / total * 100)) + "%"
print("Unforunately, you got this one incorrect, the actual answer was " + str(realAnswer) + ".\nScore: " + score)
playAgain()
def playAgain():
playAgain = input("Do you wish to play again? (yes or no)\n")
if playAgain == "yes":
settings()
else:
print("Thank you for practising your multiplication tables with me. Your final score was " + score + " and your average time was " + averageTime)
def settings():
settings = input("Do you wish to edit settings? (yes or no)\n")
if settings == "yes":
tables()
timer()
tables()
timer()
returns an error saying:
TypeError: 'str' object is not callable, line 66, line 10, line 35
Please could someone help and tell me what I'm doing wrong?
I gather that it's probably to do with defining functions incorrectly, but I can't find anything on that solves my problem.
You defined playAgain both as a function and a local variable in the withTimer function:
def withTimer():
playAgain = "yes"
# ...
while playAgain == "yes":
# ....
playAgain() # this is now a string, not the function
Don't do that, use meaningful names that don't shadow your function names.

Categories