Python: Unknown Syntax Error (easy) - python

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)

Related

How to get the code to display amount of the discount & the total amount of the purchase after the discount & including the giftwrapping if needed

baseballs cost $1.99 each
Develop a Python program that prompts the user to enter the number of baseballs purchased
In addition the program should ask the user if they want giftwrapping and if so add another $2.00 to the order.
I simply want my output to prompt the amount of the discount
(if any) and the total amount of the purchase after the discount and
including the giftwrapping if needed. But I don't know what code is needed to display that output? so I need someone to show me what code it is?
Quantity Discount
0 - 9 0%
10 - 50 5%
51 or more 10%
baseballs = int(input("Enter the number of baseballs purchased: "))
if(baseballs>0):
if baseballs<=9:
disc = baseballs*0.00
elif baseballs<=50:
disc = baseballs*0.05
elif baseballs>=51:
disc=baseballs*0.10
print("Discount : ",disc)
gift_wrapping = input("Do you want gift wrapping?: ")
print(baseballs + " " + "baseballs purchased" )
print(gift_wrapping)
Something like this maybe? Not 100% sure what you're asking:
Do let me know if you want comments on the code.
price = 1.99
baseballs = int(input("Enter the number of baseballs purchased: "))
if(baseballs>0):
if 0 <= baseballs <= 9:
disc = baseballs*0.00
elif 9 <= baseballs <= 50:
disc = baseballs*0.05
elif baseballs <= 51:
disc=baseballs*0.10
print("Discount : ",disc)
gift_wrapping = input("Do you want gift wrapping?: ")
if gift_wrapping == "yes" or "y" or "Yes":
total = (baseballs * price) - disc + 2
else:
total = (baseballs * price) - disc
print(str(baseballs) + " " + "baseballs purchased" )
if disc != 0:
total_disc = total-(baseballs*price)
print("Discount: "+str(total_disc))
print("Total price "+str(total))

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

Nested loop code error free, not executing

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)

How do format my output to 2 decimal places in Python?

I'm trying to format my output into 2 decimal places in Python..This is my code
def introduction():
print("This calculator calculates either the Simple or Compound interest of an given amount")
print("Please enter the values for principal, annual percentage, number of years, and number of times compounded per year")
print("With this information, we can provide the Simple or Compound interest as well as your future amount")
def validateInput(principal, annualPercntageRate, numberOfYears,userCompound):
if principal < 100.00:
valid = False
elif annualPercntageRate < 0.001 or annualPercntageRate > .15:
valid = False
elif numberOfYears < 1:
valid = False
elif userCompound != 1 and userCompound != 2 and userCompound != 4 and userCompound != 6 and userCompound != 12:
valid = False
else:
valid = True
return valid
def simpleInterest(principal, annualPercentageRate, numberOfYears):
return (principal * annualPercentageRate * numberOfYears)
def compoundInterest(principal, annualPercentageRate, numberOfYears, userCompound):
return principal * ((1 + (annualPercentageRate / userCompound))**(numberOfYears * userCompound) - 1)
def outputAmounts(principal, annualPercentageRate, numberOfYears, userCompound, simpleAmount,compoundAmount):
print("Simple interest earned in", numberOfYears, "will be $",simpleAmount,"making your future amount $",(principal + simpleAmount)
print("Interest compounded", userCompound, "in",numberOfYears, "will earn $",compoundAmount,"making your future amount",(principal + compoundAmount)
def main():
introduction()
principal = float(input("Enter principal: "))
annualPercentageRate = float(input("Enter rate: "))
numberOfYears = int(input("Enter years: "))
userCompound = int(input("Enter compounding periods: "))
if validateInput(principal, annualPercentageRate, numberOfYears, userCompound):
simpleAmount = simpleInterest(principal, annualPercentageRate, numberOfYears)
compoundAmount = compoundInterest(principal, annualPercentageRate, numberOfYears, userCompound)
outputAmounts(principal, annualPercentageRate, numberOfYears, userCompound, simpleAmount,compoundAmount)
else:
print("Error with input, try again")
main()
So for my output, I want to format the ending to 2 decimal places. Namely, these 2 variables
-(principal + compoundAmount)
-(principal + simpleAmount)
I know I need to use %.2, but Im not sure how to add that into a print statement so that it would output into 2 decimal places...How do I do this?
try this
print('pi is {:.2f}'.format(your_variable))
You just need simple formatting string, like:
print('pi is %.2f' % 3.14159)
which output is pi is 3.14
You might wanna read https://docs.python.org/2.7/library/string.html#formatspec

Python print out float or integer

How can i print out float if the result have decimal or print out integer if the result have no decimal?
c = input("Enter the total cost of purchase: ")
bank = raw_input("Enter the bank of your credit card (DBS, OCBC, etc.): ")
dbs1 = ((c/float(100))*10)
dbs2 = c-dbs1
ocbc1 = ((c/float(100))*15)
ocbc2 = c-ocbc1
if (c > 200):
if (bank == 'DBS'):
print('Please pay $'+str(dbs2))
elif (bank == 'OCBC'):
print('Please pay $'+str(ocbc2))
else:
print('Please pay $'+str(c))
else:
print('Please pay $'+str(c))
exit = raw_input("Enter to exit")
Example-Result
Enter the total cost of purchase: 250
Enter the bank of your credit card (DBS, OCBC, etc.): OCBC
Please pay $212.5
Enter the total cost of purchase: 250
Enter the bank of your credit card (DBS, OCBC, etc.): DBS
Please pay $225.0
You can try this, which simply uses Python's string formatting method:
if int(c) == float(c):
decimals = 0
else:
decimals = 2 # Assumes 2 decimal places for money
print('Please pay: ${0:.{1}f}'.format(c, decimals))
This will give you the following output if c == 1.00:
Please pay: $1
Or this output if c == 20.56:
Please pay: $20.56
Python floats have a built-in method to determine whether they're an integer:
x = 212.50
y = 212.0
f = lambda x: int(x) if x.is_integer() else x
print(x, f(x), y, f(y), sep='\t')
>> 212.5 212.5 212.0 212
Since there is a much simpler way now and this post is the first result, people should now about it:
print(f"{3.0:g}") # 3
print(f"{3.14:g}") # 3.14
def nice_print(i):
print '%.2f' % i if i - int(i) != 0 else '%d' % i
nice_print(44)
44
nice_print(44.345)
44.34
in Your code:
def nice_number(i):
return '%.2f' % i if i - int(i) != 0 else '%d' % i
c = input("Enter the total cost of purchase: ")
bank = raw_input("Enter the bank of your credit card (DBS, OCBC, etc.): ")
dbs1 = ((c/float(100))*10)
dbs2 = c-dbs1
ocbc1 = ((c/float(100))*15)
ocbc2 = c-ocbc1
if (c > 200):
if (bank == 'DBS'):
print('Please pay $'+nice_number(dbs2))
elif (bank == 'OCBC'):
print('Please pay $'+nice_number(ocbc2))
else:
print('Please pay $'+nice_number(c))
else:
print('Please pay $'+nice_number(c))

Categories