Nested loop code error free, not executing - python

I have this code and it doesn't run at all. It is a list of objects, and each object has a two dimensional list in it. It is not executing the code to even display just the flightNo element. I've made a method to display the 2d list in the object, but nothing happens. I tested with a simple print('Hello') at the end and that does work. Can someone tell me what could be wrong here?
EDIT: Full code at: https://onlinegdb.com/HJPqXWXWU
elif a == 3:
for i in range(len(FlightList)):
print(FlightList[i].flightNo)
req = input('Enter flight number to buy tickets: ')
for Flight in FlightList:
if Flight.flightNo == req:
for a in range(len(Flight.seats)):
for b in range(len(Flight.seats[a])):
print(Flight.seats[a][b], end=" ")
print()
qty = int(input('Enter number of tickets'))
Flight.buyTicket(one, qty)
print("Hello")
I have also tried a different method to display flightNo, no execution again:
for Flight in FlightList:
print(Flight.flightNo)
re4 = input('Enter flight number to view seats: ')
for i in FlightList:
if i.flightNo == re4:
for a in range(len(i.seats)):
for b in range(len(i.seats[a])):
print(i.seats[a][b], end=" ")
print()

Here is the working code that I modified the location of calling the method and assigning to the variable because every time we have to create a new instance of the class to save data properly and we should not clear the list that's why I changed the position outside of the loop. And this I working properly. for my basic testing. I can improve if you need. and kept your code in the comment's so you can see the change.
import sys
class Flight:
def __init__(self):
self.flightNo = "None"
self.planeType = "None"
self.destination = "None"
self.w = self.h = 0
self.seats = [["None" for x in range(self.w)] for y in range(self.h)]
self.depDate = "None"
self.depTime = "None"
self.eta = "None"
self.ticketsSold = 0
self.pricePerTicket = 0.0
def displayDetails(self):
print('Flight No: ', self.flightNo,
'\nPlane Type: ', self.planeType,
'\nDestination: ', self.destination,
'\nDeparture Date: ', self.depDate,
'\nDeparture Time: ', self.depTime,
'\nETA: ', self.eta,
'\nTickets Sold: ', self.ticketsSold,
'\nPrice: ', self.pricePerTicket, '\n\n')
def totalSales(self):
return print("Total number of tickets sold: ", self.ticketsSold,
"\nTotal sales: ", (self.ticketsSold * self.pricePerTicket))
def buyTicket(self, quantity):
quantity = int(input("Enter number of tickets required: "))
cost = quantity * self.pricePerTicket
for v in range(len(self.seats)):
for j in range(len(self.seats[v])):
if quantity > len(self.seats) * len(self.seats[v]):
print("Lessen the number of tickets")
break
if self.seats[v][j] == "\\__/":
self.seats[v][j] = "\\AA/"
quantity -= 1
if quantity == 0:
break
if quantity == 0:
break
print(quantity, "tickets bought for $", cost,
"\nSeats assigned", )
self.ticketsSold += quantity
# one = Flight()
ans = True
FlightList = []
while ans:
print("----------------------------- \n1. Add a flight \n2. Remove a flight \n3. Sell Tickets",
"\n4. Display seat info \n5. Display total sales for flight \n6. Display flight info",
"\n7. Display all flight's info \n0. Quit")
a = int(input("Enter number: "))
#FlightList = []
if a == 1:
one = Flight()
one.flightNo = input('Enter flight number: ')
one.planeType = input('Enter plane type: ')
one.destination = input('Enter destination: ')
one.w = int(input('Enter number of columns in flight: '))
one.h = int(input('Enter number of rows in flight: '))
one.seats = [["\\__/" for x in range(one.w)]
for y in range(one.h)]
one.depDate = input('Enter departure date: ')
one.depTime = input('Enter departure time: ')
one.eta = input('Enter ETA: ')
one.ticketsSold = int(input('Enter number of tickets sold: '))
one.pricePerTicket = float(input('Price: '))
FlightList.append(one)
elif a == 2:
rem = input('Enter flight number to remove: ')
for i in FlightList:
if i.flightNo == rem:
del FlightList[FlightList.index(i)]
elif a == 3:
for i in range(len(FlightList)):
print(FlightList[i].flightNo)
req = input('Enter flight number to buy tickets: ')
for Flight in FlightList:
if Flight.flightNo == req:
for a in range(len(Flight.seats)):
for b in range(len(Flight.seats[a])):
print(Flight.seats[a][b], end=" ")
print()
qty = int(input('Enter number of tickets'))
Flight.buyTicket(one, qty)
print("Hello")
elif a == 4:
for Flight in FlightList:
print(Flight.flightNo)
re4 = input('Enter flight number to view seats: ')
for i in FlightList:
if i.flightNo == re4:
for a in range(len(i.seats)):
for b in range(len(i.seats[a])):
print(i.seats[a][b], end=" ")
print()
elif a == 5:
re4 = input('Enter flight number to view seats: ')
for i in FlightList:
if i.flightNo == re4:
i.totalSales()
elif a == 6:
re4 = input('Enter flight number to view seats: ')
for i in FlightList:
if i.flightNo == re4:
i.displayDetails()
elif a == 7:
for item in FlightList:
item.displayDetails()
elif a == 0:
sys.exit(0)

Related

If a user checks out 5 copies of book1 and returns 3 returns 2 and then returns 1 more it allows it even if it exceeds the original amount of copies

if you choose to return a book at the start of the program, without checking out any books,
then it won't allow the return (intended). So say the user wants to check out 5/10 copies of
book1. It checks them out and subtracts them from the copies on shelf. They choose to return
3 one day, and 2 another day. (For testing purposes) the day after that, they return another
copy of book1, which is more than they checked out. It appends it to the book1.borrow aka
num of copies. It should not allow the user to return more copies than the original numbr of copies. So this is what I have in my main module. I can add the class LibraryBook if
needed.
from LibraryBook import *
book1 = LibraryBook()
book1.title = "not set"
book1.year = "no se"
book1.author = "set not"
book1.borrow = 10
book2 = LibraryBook()
book2.title = "tes ton"
book2.year = "es on"
book2.author = "ton tes"
book2.borrow = 8
selection = 0
amount = 0
amount1 = 0
while selection != 5:
print("Select an option")
print('1 - Borrow a book')
print('2 - Return a book')
print('3 - See info on available books')
print('4 - Exit')
print()
selection = int(input("What would you like to do? "))
print()
if selection == 1:
print("Book 1 is: ", book1.title)
print("Book 2 is: ", book2.title)
print()
bookNum = int(input("Enter the book number. "))
print()
if bookNum == 1:
print()
amount = int(input("Enter the number of copies you would like to check out. "))
print()
if (amount <= book1.borrow) and (amount > 0):
book1.borrowed(amount)
else:
print("We only have", book1.borrow, "copies available.")
print()
elif bookNum == 2:
print()
amount = int(input("Enter the number of copies you would like to check out. "))
print()
if (amount <= book2.borrow) and (amount > 0):
book2.borrowed(amount)
else:
print("We only have", book2.borrow, "copies available.")
print()
else:
print()
print("That book is not here. Enter 1 or 2. ")
print()
if selection == 2:
print("Book 1 is: ", book1.title)
print("Book 2 is: ", book2.title)
print()
bookNum = int(input("Which book would you like to return? "))
print()
if bookNum == 1:
print()
amount1 = int(input("Enter the amount of copies you would like to return. "))
print()
if amount1 <= amount:
book1.returned(amount1)
print()
elif book1.borrow == book1.borrow:
print("Invalid number of copies. Count the books and try again ")
print()
else:
print("You only checked out", amount)
print()
elif bookNum == 2:
print()
amount1 = int(input("Enter the amount of copies you would like to return. "))
print()
if amount1 <= amount:
book2.returned(amount1)
print()
elif book2.borrow == book2.borrow:
print("You did not check out this book.")
print()
else:
print("You only checked out", amount)
print()
else:
print("Invalid selection. Choose book 1 or book 2.")
print()
if selection == 3:
print()
print("Book 1:")
print(book1.__str__())
print()
print("Book 2:")
print(book2.__str__())
print()
if (selection <= 0) or (selection >= 5):
print("Invalid selection. Enter a number 1-4. ")
print()
if selection == 4:
break
I'm not the best programmer but I think I made and example here
Ofc is not the best I made it larger for you to understand, there are some bugs like when asked for book if u give bigger then 2 will break but I let you fix it ;D
import sys, os, time, re
class LibraryBook(object):
def __init__(self, title, year, author, borrow):
self.title = title
self.year = year
self.author = author
self.borrow = borrow
def borrow_add(self, amount: int):
self.borrow += amount
def left(self):
return self.borrow
def get_title(self):
return self.title
def borrow_sell(self, amount: int):
self.borrow -= amount
def get_book_info(self):
val = f'''
Book Title: {self.title}
Book Year: {self.year}
Book Author: {self.author}
Left in stock: {self.borrow}
'''
return val
book1 = LibraryBook('Prison Break', 2016, 'My House', 8)
book2 = LibraryBook('Hello', 1999, 'NO one', 10)
###########
#That is so you can do book3,4,5 etc.. without write in print all books on hand ;D
books = re.findall('book.', (str(globals().copy())).replace("'", ''))
books_titles = [eval(f'{o}.get_title()') for o in books]
##########
user_lib =[]
#You can use that in a function (def) and call it when you need it
while True:
os.system('cls')
option = int(input('''
Select an option
1 - Borrow a book
2 - Return a book
3 - See info on available books
4 - See my lib
5 - Exit
>>> '''))
if option == 1:
option_2 = input("\n".join(f"Book{o+1}:{i}" for o, i in enumerate(books_titles))+'\nWhat book(ex: 1):')
option_3 = int(input('How much?: '))
if int(eval(f'book{option_2}.left()'))-option_3 >= 0:
if x:=list(filter(lambda book: book['name'] == eval(f'book{option_2}.title'), user_lib)):
user_lib[user_lib.index(x[0])]['amount'] +=option_3
else:
user_lib.append({'name': eval(f'book{option_2}.get_title()'), 'amount': option_3})
print(f'You borrowed {option_3} books')
eval(f'book{option_2}.borrow_sell({option_3})') #Remove from store
else:
print(f'We have {eval(f"book{option_2}.left()")} books left...')
time.sleep(1) # wait 1 second for user to read then reset
elif option == 2:
option_2 = input("\n".join(f"Book{o+1}:{i}" for o, i in enumerate(books_titles))+'\nWhat book(ex: 1):')
if len(x:=list(filter(lambda book: book['name'] == eval(f'book{option_2}.get_title()'), user_lib))) > 0:
option_3 = int(input('How much?: '))
if user_lib[pos:=user_lib.index(x[0])]['amount'] -option_3 >= 0:
user_lib[pos]['amount'] -= option_3
if user_lib[pos]['amount'] == 0:
user_lib.pop(pos)
print(f'You returned {option_3} books')
eval(f'book{option_2}.borrow_add({option_3})') # Add them back to shop
else:
print(f"You don't have enogh books, you have only: {x[0]['amount']}")
time.sleep(1) # wait 1 second for user to read then reset
else:
print("You don't any books of thta kind")
time.sleep(1)
elif option == 3:
option_2 = input("\n".join(f"Book{o+1}:{i}" for o, i in enumerate(books_titles))+'\nWhat book(ex: 1):')
print(eval(f'book{option_2}.get_book_info()'))
input('Press enter to continue...')
elif option == 4:
print("\n".join(f"Book Name:{user_lib[o]['name']}\nAmount I have:{user_lib[o]['amount']}" for o, i in enumerate(user_lib)) if user_lib != [] else "You don't have any books")
elif option == 5:
sys.exit(1)
else:
print('Invalid number')
time.sleep(1) # wait 1 second for user to read then reset

