Below is the code I use.
# display a welcome message
print("===============================================================")
print("Shipping Calculator")
print("===============================================================")
while True:
# get input from the user
cost_of_items = float(input("Cost of items ordered: "))
# make sure input is a positive number
if cost_of_items < 0:
print("You must enter a positive number. Please try again.")
continue
# to do: get shipping cost(one given for example)
if cost_of_items < 30:
shipping_cost = 5.95
if 30.00 < cost_of_items < 49.99:
shipping_cost = 7.95
if 50.00 < cost_of_items < 74.99:
shipping_cost = 9.95
if cost_of_items > 75:
shipping_cost = 0
# To do: calculate total cost: total_cost
total_cost = cost_of_items + shipping_cost
# to do: display in output, print shipping cost, print total cost
print(shipping_cost,total_cost)
# to do: make your program more interesting, ask user how many item like to ship,
num_of_items = float(input("Number of items to ship: "))
# and caclutate the cost of shipping based on total cost
total_shipping_cost = shipping_cost*num_of_items
final_total_cost = cost_of_items + total_shipping_cost
print(total_shipping_cost, final_total_cost)
# see if the user wants to continue
choice = input("Continue? (y/n): ")
print("===============================================================")
if choice.lower() != "y":
break
print("Bye!")
Here is the output I get:
enter image description here
but I want the output to display like:
enter image description here
How can I do that? to put some description before the output? like Number of items to ship: X, Total Shipping cost: XX
You are attempting to create a multi-line string. That can simply be done with "\n"
Example:
# String containing newline characters
line_str = "I'm learning Python.\nI refer to TechBeamers.com tutorials.\nIt is the most
popular site for Python programmers."
That should make it appear like:
"I'm learning Python.
I refer to TechBeamers.com tutorials.
It is the most
popular site for Python programmers."
need to add the newline character to the end of your prints:
\n
Don't forget to print the name of each variable alongside the value of each variable.
print('Shipping Cost: ' + str(shipping_cost) + '\n', 'Total Cost: ' + str(total_cost))
...
print('Total Shipping Cost: ' + str(total_shipping_cost) + '\n', 'Final Shipping Cost: ' + str(final_total_cost))
You need to write some text manually that you want to print as follows
# display a welcome message
print("===============================================================")
print("Shipping Calculator")
print("===============================================================")
while True:
# get input from the user
cost_of_items = float(input("Cost of items ordered: "))
# make sure input is a positive number
if cost_of_items < 0:
print("You must enter a positive number. Please try again.")
continue
# to do: get shipping cost(one given for example)
if cost_of_items < 30:
shipping_cost = 5.95
if 30.00 < cost_of_items < 49.99:
shipping_cost = 7.95
if 50.00 < cost_of_items < 74.99:
shipping_cost = 9.95
if cost_of_items > 75:
shipping_cost = 0
# To do: calculate total cost: total_cost
total_cost = cost_of_items + shipping_cost
# to do: display in output, print shipping cost, print total cost
print("Shipping cost:", shipping_cost)
print("Total cost:", total_cost)
# to do: make your program more interesting, ask user how many item like to ship,
num_of_items = float(input("Number of items to ship: "))
# and caclutate the cost of shipping based on total cost
total_shipping_cost = shipping_cost*num_of_items
final_total_cost = cost_of_items + total_shipping_cost
print("Total Shipping cost:", total_shipping_cost)
print("Final total cost:", final_total_cost)
# see if the user wants to continue
choice = input("Continue? (y/n): ")
print("===============================================================")
if choice.lower() != "n":
break
print("Bye!")
Related
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))
I've nearly finished my program but have to add a feature so it only accepts certain coins and will throw a message if a wrong coin is inserted.
any help would be appreciated
def main():
total = 0
coins = [10, 20, 30]
while True:
total += int(input("Insert one coin at a time: ").replace('"', '').replace("'", '').strip())
coke = 50
print(total)
if total > coke:
print("Change Owed =", total - coke)
return
elif total == coke:
print("No Change Owed, Here's a coke ")
return
else:
print("Amount Due =", coke-total)
main()
As suggested by #Barmar, create a list of allowed coins and make sure the input falls in the list:
def main():
total = 0
allowed_coins = [25,50,100]
coke = 50
while True:
coin_input = int(input("Insert one coin at a time: ").replace('"', '').replace("'", '').strip())
if coin_input not in allowed_coins:
print("Invalid Coin Amount Due =", coke - total)
return
total = total + coin_input
if total > coke:
print("Change Owed =", total - coke)
return
elif total == coke:
print("No Change Owed, Here's a coke ")
return
else:
print("Amount Due =", coke-total)
main()
You need to check the coin before adding it to total. If it's not valid, skip the rest of the loop and ask again
def main():
total = 0
coins = [10, 20, 30]
while True:
coin = int(input("Insert one coin at a time: ").replace('"', '').replace("'", '').strip())
if coin not in coins:
print("That's not an allowed coin, try again")
continue
total += coin
coke = 50
print(total)
if total > coke:
print("Change Owed =", total - coke)
return
elif total == coke:
print("No Change Owed, Here's a coke ")
return
else:
print("Amount Due =", coke-total)
main()
I am trying to make a Shipping calculator in python by using IF Statements.
The application should calculate the total cost of an order including shipping. I am stuck at a point where python just won't run my code at all. I have a feeling I'm close but I do not know what is wrong with what I'm inputting because python won't return any errors. please someone just steer me in the right direction.
Instructions:
Create a program that calculates the total cost of an order including shipping.
When your program is run it should ...
Print the name of the program "Shipping Calculator"
Prompt the user to type in the Cost of Items Ordered
If the user enters a number that’s less than zero, display an error message and give the user a chance to enter the number again.
(note: if you know loops/iterations, OK to use here, but if not, just a simple one-time check with an if statement will be OK here.)
For example: if the cost is less than zero, print an error message and then re-ask once for the input.
Use the following table to calculate shipping cost:
Cost of Items
Shipping cost
<30
5.95
30.00-49.99
7.95
50.00-74.99
9.95
>75.00
FREE
Print the Shipping cost and Total Cost to ship the item
End the program with an exit greeting of your choice (e.g. Thank you for using our shipping calculator!)
Example 1:
=================
Shipping Calculator
=================
Cost of items ordered: 49.99
Shipping cost: 7.95
Total cost: 57.94
Thank you for using our shipping calculator!
Example 2:
=================
Shipping Calculator
=================
Cost of items ordered: -65.50
You must enter a positive number. Please try again.
Cost of items ordered: 65.50
Shipping cost: 9.95
Total cost: 75.45
Thank you for using our shipping calculator!
Here is the code I have written out so far:
#Assignment shipping calculator
#Author: Name
def main():
print("Shipping Calculator")
subtotal = calc_subtotal()
shipping = calc_shipping()
total = calc_total()
main()
def calc_subtotal():
subtotal = float(input("Cost of Items Ordered: $"))
if subtotal <= 0:
print("You must enter a positive number. Please try again.")
return subtotal
def calc_shipping():
subtotal = calc_subtotal()
shipping = calc_shipping
if subtotal >= 1 and subtotal <= 29.99:
shipping = 5.95
print("Shipping Cost: $5.95")
if subtotal >= 30 and subtotal <= 49.99:
shipping = 7.95
print("Shipping Cost: $7.95")
if subtotal >= 50 and subtotal <= 74.99:
shipping = 9.95
print("Shipping Cost: $9.95")
if subtotal >= 75:
shipping = 0
print("Shipping Cost: Free")
def calc_total():
total = calc_subtotal() + calc_shipping()
print("Total Cost: ",total)
print("Thank you for using our shipping calculator!")
First, I will put the code here then explain all the changes I made (your original attempt was very close, just a few tweaks):
#Assignment shipping calculator
#Author: Name
def main():
print("Shipping Calculator")
subtotal = calc_subtotal()
shipping = calc_shipping(subtotal)
calc_total(subtotal,shipping)
def calc_subtotal():
subtotal = float(input("Cost of Items Ordered: $"))
while subtotal <= 0:
print("You must enter a positive number. Please try again.")
subtotal = float(input("Cost of Items Ordered: $"))
return subtotal
def calc_shipping(subtotal):
if subtotal >= 1 and subtotal <= 29.99:
shipping = 5.95
print("Shipping Cost: $5.95")
if subtotal >= 30 and subtotal <= 49.99:
shipping = 7.95
print("Shipping Cost: $7.95")
if subtotal >= 50 and subtotal <= 74.99:
shipping = 9.95
print("Shipping Cost: $9.95")
if subtotal >= 75:
shipping = 0
print("Shipping Cost: Free")
return shipping
def calc_total(subtotal,shipping):
total = subtotal + shipping
print("Total Cost: $" + str(round(total,2)))
print("Thank you for using our shipping calculator!")
main()
As #Devang Sanghani mentioned, you should call your main() outside of your function so that it will run
For your calc_subtotal() function, use a while loop to keep taking in user input until given a valid number. Make sure you move your return subtotal outside of this loop so that it will only return it once this number is valid.
In your calc_shipping() function, make sure you take in subtotal as a parameter since you are using it in your function. Make sure you also return shipping.
Similarly, in your calc_total() function, take in both subtotal and shipping as parameters since they are used in your function.
Given these changes, update your main() function accordingly.
I hope these changes made sense! Please let me know if you need any further help or clarification :)
Adding to the above answers, also consider the case where the price can be a few cents, so this line should change:
if subtotal >= 0 and subtotal <= 29.99: # changed from 1 to 0
So there seem to be 2 errors:
You forgot to call the main function
You indented the return statement in calc_subtotal() so it returns the value only if the subtotal <= 0
The correct code might be:
def main():
print("Shipping Calculator")
subtotal = calc_subtotal()
shipping = calc_shipping()
total = calc_total()
def calc_subtotal():
subtotal = float(input("Cost of Items Ordered: $"))
if subtotal <= 0:
print("You must enter a positive number. Please try again.")
calc_subtotal() # Re asking for the input in case of invalid input
else:
return subtotal # returning subtotal in case of valid input
def calc_shipping():
subtotal = calc_subtotal()
shipping = calc_shipping
if subtotal >= 0 and subtotal <= 29.99:
shipping = 5.95
print("Shipping Cost: $5.95")
if subtotal >= 30 and subtotal <= 49.99:
shipping = 7.95
print("Shipping Cost: $7.95")
if subtotal >= 50 and subtotal <= 74.99:
shipping = 9.95
print("Shipping Cost: $9.95")
if subtotal >= 75:
shipping = 0
print("Shipping Cost: Free")
def calc_total():
total = calc_subtotal() + calc_shipping()
print("Total Cost: ",total)
print("Thank you for using our shipping calculator!")
main() # Calling main
The calculator does not recognize the price input being 60 as the first if statement, it will send you to else.
while True:
price = float(input("How much does it cost? (include cents!): $"))
discount=float(price)*100 / 1000
discount2=float(price)*200 /1000
proceed = 60
proceed2 = 120
if price >= proceed << proceed2:
print("Your new cost is")
print(round(price - discount, 2))
print("Press any key to exit")
input()
if price >= proceed2:
print("Your new cost is")
print(round(price - discount, 2))
print("Press any key to exit")
input()
else:
print("You are not viable for a discount, make a purchase >= sixty dollars to recive a 10% discount or a purchase >= $120 for a 20% discount.")
print("Press any key to exit")
input()
I fixed it, the first if statement used << when it should have used <.
while True:
price = float(input("How much does it cost? (include cents!): $"))
discount=float(price)*100 / 1000
discount2=float(price)*200 /1000
proceed = 60
proceed2 = 120
if price >= proceed < proceed2:
print("Your new cost is")
print(round(price - discount, 2))
print("Press any key to exit")
input()
if price >= proceed2:
print("Your new cost is")
print(round(price - discount, 2))
print("Press any key to exit")
input()
else:
print("You are not viable for a discount, make a purchase >= sixty dollars to recive a 10% discount or a purchase >= $120 for a 20% discount.")
print("Press any key to exit")
input()
I've been having some trouble with Else and Elif statements in Python 3.3.3 lately.
Here's my code:
# ATM was programmed by Jamie Mathieson
# introduction
sleep (1)
print ("-----------------------------------------------")
print ("\n ATM ")
print ("\n-----------------------------------------------")
sleep (3)
print ("\nWelcome to ATM. ATM is a mathematical system that handles data.")
sleep (5)
print ("\n Your ATM card has is being inserted. Please wait...")
sleep (3)
print ("Your ATM card has been inserted.")
sleep (5)
print ("Type 'options' to view available commands.")
# variables
balance = print("Balance £", money)
money = 200
options = ("Options: 1) Withdraw <amount> 2) Deposit <amount> 3) Balance 4) Exit")
# statements
option=int(input("Please enter an option: "))
if Option==1:
print("Balance £", money)
if Option==2:
print("Balance £", money)
Withdraw=float(input("Please enter the amount of money you would like to withdraw: £ "))
if Withdraw>0:
newbalance=(money-Withdraw)
print("New Balance: £",remainingbalance)
elif: Withdraw>money
print("No Balance Remaining")
else:
print("Withdraw canceled.")
if Option==3:
print("Balance £", money)
Deposit=float(input("Please enter the amount of money you would like to deposit: £ "))
if Deposit>0:
newbalance=(money+Deposit)
print("New Balance: £",newbalance)
else:
print("Deposit canceled.")
if Option==4:
print("ATM is ejecting your card. Please wait...")
sleep(5)
exit()
The error I'm getting is "invalid syntax" and it highlights both the Else and Elif statements. What is it that I'm doing wrong?
You have to put the : at the end, and correct the identation.
if Option==2:
print("Balance £", money)
Withdraw=float(input("Please enter the amount of money you would like to withdraw: £ "))
if Withdraw>0:
newbalance=(money-Withdraw)
print("New Balance: £",remainingbalance)
elif Withdraw>money:
print("No Balance Remaining")
else:
print("Withdraw canceled.")
There are several issues with the code. As #Daniel pointed out, your indentation must be corrected. Also, your condition for the elif block is placed after the colon.
Beyond that, you're assigning the user's response to a variable called option and then writing conditions on Option. Those are two different things.
Finally balance = print("Balance £", money) is going to throw an error. It looks like you're trying to define balance as a function that will print "Balance £" followed by the balance amount. If so, you could do something like this:
balance = lambda x: print("Balance £{}".format(x))
Edit: To answer your question re: sleep, use
from time import sleep
while True:
# Reading id from user
id = int(input("\nEnter account pin: "))
# Loop till id is valid
while id < 1000 or id > 9999:
id = int(input("\nInvalid Id.. Re-enter: "))
# Iterating over account session
while True:
# Printing menu
print("\n1 - View Balance \t 2 - Withdraw \t 3 - Deposit \t 4 - Exit ")
# Reading selection
selection = int(input("\nEnter your selection: "))
# Getting account object
for acc in accounts:
# Comparing account id
if acc.getId() == id:
accountObj = acc
break
# View Balance
if selection == 1:
# Printing balance
print(accountObj.getBalance())
# Withdraw
elif selection == 2:
# Reading amount
amt = float(input("\nEnter amount to withdraw: "))
ver_withdraw = input("Is this the correct amount, Yes or No ? " + str(amt) + " ")
if ver_withdraw == "Yes":
print("Verify withdraw")
else:
break
if amt < accountObj.getBalance():
# Calling withdraw method
accountObj.withdraw(amt)
# Printing updated balance
print("\nUpdated Balance: " + str(accountObj.getBalance()) + " n")
else:
print("\nYou're balance is less than withdrawl amount: " + str(accountObj.getBalance()) + " n")
print("\nPlease make a deposit.");
# Deposit
elif selection == 3:
# Reading amount
amt = float(input("\nEnter amount to deposit: "))
ver_deposit = input("Is this the correct amount, Yes, or No ? " + str(amt) + " ")
if ver_deposit == "Yes":
# Calling deposit method
accountObj.deposit(amt);
# Printing updated balance
print("\nUpdated Balance: " + str(accountObj.getBalance()) + " n")
else:
break
elif selection == 4:
print("nTransaction is now complete.")
print("Transaction number: ", random.randint(10000, 1000000))
print("Current Interest Rate: ", accountObj.annualInterestRate)
print("Monthly Interest Rate: ", accountObj.annualInterestRate / 12)
print("Thanks for choosing us as your bank")
exit()
# Any other choice
else:
print("That's an invalid choice.")
# Main function
main()