I am doing a University project to create a plan ordering ticket program, so far these are what I have done:
First, this is the function finding the seat type:
def choosingFare():
print("Please choose the type of fare. Fees are displayed below and are in addtion to the basic fare.")
print("Please note choosing Frugal fare means you will not be offered a seat choice, it will be assigned to the ticketholder at travel time.")
listofType = [""] * (3)
listofType[0] = "Business: +$275"
listofType[1] = "Economy: +$25"
listofType[2] = "Frugal: $0"
print("(0)Business +$275")
print("(1)Economy +$25")
print("(2)Frugal: $0")
type = int(input())
while type > 2:
print("Invalid choice, please try again")
type = int(input())
print("Your choosing type of fare is: " + listofType[type])
if type == 0:
price1 = 275
else:
if type == 1:
price1 = 25
else:
price1 = 0
return price1, listofType[type]
And this is a function finding the destination:
def destination():
print("Please choose a destination and trip length")
print("(money currency is in: Australian Dollars: AUD)")
print("Is this a Return trip(R) or One Way trip(O)?")
direction = input()
while direction != "R" and direction != "O":
print("Invalid, please choose again!")
direction = input()
print("Is this a Return trip(R) or One Way trip(O)?")
if direction == "O":
print("(0)Cairns oneway: $250")
print("(2)Sydney One Way: $420")
print("(4)Perth One Way: $510")
else:
print("(1)Cairns Return: $400")
print("(3)Sydney Return: $575")
print("(5)Perth Return: $700")
typeofTrip = [""] * (6)
typeofTrip[0] = "Cairns One Way: $250"
typeofTrip[1] = "Cairns Return: $400"
typeofTrip[2] = "Sydney One Way: $420"
typeofTrip[3] = "Sydney Return: $575"
typeofTrip[4] = "Perth One Way: $510"
typeofTrip[5] = "Perth Return: $700"
trip = int(input())
while trip > 5:
print("Invalid, please choose again")
trip = int(input())
if trip == 0:
price = 250
else:
if trip == 1:
price = 400
else:
if trip == 2:
price = 420
else:
if trip == 3:
price = 574
else:
if trip == 4:
price = 510
else:
price = 700
print("Your choice of destination and trip length is: " + typeofTrip[trip])
return price, typeofTrip[trip]
And this is the function calculating the total price:
def sumprice():
price = destination()
price1 = choosingFare()
price2 = choosingseat()
sumprice = price1 + price2 + price
print("How old is the person travelling?(Travellers under 16 years old will receive a 50% discount for the child fare.)")
age = float(input())
if age < 16 and age > 0:
sumprice = sumprice / 2
else:
sumprice = sumprice
return sumprice
The error I have:
line 163, in <module> main()
line 145, in main sumprice = sumprice()
line 124, in sumprice
sumprice = price1 + price2 + price
TypeError: can only concatenate tuple (not "int") to tuple
Can someone help me? I am really stuck.
I can't return all the
These functions return 2 values each: destination(), choosingFare(), choosingseat().
Returning multiple values at once returns a tuple of those values:
For example:
return price, typeofTrip[trip] # returns (price, typeofTrip[trip])
So while calculating the sum of all prices, you need to access price, price1, price2 from the tuples:
sumprice = price1[0] + price2[0] + price3[0]
Alternatively: You can edit the code to return list/ dictionary or some other data structure as per your convenience.
First let me explain what happends when you write. return price, typeofTrip[trip].
The above line will return a tuple of two values.
Now for sumprice I think what you want is sum of all prices. So you just want to sum first element of returned values.
This should work for your case.
sumprice = price1[0] + price2[0] + price3[0]
Related
Ticket sales. Calculate the total, based on the number of half price and full price tickets. If the user is a student, give a 50 cent discount for each ticket. Ask user to input number of child tickets, number of adult tickets, and if the person is a student (y/n). Keep asking until user enters a 0 and a 0
FULL_PRICE = 10.00
HALF_PRICE = FULL_PRICE % 2
giveDiscount = True
def calculatePrice(nHalfPriceTix, nFullPriceTix, giveDiscount):
if giveDiscount:
total = (nHalfPriceTix * HALF_PRICE) + (nFullPriceTix * FULL_PRICE) - .5
else:
total = (nHalfPriceTix * HALF_PRICE) + (nFullPriceTix * FULL_PRICE)
return total
while True:
print()
nChildTickets = input('How many child tickets do you want? ')
nChildTickets = int(nChildTickets)
nAdultTickets = input('How many adult tickets do you want? ')
nAdultTickets = int(nAdultTickets)
if (nChildTickets == 0) or (nAdultTickets == 0):
break
yesOrNo = input('Are you a student (y/n)? ')
if yesOrNo.lower() == 'y':
isStudent = True
else:
isStudent = False
thisTotal = calculatePrice(nChildTickets, nAdultTickets)
print('Your total is $' + thisTotal)
print()
totalSales = totalSales + thisTotal
print('Total of all sales $', totalSales)
Also to add on, this:
print('Your total is $' + thisTotal)
should be:
print('Your total is $' + str(thisTotal))
since the '+' operator in print() can only accept strings(not a float).
Or you could change the + to a ,.
calculatePrice function requires 3 arguments and got only two:
thisTotal = calculatePrice(nChildTickets, nAdultTickets)
so i think for that to work you need to pass isStudent because you didnt use it
thisTotal = calculatePrice(nChildTickets, nAdultTickets,isStudent)
my problem lies within the lines of #. I don't understand why the invalidDish is always True even after it is set to False in one of the if statement.
class dishes:
def __init__(self, serial_no, dish_name, price):
self.serial_no = serial_no
self.dish_name = dish_name
self.price = price
def show_menu(self):
print(str(self.serial_no) + '. ' + self.dish_name + '\t$' + self.price)
def errorMessage(code, range):
if code == 'outOfRange':
print('***Please enter number 1 - {} only***\n'.format(str(range)))
machineRunning()
plain_prata = dishes(1, 'Plain prata', '0.50')
egg_prata = dishes(2, 'Egg prata', '1.00')
cheese_prata = dishes(3, 'Cheese prata', '2.50')
garlic_prata = dishes(4, 'Garlic prata', '1.50')
ham_prata = dishes(5, 'Ham prata', '2.50')
menu = [plain_prata, egg_prata, cheese_prata, garlic_prata, ham_prata]
current_order = []
def machineRunning():
while True:
print('1. Menu')
print('2. Add order')
print('3. Checkout')
value = input('Please input:')
try:
value = int(value)
if value < 1 or value > 3:
errorMessage('outOfRange', 3)
except ValueError:
print('***Please enter number 1 - 3 only***\n')
continue
if value == 1:
print()
for x in range(len(menu)):
menu[x].show_menu()
elif value == 2:
dish = input('Dish name/number:')
try:
dish = int(dish) - 1
if dish < 0 or dish >= len(menu):
errorMessage('outOfRange', len(menu))
except ValueError:
loop = True
while(loop):
for x in range(len(menu)):
dish = dish.capitalize()
split_dish = dish.split()
if dish == menu[x].dish_name:
dish = int(x)
loop = False
break
else:
invalidDish = True
x = 0
############################################
while invalidDish and x < len(menu):
print (invalidDish)
print (x)
if split_dish[0] in menu[x].dish_name:
isDish = input('Are you ordering ' + menu[x].dish_name + '?')
print('isDish',isDish.lower())
if 'y' in isDish.lower(): #TurningPoint
print('Entered here')
invalidDish = False
print(invalidDish)
break
else: x += 1
else: x += 1
##########################################
if invalidDish:
print('***Invalid dish name***\n')
dish = input('Dish name/number:')
amount = input('Amount:')
current_order.append([menu[dish].dish_name, menu[dish].price, amount])
else:
print('***Please enter number 1 - 3 only***\n')
for x in current_order:
print (x)
machineRunning()
I tried to follow the code in terminal and still can't figure out the problem. This is the result from the terminal.
1. Menu
2. Add order
3. Checkout
Please input:2
Dish name/number:c
True
0
True
1
True
2
Are you ordering Cheese prata?y
isDish y
Entered here
False #It is set to False at this point
True #Why it becomes True again at the beginning of the loop?
0
True
1
PS. Am learning python by trying to make a cash register for a restaurant, with generating weekly, monthly summary, calculating profit etc. Any suggestion on what I can do next to make this more user-friendly? Like python talks to other software or code making the interface for easy to use?
You are breaking out of the while loop, then looping again using the outer for loop, which then sets invalidDish to True.
I decided to make a calculator as a project.
Implementing basic addition, subtraction, division, and multiplication was fairly easy.
I wanted to add more functionality so I decided to implement a list of results the user view. However, I had a difficult time keeping track of the results numerically. I wrote a maze of if statements that are functional but seem to be overwrought with code. I am sure there is a better way to handle this.
Any advice?
def add(x, y):
return x + y
def sub(x, y):
return x - y
def mul(x, y):
return x * y
def div(x, y):
value = None
while True:
try:
value = x / y
break
except ZeroDivisionError:
print('Value is not dividable by 0, try again')
break
return value
def num_input(prompt='Enter a number: '):
while True:
try:
print(prompt, end='')
x = int(input())
break
except ValueError:
print('You must input a number. Try again.')
return x
def get_two_val():
x, y = num_input(), num_input()
return x, y
print("Welcome to Simple Calc")
# declaration of variables
num_of_calc_counter = 0
index_of_calc = 1
calculations = []
while True:
print("Choose from the following options:")
print(" 1. Add")
print(" 2. Subtract")
print(" 3. Multiply")
print(" 4. Divide")
print(" 5. Sales Tax Calculator")
print(" 6. Recent Calculations")
print(" 0. Quit")
usrChoice = num_input('Enter your choice: ')
'''
Menu workflow
options 1-4 take in two numbers and perform the specified calculation and
then add the result to a master list that the user can reference later.
lastly, the workflow increments the num_of_calc variable by 1 for recent
calc logic
option 5 is a simple tax calculator that needs work or option to enter
or find tax rate
option 6 returns a list of all the calculations perform by the user
'''
if usrChoice is 1:
numbers = get_two_val()
result = add(*numbers)
print(numbers[0], "plus", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 2:
numbers = get_two_val()
result = sub(*numbers)
print(numbers[0], "minus", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 3:
numbers = get_two_val()
result = mul(*numbers)
print(numbers[0], "times", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 4:
numbers = get_two_val()
result = div(*numbers)
print(numbers[0], "divided by", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 5:
tax_rate = .0875
price = float(input("What is the price?: "))
total_tax = tax_rate * price
final_amount = total_tax + price
print('Tax rate: ', tax_rate, '%')
print('Sales tax: $', total_tax)
print('_____________________________')
print('Final amount: $', final_amount)
#
elif usrChoice is 6:
if len(calculations) is 0:
print('There are no calculations')
elif num_of_calc_counter == 0:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter += 1
elif index_of_calc == num_of_calc_counter:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter += 1
elif num_of_calc_counter > index_of_calc:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter -= 1
elif num_of_calc_counter < index_of_calc:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter += 1
elif usrChoice is 0:
break
I don't know if you could find this simpler:
def num_input(prompt='Enter a number: '):
finished = False
while not finished:
string_input = input(prompt)
try:
input_translated = int(string_input)
except ValueError:
print('You must input a number. Try again.')
else:
finished = True
return input_translated
def division_operation(x, y):
if y == 0:
print('Value is not dividable by 0, try again')
return None
else:
return x / y
math_operations_values = [
(lambda x, y: x + y, 'plus'),
(lambda x, y: x - y, 'minus'),
(lambda x, y: x * y, 'times'),
(division_operation, 'divided by')
]
def get_two_val():
return (num_input(), num_input())
def operate_on_numbers(operation_index):
def operate():
numbers = get_two_val()
operator, operation_string = math_operations_values[operation_index]
result = operator(*numbers)
if result is not None:
print(numbers[0], operation_string, numbers[1], "equals", result)
calculations.append(result)
return operate
def tax_computation():
tax_rate = .0875
price = float(input("What is the price?: "))
total_tax = tax_rate * price
final_amount = total_tax + price
print('Tax rate: ', tax_rate * 100, '%')
print('Sales tax: $', total_tax)
print('_____________________________')
print('Final amount: $', final_amount)
def show_computations():
if calculations:
for (index, values) in enumerate(calculations, start=1):
print(f'{index}: {values}')
else:
print('There are no calculations')
calculations = []
finished = False
choices_actions = [
operate_on_numbers(0),
operate_on_numbers(1),
operate_on_numbers(2),
operate_on_numbers(3),
tax_computation,
show_computations
]
while not finished:
print("""
Choose from the following options:
1. Add
2. Subtract
3. Multiply
4. Divide
5. Sales Tax Calculator
6. Recent Calculations
0. Quit""")
user_choice = num_input('Enter your choice: ')
'''
Menu workflow
options 1-4 take in two numbers and perform the specified calculation and
then add the result to a master list that the user can reference later.
lastly, the workflow increments the num_of_calc variable by 1 for recent
calc logic
option 5 is a simple tax calculator that needs work or option to enter
or find tax rate
option 6 returns a list of all the calculations perform by the user
'''
if user_choice == 0:
finished = True
else:
try:
operation_to_do = choices_actions[user_choice - 1]
except IndexError:
print('Please enter one of choice shown.')
else:
operation_to_do()
I can't even explain. Here is my code
foods = {12345670 : 'orange(s)',
87654325 : 'pineapple(s)'}
loop = 10
while loop == 10:
full_list = input("Type: ")
if full_list == 'end':
break
amount = int(input("Amount: "))
subtotal = 0
item = int(full_list)
if item in foods:
print("That would be {} {}".format(amount, foods[item]))
if full_list == '12345670':
price = (0.50 * amount)
print("Added Orange(s)")
print("Added "+str(price))
subtotal = subtotal + price
if full_list == '87654325':
price = (1.00 * amount)
subtotal = subtotal + price
print("Added Pineapple(s)")
print("Added "+str(price))
print("Your subtotal is " +str(subtotal))
I'm trying to get my subtotal to change accordingly to what the user purchases, I haven't finished making my list of purchasable items and so I don't want to change the name of the variable every time. What is the problem here? Why doesn't the variable subtotal change?
foods = {12345670 : 'orange(s)',
87654325 : 'pineapple(s)'}
loop = 10
subtotal = 0 # <------ moved it outside of the while loop
while loop == 10:
full_list = input("Type: ")
if full_list == 'end':
break
amount = int(input("Amount: "))
item = int(full_list)
if item in foods:
print("That would be {} {}".format(amount, foods[item]))
if full_list == '12345670':
price = (0.50 * amount)
print("Added Orange(s)")
print("Added "+str(price))
subtotal = subtotal + price
if full_list == '87654325': #should be an elif not an if
price = (1.00 * amount)
subtotal = subtotal + price
print("Added Pineapple(s)")
print("Added "+str(price))
print("Your subtotal is " +str(subtotal))
Every time you looped you restarted the total cost to 0 and it only kept the latest price. Move it outside of the while loop where I commented and you should be fine. Also use elif if you want to chain similar if statements together.
You have the following
if full_list == '12345670'
But it will never enter this if statement because your input type is an integer not a string. Do this without the single quotes instead:
if full_list == 12345670
Hi having trouble trying to fix an error that occurs when I put just a '#' or rogue value in case someone doesn't want to add any data. I don't know how to fix it and I'm hoping to just end the code just like I would with data.
#Gets Data Input
def getData():
fullList = []
inputText = checkInput("Enter the students first name, last name, first mark, and second mark (# to exit): ")
while inputText != "#":
nameList = []
nameList2 = []
nameList = inputText.split()
nameList2.extend((nameList[0],nameList[1]))
nameList2.append((float(nameList[2]) + float(nameList [3]))/2)
fullList.append(nameList2)
inputText = checkInput("Enter the students first name, last name, first mark, and second mark (# to exit): ")
print("\n")
return fullList
#Calculates Group Average
def calc1(fullList):
total = 0
for x in fullList:
total = total + x[2]
groupAverage = total/(len(fullList))
return(groupAverage)
#Finds Highest Average
def calc2(fullList):
HighestAverage = 0
nameHighAverage = ""
for x in fullList:
if x[2] > HighestAverage:
HighestAverage = x[2]
nameHighAverage = x[0] + " " + x[1]
return (HighestAverage, nameHighAverage)
#Returns Marks above average
def results1(groupAverage,r1FullList):
r1FullList.sort()
print("List of students with their final mark above the group average")
print("--------------------------------------------------------------")
print("{:<20} {:<12}".format("Name","Mark"))
for x in r1FullList:
if x[2] > groupAverage:
name = x[0] + " " + x[1]
print("{:<20} {:<12.2f}".format(name,x[2]))
def calc3(x):
if x[2] >= 80:
return 'A'
elif x[2] >= 65:
return 'B'
elif x[2] >= 50:
return 'C'
elif x[2] < 50:
return 'D'
else:
return 'ERROR'
def results2(fullList):
print("List of Studens with their Final Marks and Grades")
print("-------------------------------------------------")
print("{:<20} {:<12} {:<12}".format("Name","Mark","Grade"))
for x in fullList:
grade = calc3(x)
name = x[0] + " " + x[1]
print("{:<20} {:<12.2f} {:<12}".format(name,x[2],grade))
#Checks for boundary and invalid data
def checkInput(question):
while True:
textInput = input(question)
if textInput == "#":
return textInput
splitList = textInput.split()
if len(splitList) !=4:
print("Invalid Format, Please Try Again")
continue
try:
a = float(splitList[2])
a = float(splitList[3])
if float(splitList[2]) < 0 or float(splitList[2]) > 100:
print("Invalid Format, Please Try Again")
continue
if float(splitList[3]) < 0 or float(splitList[3]) > 100:
print("Invalid Format, Please Try Again")
continue
return(textInput)
except ValueError:
print("Invalid Input, Please Try Again")
continue
#Main Program
#Input Data
fullList = getData()
#Process Data
groupAverage = calc1(fullList)
HighestAverage, nameHighAverage = calc2(fullList)
#Display Results
print("The group average was %.2f" % groupAverage)
print("The student with the highest mark was: %s %0.2f" %(nameHighAverage,HighestAverage))
results1(groupAverage,fullList)
print("\n")
results2(fullList)
Your program works OK for me, unless you enter a # as the first entry, in which case fullList is [] and has length 0. Hence, DivisionByZero at this line: groupAverage = total/(len(fullList)).
You could modify your code to check for this and exit:
import sys
fullList = getData()
if not fullList:
print('No Data!')
sys.exit()