Is there a loop that will calculate the better value of an unlimited amount of products?

So currently, I am aiming to create a code that helps customers at shops, find which product has better value.
However, the code should be as simple, short and elegant as possible. And that's a bit of a problem for me.
I am supposed to have a code that can calculate the value of an unlimited amount of products, but I don't know how to do that, so that's why I had to do everything manually, and could only create a code that calculates the better value of up to 10 products only.
Could I receive any tips maybe?
products = int(input("How many products are there? "))
if products > 10:
print("This code can only take up to 10 product sizes.")
print("Please enter only up to 10 product sizes below.")
if products <= 1:
print("You must enter at least two product sizes to compare.")
if products >= 1:
cost1 = float(input("Cost of first product($): "))
mass1 = float(input("Mass of first product(g): "))
ans1 = cost1/mass1
a = ans1
ans2 = ""
ans3 = ""
ans4 = ""
ans5 = ""
ans6 = ""
ans7 = ""
ans8 = ""
ans9 = ""
ans10 = ""
if products >= 2:
cost2 = float(input("Cost of second product($): "))
mass2 = float(input("Mass of second product(g): "))
ans2 = cost2/mass2
if a > ans2:
a = ans2
if products >= 3:
cost3 = float(input("Cost of third product($): "))
mass3 = float(input("Mass of third product(g): "))
ans3 = cost3/mass3
if a > ans3:
a = ans3
ans4 = ""
ans5 = ""
ans6 = ""
ans7 = ""
ans8 = ""
ans9 = ""
ans10 = ""
if products >= 4:
cost4 = float(input("Cost of fourth product($): "))
mass4 = float(input("Mass of fourth product(g): "))
ans4 = cost4/mass4
if a > ans4:
a = ans4
ans5 = ""
ans6 = ""
ans7 = ""
ans8 = ""
ans9 = ""
ans10 = ""
if products >= 5:
cost5 = float(input("Cost of fifth product($): "))
mass5 = float(input("Mass of fifth product(g): "))
ans5 = cost5/mass5
if a > ans5:
a = ans5
ans6 = ""
ans7 = ""
ans8 = ""
ans9 = ""
ans10 = ""
if products >= 6:
cost6 = float(input("Cost of sixth product($): "))
mass6 = float(input("Mass of sixth product(g): "))
ans6 = cost6/mass6
if a > ans6:
a = ans6
ans7 = ""
ans8 = ""
ans9 = ""
ans10 = ""
if products >= 7:
cost7 = float(input("Cost of seventh product($): "))
mass7 = float(input("Mass of seventh product(g): "))
ans7 = cost7/mass7
if a > ans7:
a = ans7
ans8 = ""
ans9 = ""
ans10 = ""
if products >= 8:
cost8 = float(input("Cost of eighth product($): "))
mass8 = float(input("Mass of eighth product(g): "))
ans8 = cost8/mass8
if a > ans8:
a = ans8
ans9 = ""
ans10 = ""
if products >= 9:
cost9 = float(input("Cost of ninth product($): "))
mass9 = float(input("Mass of ninth product(g): "))
ans9 = cost9/mass9
if a > ans9:
a = ans9
ans10 = ""
if products >= 10:
cost10 = float(input("Cost of tenth product($): "))
mass10 = float(input("Mass of tenth product(g): "))
ans10 = cost10/mass10
if a > ans10:
a = ans10
if products >= 1:
print("The product(s) with the best value is/are the below product number(s):")
if ans1 == a:
print(1)
if ans2 == a:
print(2)
if ans3 == a:
print(3)
if ans4 == a:
print(4)
if ans5 == a:
print(5)
if ans6 == a:
print(6)
if ans7 == a:
print(7)
if ans8 == a:
print(8)
if ans9 == a:
print(9)
if ans10 == a:
print(10)
print("The cost per gram is ${}/g".format(a))
Here's a way you can do it. You should study the standard data types and standard operations intensively and enough examples of use.
# This list stores products as tuples (cost, mass)
# Just add tuples if you want to have more products
products = [(2.0, 300), (1.7, 250), (3.8, 480), (1.9, 225)]
best = None
# Use a for loop to iterate over the products
for product in products:
# unpack the tuple
cost, mass = product
# calculate the ratio
ratio = float(cost/mass)
# see if its better than the best
# 'not best' just checks for the case that best == None
if not best or ratio > float(best[0]/best[1]):
best = product
print("The best product is: {0}".format(best))
first off think about looping. for loops, while loops, etc
count = -1
while count < 0:
try:
count = int(input("How many products are there? "))
except ValueError:
# meaningful error for invalid options, # catches non integer values
print(" Please try again: inputs must be a positive integers")
continue
if count < 0:
print(" Please try again: inputs must be a positive integers")
once you capture how many products you want. you need to loop to gather all the cost and mass values for a product and store it into something that can easily be accessed.
This makes me think of an array.
products = []
now loop over and capture the data values for cost and mass
# loop over to capture data
for i in range(0,count):
# again loop for positive values
cost = -1
while cost < 0:
try:
cost = float(input("How much does product "+str(i+1)+" cost? "))
except ValueError:
# meaningful error for invalid options, # catches non integer values
print(" Please try again: inputs must be a positive float")
continue
if cost < 0:
print(" Please try again: inputs must be a positive float")
mass = -1
while mass < 0:
try:
mass = float(input("How much does product "+str(i+1)+" weight? "))
except ValueError:
# meaningful error for invalid options, # catches non integer values
print(" Please try again: inputs must be a positive float")
continue
if mass < 0:
print(" Please try again: inputs must be a positive float")
# append to cost and mass into the products array as an array of to values
products.append([cost,mass])
# test the output
print(products
This should be a good enough jumping off point. Now you have captured all the data for any amount of products, you can access it later.
print(products[3])
if this is something you looking for,
def best_cost():
while True:
num_of_products = int(input('enter no.of products:'))
if num_of_products < 1:
print('enter valid number for number of products')
else:
print(f'finding best value out of {num_of_products} products')
all_prices = []
for i in range(1, num_of_products+1):
cost = float(input(f'enter cost of prod {i} in $:'))
mass = float(input(f'enter mass of prod {i} in grms:'))
print(f'cost of product {i} for {mass}grms is {cost}$')
price = cost/mass
all_prices.append(price)
for prod in all_prices:
if prod == min(all_prices):
best_prod = all_prices.index(prod)+1
return f'best product is {best_prod}'
best_cost()
you need more practice.

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.

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: Unknown Syntax Error (easy)

I'm getting a syntax error around the word rental and I just have no clue what I've done wrong. This is like my 6th program. Any and all suggestions are helpful.
#Computes Cable Bill
print("Welcome to cable customer billing calculator")
acct = int(input("Enter an account number"))
cust_type = input("Enter customer type: (R) Residential or (B) Business: ")
def residential():
processing = 4.50
basic_service = 20.50
daily_rental = 2.99
prem_channel_fee = 7.50
prem_channels = int(input("Enter the number of premium channels used: ")
rental = int(input("Were movies rented (Y or N): ")
if rental == Y or y:
rental_days = int(input("Enter the total number of rental days (one day for each movie, each day): ")
else:
rental_days = 0
bill_amt = processing + basic_service + (rental_days * daily_rental) + (prem_channels * prem_channel_fee)
return (bill_amt)
def business():
processing = 15
basic_service = 75
prem_channel_fee = 50
connections = int(input("Enter the number of basic service connections: ")
prem_channels = int(input("Enter the number of premium channels used: ")
if (connections <= 10):
bill_amt = processing + basic_service + (prem_channel * prem_channel_fee)
else:
bill_amt = processing + basic_service + ((connections - 10) * 5) + (prem_channel * prem_channel_fee)
return (bill_amt)
if (cust_type == "R" or "r"):
bill_total = residential()
else:
bill_total = business()
print("Account number: ", acct)
print("Amount due: ",bill_total)
You need to add closing parentheses as depicted in the snippet below and ensure that the first line of your conditionals line up with the previous line. Also, consider matching the value of rental against a list of valid responses – it's more Pythonic way of writing the logic you're proposing:
prem_channels = int(input("Enter the number of premium channels used: "))
rental = int(input("Were movies rented (Y or N): "))
if rental in ['Y', 'y']:
rental_days = input("Enter the total number of rental days (one day for each movie, each day): ")
Similarly, the following lines need closing parentheses:
connections = int(input("Enter the number of basic service connections: "))
prem_channels = int(input("Enter the number of premium channels used: "))
Replace the logic of your final conditional as above:
if (cust_type in ["R", "r"]):
Or, alternatively (but less Pythonic):
if (cust_type == "R" or cust_type == "r"):
Finally, note that input("Were movies rented (Y or N): ") returns a string and thus should not be cast to an integer. If you cast it using int(), you'll receive a type error and if rental in ['Y', 'y']: will never evaluate to true.
if rental == 'Y' or rental == 'y':
Should solve this
Following should help you.
rental = str(input("Were movies rented (Y or N): "))
if rental == "Y" or rental == "y":
Points raised by zeantsoi are also valid. Please consider them too.
There are a number of errors:
prem_channels = int(input("Enter the number of premium channels used: ") needs closing parenthesis.
rental = int(input("Were movies rented (Y or N): ") remove int(. The input is a string.
if rental == Y or y: should be if rental == 'Y' or rental == 'y':.
The whole if rental block needs unindented to line up with the previous line.
The two lines below need trailing ):
connections = int(input("Enter the number of basic service connections: ")
prem_channels = int(input("Enter the number of premium channels used: ")
The if (connections block needs unindented to line up with the previous line.
if (cust_type == "R" or "r"): should be if cust_type == 'R' or cust_type == 'r':
The bill_amt calculations both need to use prem_channels not prem_channel.
In addition, parentheses around if statements and return values are unnecessary.
Here's your code with the above fixes:
#Computes Cable Bill
print("Welcome to cable customer billing calculator")
acct = int(input("Enter an account number"))
cust_type = input("Enter customer type: (R) Residential or (B) Business: ")
def residential():
processing = 4.50
basic_service = 20.50
daily_rental = 2.99
prem_channel_fee = 7.50
prem_channels = int(input("Enter the number of premium channels used: "))
rental = input("Were movies rented (Y or N): ")
if rental == 'Y' or rental == 'y':
rental_days = int(input("Enter the total number of rental days (one day for each movie, each day): "))
else:
rental_days = 0
bill_amt = processing + basic_service + (rental_days * daily_rental) + (prem_channels * prem_channel_fee)
return bill_amt
def business():
processing = 15
basic_service = 75
prem_channel_fee = 50
connections = int(input("Enter the number of basic service connections: "))
prem_channels = int(input("Enter the number of premium channels used: "))
if connections <= 10:
bill_amt = processing + basic_service + (prem_channels * prem_channel_fee)
else:
bill_amt = processing + basic_service + ((connections - 10) * 5) + (prem_channels * prem_channel_fee)
return bill_amt
if cust_type == "R" or cust_type == "r":
bill_total = residential()
else:
bill_total = business()
print("Account number: ", acct)
print("Amount due: ",bill_total)

Categories