I am solving the following problem, and came across the situation where I'm unable to define either decision operators or the while loop properly.
The task:
Customers get a monthly discount depending on the length of contract they take out as shown below:
3 – 6 months 2% discount
7 – 12 months 5% discount
over 12 months 10% discount
The program should ask users for their name and the monthly cost of their game package. It should then ask them to enter the contract length they would like. The maximum contract length is 18 months. The program should finally display the entered details and the final cost of the package with the discount applied.
contract_length = 0
final_cost = 0
#prompt the user to enter their name
user_name = input("What is your name? ")
#prompt the user to enter monthly cost for the game package
package_cost = float(input("Monthly cost of your game package: "))
while contract_length > 0 and contract_length <= 18:
#prompt the user to enter the contract length
contract_length = int(input("Enter the contract length you would like: "))
#selection statement to calculate final cost
if contract_length > 12:
discount = (package_cost * 0.1)
final_cost = format(package_cost - discount,".2f")
elif contract_length > 6:
discount = (package_cost * 0.05)
final_cost = format(package_cost - discount, ".2f")
elif contract_length >= 3:
discount = (package_cost * 0.02)
final_cost = format(package_cost - discount, ".2f")
else:
print("Invalid entry")
#display results
print("Name " +user_name)
print("Package Cost £",str(package_cost))
print("Months in Contract " , str(contract_length))
print("The final cost is £",str(final_cost))
Error I am having
What is your name? Jhon
Monthly cost of your game package: 35.12
Name Jhon
Package Cost £ 35.12
Months in Contract 0
The final cost is £ 0
>>>
I even tried "and" to "or" but with or operator it's start repeating the input function under while loop. Any help? Thanks.
I would recommend you to have a condition on the final_cost, like this:
contract_length = 0
final_cost = 'none'
#...
while final_cost == 'none':
#prompt the user to enter the contract length
contract_length = int(input("Enter the contract length you would like: "))
if contract_length > 18:
print("Invalid entry")
continue
#selection statement to calculate final cost
if contract_length > 12:
discount = (package_cost * 0.1)
final_cost = format(package_cost - discount,".2f")
elif contract_length > 6:
discount = (package_cost * 0.05)
final_cost = format(package_cost - discount, ".2f")
elif contract_length >= 3:
discount = (package_cost * 0.02)
final_cost = format(package_cost - discount, ".2f")
else:
print("Invalid entry")
Here is another solution:
contract_length = 0
final_cost = 0
package_cost = 0
user_name = None
while not user_name:
user_name = input("What is your name? ")
while package_cost <= 0:
package_cost = input("Monthly cost of your game package: ")
if not package_cost.isdigit():
package_cost = 0
package_cost = float(package_cost)
while not (3 <= contract_length <= 18):
contract_length = input("Enter the contract length you would like: ")
if not contract_length.isdigit():
contract_length = 0
contract_length = int(contract_length)
if contract_length > 12:
discount = 0.1
elif contract_length > 6:
discount = 0.05
elif contract_length >= 3:
discount = 0.02
else:
discount = 0
final_cost = package_cost - (package_cost * discount)
print("Name", user_name)
print("Package Cost £", format(package_cost, ".2f"))
print("Months in Contract", contract_length)
print("The final cost is £", format(final_cost, ".2f"))
Related
I am currently working on improving my commission program by implementing arrays into my program. However, I cannot properly display my commission results anymore. If I revert some array changes, I can display my commission fine. Can someone show me where I did wrong? I would appreciate any feedback on my code to the problem posted below. I'm a beginner and have only included code that I have learned up to this point
MAX = 10
def main():
comp_name = [""] * MAX
sales_amount = [0.0] * MAX
total_sales_amount = 0.0
commission = 0.0
bonus = 0.0
more_sales = 'Y'
select_item = 0
welcome_message()
while more_sales == 'Y':
comp_name[select_item] = get_comp_name()
sales_amount[select_item] = get_sales_amount()
total_sales_amount = total_sales_amount + (sales_amount[select_item] + sales_amount[select_item])
more_sales = more_sales_input()
select_item = select_item + 1
commission += get_commission_calc(sales_amount)
print_receipt(comp_name, sales_amount, select_item)
bonus = get_bonus(commission)
commission = commission + bonus
print_totals(bonus, commission)
def welcome_message():
print("Welcome to your commission calculator (v3)!")
def print_receipt(comp_name, sales_amount, select_item):
sub_total = 0
count = 0
print("\nCompany Name Unit Price Total Price")
print("------------ ---------- -----------")
while count < num_items:
print("{0:<15}".format(comp_name[count]), "\t\t$ ", format(sales_amount[count], ".2f"), "\t$ ", format(sales_amount[count], ".2f"))
sub_total = sub_total + (sales_amount[count])
count = count + 1
print("-----------------------------------------------")
print("Subtotal: $", format(sub_total, ".2f"))
def get_comp_name():
comp = ""
comp = input("\nEnter Company name: ")
return comp
def more_sales_input():
more = ""
more = input("Do you have more sales to add? (y/n): ")
more = more.upper()
while more != "Y" and more!= "N":
print("Invalid entry, either y or n.")
more = input("Do you have more sales to add? (y/n): ")
more = more.upper()
return more
def get_sales_amount():
sales = 0.0
while True:
try:
sales = float(input("Please enter sales $ "))
if sales < 0:
print("Invalid, must be a positive numeric!")
else:
return sales
except:
print("Invalid, must be a positive numeric!")
def get_commission_calc(sales):
commission = 0.0
if sales >= 20000:
commission = sales * .10
elif sales >= 10000:
commission = sales * .07
else:
commission = sales * .05
return commission
def get_bonus(commission):
if commission >= 1000:
return + 500
else:
return 0
def print_totals(bonus, total_commission):
if bonus > 0:
print("\nYou earned a $500 bonus added to your pay!")
else:
print("\nYou did not yet meet requirements for a bonus!")
print("\nYour commission is", '${:,.2f}'.format(total_commission))
main()
You're passing 'sales_amount', which is a list, to 'get_commission_calc', which then compares the list with a number; hence the error.
What I believe you're trying to do is not passing the list, but the 'selected_item' of the list.
If that's the case, the function call should look more like this:
get_commission_calc(sales_amount[selected_item])
Its not working this is what I am trying to do.
finding out the tax of a person and subtract some based on their status and dependents my expected output is the user will enter its income then will multiply how much tax will be deducted and will also deduct some based on their status and how many dependents
They have:
Income: 500000
Status: Married
Dependents= 3
Tax = 25000
income = float(input("your income: "))
if income <= 100000:
initialIncome = income * .5
elif income in range (100001,250000):
initialIncome = income * .10
elif income in range (250001,500000):
initialIncome = income * .15
elif income >= 500001:
initialIncome = income * .20
status = input("status (s,m,w,d) ")
if status == "S":
S = 10000
elif status == "M":
S = 20000
elif status == "W":
S = 10000
elif status == "D":
S = 30000
dependents = float(input("dependents num: "))
if dependents >= 5:
dependentsPrice = 50000
if dependents <= 5:
dependentsPrice = 10000 * dependents
totalTax = initialIncome - (status + dependents)
print(totalTax)
Code:
You are using status in totalTax instead of S.
You must add .upper() to convert all the input strings to upper case as you have used uppercase in if statements.
income = float(input("your income: "))
if income <= 100000:
initialIncome = income * .5
elif income in range (100001,250000):
initialIncome = income * .10
elif income in range (250001,500001):
initialIncome = income * .15
elif income >= 500001:
initialIncome = income * .20
else:
print("Invalid input")
initaialIncome = 0
# Here you must add upper to convert all the strings to upper case
status = input("status (s,m,w,d) ").upper()
#To prevent undefined error
S =
if status == "S":
S = 10000
elif status == "M":
S = 20000
elif status == "W":
S = 10000
elif status == "D":
S = 30000
#In case user enters wrong input.
else:
print("Invalid input")
dependents = float(input("dependents num: "))
if dependents >= 5:
dependentsPrice = 50000 *dependents
if dependents <= 5:
dependentsPrice = 10000 * dependents
# Here status is string. I suppose you are trying to use S.
#here use dependsPrice
totalTax = initialIncome - (S + dependentsPrice)
print(totalTax)
Here is the code I wrote and I am not able to get the surcharge to add into the final price of the ticket:
#program will compute the price of a theater ticket
#cost of a ticket will be 10 dollars $
#3D _ticket will cost a surcharge of 2 $
#senior discount will be 20%
#children discount will be 10%
#value will be in $
ticket = 10
senior discount = .8
children discount = .9
surcharge = +2
#ask user to input age, and if the move is in 3D
num = int(input('enter buyers age: \n'))
question1 = input('is the movie in 3D? \n')
#if statements determine discount for seniors and children and compute the price
if num > 60:
print('the senior ticket cost is: $', ticket * .8)
if num < 12:
print('the children cost of the ticket is $', ticket * .9)
elif num >= 12 and num <=60:
print('cost of the adult ticket is $', ticket)
if question1 == 'yes':
print('print price of ticket with surcharge is $', ticket +2)
elif question1 == 'no':
print('no surcharge!')
else:
print('invalid') #answer should be yes or no
print('num + question1')
You are only printing the calculated value of the ticket, but you are not updating the actual variable to be used in later steps. For example, instead of
if num < 12:
print('the children cost of the ticket is $', ticket * .9)
you should write
if num < 12:
ticket = ticket * 0.9
print('the children cost of the ticket is $', ticket)
Update all calculations similar to the above example I did for you.
https://www.101computing.net/entry-fees-calculator-using-a-flowchart/
I was trying to do the coding challenge my school sent me (link attached above) and I got quite stuck so I was hoping if someone could help. I was stuck when trying to add the discount calculating part because I had to see if the price was more than 50 and if it was, apply a 5% discount to it
def ThemePark():
age = int(input('Enter age: '))
if age <= 15:
print("Your entry price is £11")
if age >= 15:
print("Your entry price is £13.50")
if age >= 18:
print("Your entry price is £15 ")
discount = get_discount(price1 + price2 + price3)
print_discount_message(discount)
price > 50
price1 = 11
price2 = 13.50
price3 = 15
price > 50
discountprice = calculate_discount_price(price, discount)
print(f' Your price: {discd} (original price: {price})')
def Discount(price):
if price > 50:
discount = 0.95
else:
discount = 0.0
return discount
def print_discount_message(discount):
if discount == 0.0:
print(' Not qualified for family discount.')
else:
print(' Qualified for discount: {}%'.format(int(discount * 100)))
def calculate_discount_price(original_price, discount):
return round(original_price - original_price * discount, 2)
if __name__ == '__main__':
while True:
ThemePark()
more = input('Buy more? (Yes/No): ')
if more != 'Yes':
break
def print_discount_message(discount):
if discount == 0.0:
print(' Not qualified for family discount.')
else:
print(' Qualified for discount: {}%'.format(int(discount * 100)))
To output the print(' Qualified for discount: {}%'.format(int(discount * 100)))
you should have:
print(' Qualified for discount: {}%'.format(int((1 - discount) * 100)))
I am a first year programming student and I am having trouble trying to get my code to loop properly and I would like some pointers on how I can get it to run as desired. I am running a program that will calculate change with a preset stock of 10 of each coin, price and payment will be input by the user and change will be returned by the number of coins left in the stock. Right now i am having difficulties trying to get the program to return the 'insufficient funds' and the 'no change' print statements and trying to get it to loop over from quarters to dimes to nickels and pennies properly, I am not sure what I could be doing wrong.
quarters = 10
dimes = 10
nickels = 10
pennies = 10
stock = quarters, dimes, nickels, pennies
print("\nWelcome to change-making program.")
print("\nStock: {} quarters, {} dimes, {} nickels, and {} pennies".format(
quarters, dimes, nickels, pennies))
in_str = float(input("Enter the purchase price (xx.xx) or 'q' to quit: "))
payment_int = int(input("Input dollars paid (int):"))
change_sum = float(payment_int) - in_str
#in_str = float(input("Enter the purchase price (xx.xx) or 'q' to quit: "))
while change_sum >= 0:
if payment_int < in_str:
print("Insufficient funds")
break
elif payment_int == in_str:
print("No Change")
break
else:
if quarters > 0 and change_sum >= 0.25:
change_sum = change_sum - 0.25
quarters -= 1
print(quarters, change_sum)
elif dimes > 0 and 0.25 > change_sum >= 0.10:
change_sum = change_sum - 0.1
dimes -= 1
print(dimes, change_sum)
elif nickels > 0 and 0.1 > change_sum >= 0.05:
change_sum = change_sum - 0.05
nickels -= 1
print(nickels, change_sum)
elif pennies > 0 and 0.05 > change_sum >= 0.01:
change_sum = change_sum -0.01
pennies -=1
print(pennies, change_sum)
else:
if change_sum == 0.0:
break
print("\nStock: {} quarters, {} dimes, {} nickels, and {} pennies".format(
quarters, dimes, nickels, pennies))
print(change_sum)
If the fund is insufficient, then change_sum is <0 and the while loop never runs. That's why you don't get "insufficient fund" message. You should first check the sufficiency and then start the loop:
Just change this part:
while change_sum >= 0:
if payment_int < in_str:
print("Insufficient funds")
break
elif payment_int == in_str:
print("No Change")
break
else:
if quarters > 0 and change_sum >= 0.25:
to this:
if payment_int < in_str:
print("Insufficient funds")
break
elif payment_int == in_str:
print("No Change")
break
while change_sum >= 0:
if quarters > 0 and change_sum >= 0.25: