the user is required to input package weight and after I input the packages it gives me the correct answer but the answer keeps on repeating.
heres the code:
more = "y"
count = 0
total = 0
x = 0
while(more == "y"):
lbs = eval(input("Please enter the weight of the package: "))
if (lbs >= 1 and lbs <= 2):
op1:(lbs * 1.10)
x = op1
count += 1
total += x
print("The current package shipping cost is:",op1)
if (lbs > 2 and lbs <= 6):
op2 = (lbs * 2.20)
x = op2
count += 1
total += x
print("The current package shipping cost is:",op2)
if (lbs > 6 and lbs <= 10):
op3 =(lbs * 3.70)
x = op3
count += 1
total += x
print("The current package shipping cost is:",op3)
if (lbs > 10):
op4 =(lbs * 3.80)
x = op4
count += 1
total += x
print("The current package shipping cost is:",op4)
if (lbs == 0):
print("your package cannot be delivered")
more = input ("Do you want to enter another Package? <y/n>: ")
while(more == "n"):
print("Your total shipping cost is:",total,"for",count,"packages")
This line -
while(more == "n"):
print("Your total shipping cost is:",total,"for",count,"packages")
You do not need the while loop. Just do -
print("Your total shipping cost is:",total,"for",count,"packages")
Additionally, you do not need eval(), just use int() -
lbs = int(input("Please enter the weight of the package: "))
You could use range() function instead of the >= <= ... etc. things. For e.g. -
if lbs in range(1,2+1): # Not really useful, still you could use this
# code
It is not significant, so to keep it simple, you do not need to use the range function
why don't you just start with
while True:
and place a break after each if evaluation, then you get only correct input, and in case of incorrect input the while loop starts again with the input question.
The input question also requires the information that the weight needs to be in lbs.
Since you deleted your previous question about your code is giving you errors and functions are not working...here I will explain what are your errors and the new program.
1.Your first error is you used def greeting function and you didn't complete the function and you have to define what the function should do when you call the function. You used def Greeting(): but you didn't complete it,if you are using a def function you always have to complete it after():
2.Your 2nd error is your while loop is not correct.It has some logical errors
3.Your 3rd error is your functions(op1.op2,op3,op4) are in the wrong format that's why your program didn't work as you expect
🎁here i update your previous question which was asked on 22nd October 2021...please go through this code and compare it to your one and learn your errors.
Good Luck buddy and always learn from your errors:)
new code:
def Greeting():
print('good morning')
Greeting()
n=str(input("please input full name: "))
print("hello",n,"this program will allow you to input package weight and display price")
package_count=0
total=0
more=False
while more==False:
more = input ("Do you want to enter another Package? <y/n>: ")
if(more == "y"):
lbs = int(input("Please enter the weight of the package: "))
else:
print('your total shipping cost is:',total,"for",package_count,'packages')
break
if (lbs>=1 and lbs<=2):
op1=(lbs*1.10)
print('The current package shipping cost is: ',op1)
package_count=package_count+1
total=op1
elif(lbs>2 and lbs<=6):
op2 = (lbs * 2.20)
print('The current package shipping cost is:',op2)
package_count=package_count+1
total=total+op2
elif(lbs > 6 and lbs <= 10):
op3 =(lbs * 3.70)
print("The current package shipping cost is:",op3)
package_count=package_count+1
total=total+op3
elif(lbs>10):
op4=(lbs*3.80)
print("The current package shipping cost is:",op4)
package_count=package_count+1
total=total+op4
else:
print("your package cannot be delivered")
more=False
Related
The following is a sample of a running program:
Welcome to the Fast Freight Shipping Company shipping rate program.
This program is designed to take your package(s) weight in pounds and
calculate how much it will cost to ship them based on the following rates.
2 pounds or less = $1.10 per pound
Over 2 pounds but not more than 6 pounds = $2.20 per pound
Over 6 pounds but not more than 10 pounds = $3.70 per pound
Over 10 pounds = $3.80 per pound
Please enter your package weight in pounds: 1
Your cost is: $ 1.10
Would you like to ship another package <y/n>? y
Please enter your package weight in pounds: 5
Your cost is: $ 11.00
Would you like to ship another package <y/n>? y
Please enter your package weight in pounds: 52
Your cost is: $ 197.60
Would you like to ship another package <y/n>? y
Please enter your package weight in pounds: 8
Your cost is: $ 29.60
Would you like to ship another package <y/n>? y
Please enter your package weight in pounds: 3
Your cost is: $ 6.60
Would you like to ship another package <y/n>? t
Invalid Input
Would you like to ship another package <y/n>? y
Please enter your package weight in pounds: 10
Your cost is: $ 37.00
Would you like to ship another package <y/n>? n
Thank you for your purchase, your total charge is $ 282.90
Goodbye!
This is what I have so far:
charges = 0
answer = "yes"
while (answer == "yes"):
packageWeight = eval (input ("Enter weight of package: "))
answer = input ("Do you have more items to input? <yes/no>? ")
if (packageWeight <=2):
charges = (packageWeight * 1.10)
print ("The cost is: $",charges)
elif (packageWeight >2) and (packageWeight<=6):
charges= (packageWeight * 2.20)
print ("The cost is: $", charges)
elif (packageWeight >6)and (packageWeight<=10):
charges = (packageWeight * 3.70)
print ("The cost is: $", charges)
else :
charges = (packageWeight * 3.80)
print ("The cost is: $", charges)
message = "Thank you for your purchase, your total charge is $"
sum= charges+charges
message += format(sum, ',.2f')
print(message)
print("Goodbye!")
how would I find the sum of all charges? And how would I be able to have the second question come after the cost?
So it would display:
Enter weight of package: 3
The cost is: 6.60
Do you have more items to input? yes/no
I did not quite understand this statement how would I find the sum of all charges, but I solved your second question.
Here is the code:
def get_charges(current_weight):
if (current_weight <= 2):
return (current_weight * 1.10)
elif (current_weight > 2) and (current_weight <= 6):
return (current_weight * 2.20)
elif (current_weight > 6) and (current_weight <= 10):
return (current_weight * 3.70)
else:
return (current_weight * 3.80)
charges = 0
answer = "yes"
while (answer == "yes"):
# Eval is not recommended, use a float and round if needed.
packageWeight = float(input("Enter weight of package: "))
charges += get_charges(packageWeight)
print("Current charges: ", charges)
answer = input("Do you have more items to input? <yes/no>? ")
print(f"Thank you for your purchase, your total charge is ${charges}")
print("Goodbye!")
eval() is not recommended for security reasons, so I changed it to float().
Let me know if you have any questions
i have been stuck in this problem for a while now,
am trying to make a game where the user is given only 100 number to create a well defined shinobi ( got the name from watch Naruto and i love the series)
so i made my own class attributes. am trying to create a function to store the game inside and trying to make it so if the player uses more than 100 or = 100, the code should stop running but instead the code run even to negative a figure
let me put out the code for understanding ( sorry for my long write up, its actually my first time here)
print("ok, lets beging the game")
import Avatars # importing my own customised class
s = Avatars.Shinobi('naruto', 'uzimaki', 'genin', 100, 50, 70) # original class attributes
name = input('enter your name: ')
print(f'welcome onboard {name}, so you have to make your own ninja using (1- 100) '
f'and each time you make a ninja, we minus the number from the 100 you have '
f'GoodLuck!!')
print(" all you have to do is make a ninja that has 'strength', 'chakra', and 'skill' ")
def game(): # putting everything inside a function
try:
numb = 100 # the max number given by me to the player
while numb > 0:
a = (s.set_skill()) # using the imported class
a1 = int(a)
numb -= a
print('you have ', numb)
b = (s.set_chakra()) # using the imported class
b1 = int(b)
numb -= b
print(' you have ', numb)
c = (s.set_strength()) # using the imported class
c1 = int(c)
numb -= c
print('you have', numb)
if numb < 0: # using an if statement to cut the game half way, if the user inputs more than 100
print('you have run out of numbers')
else:
print('you still have more numbers to go!!')
except:
print('enter only number')
print(game())
OUTPUT:
ok, lets beging the game
enter your name: emma
welcome onboard emma, so you have to make your own ninja using (1- 100) and each time you make a ninja, we minus the number from the 100 you have GoodLuck!!
all you have to do is make a ninja that has 'strength', 'chakra', and 'skill'
enter skill rate (1 - 100): 50
you have 50
enter chakra level (1 - 100): 50
you have 0
enter strength level (1 - 100): 60
you have -60
you have run out of numbers
the code was suppose to stop, since i have input 50 twice and have no number left
Thanks for the help!
Hi Emmanuel Chidera, this is happening because you are substracting from numb after each set operation but checking numb value 'til the end. In order to prevent this to occur, you may check the numb variable value after each set operation and if its value is <= 0 you end right there the program execution.
To help you to understand this situation a bit better, I'm going to provide this short code snippet demonstrating the difference between your approach (checking numb value at the end) and the possible solution.
def initShinobi():
#This is similar to your approach
print("Inside initShinobi function\n")
maxPoints = 100 # the maximum stat points
skill = int(input("Enter skill level: "))
maxPoints -= skill
print(f'You have {maxPoints} points left to assign.')
chakra = int(input("Enter chakra level: "))
maxPoints -= chakra
print(f'You have {maxPoints} points left to assign.')
strength = int(input("Enter strength level: "))
maxPoints -= strength
print(f'You have {maxPoints} points left to assign.')
if maxPoints < 0:
print('you have run out of numbers')
def haveAvailablePoints(points):
"""Helper function to check your available points"""
if points > 0:
print(f'You have {points} points left to assign.')
return True
else:
print('You have run out of points')
return False
def initShinobi2():
# This is the possible solution
print("\n\nInside initShinobi2 function\n")
maxPoints = 100 # the maximum stat points
skill = int(input("Enter skill level: "))
maxPoints -= skill
if not haveAvailablePoints(maxPoints):
return
chakra = int(input("Enter chakra level: "))
maxPoints -= chakra
if not haveAvailablePoints(maxPoints):
return
strength = int(input("Enter strength level: "))
maxPoints -= strength
if not haveAvailablePoints(maxPoints):
return
if __name__ == '__main__':
initShinobi()
initShinobi2()
Assuming skill = 50, chakra = 50 and strength = 60 the code snippet above produces this output:
Inside initShinobi function
Enter skill level: 50
You have 50 points left to assign.
Enter chakra level: 50
You have 0 points left to assign.
Enter strength level: 60
You have -60 points left to assign.
you have run out of numbers
Inside initShinobi2 function
Enter skill level: 50
You have 50 points left to assign.
Enter chakra level: 50
You have run out of points
Successful execution. Press Enter to exit...
As you can see, in initShinobi2 function after I entered skill and chakra level it won't ask for me to enter the strength level since we have reached the maximum value with the first two parameters.
Note: You may notice in initShinobi2 function that if you type skill = 50 and chakra = 60 the output will be similar to the demonstration here but logically it has overpassed the maximum value, but that's something that I delegate you to solve.
The Speedy Shipping Company will ship packages based on how much they weigh and how far they are being sent. They will only ship light packages up to 10 pounds. You have been tasked with writing a program that will help Speedy Shipping determine how much to charge per delivery.
The charges are based on each segment of 500 miles shipped. Shipping charges are not pro-rated; i.e., 600 miles is the same charge as 900 miles; i.e., 600 miles is counted as 2 segments of 500 miles.
Your program should prompt the user for inputs (weight and miles), accept inputs from the keyboard, calculate the shipping charge, and produce accurate output.
Test:Prompts / Inputs:
Please enter package weight in pounds: 1.5
Please enter number of miles to ship: 200 (This is one 500-mile segment.)
Expected result:
To ship a 1.5 pound package 200 miles, your shipping charge is $1.50.
Helpful Hints:
You can use integer (floored) division. For example: 1200 // 500 = 2
So I have typed the code to the best of my knowledge however my print statement just prints (1.5). I need help in understanding why my print statement won't print the results.
# Package of Weight Rate per 500 miles shipped
# 2 pounds or less $1.50
# More than 2 but not more than 6 $3.75
# More than 6 but not more than 10 $5.25
weight_of_package = int(input("1.5"))
num_miles_ship = int(input("200"))
shipping_rate = 0
if weight_of_package > 0 and weight_of_package <= 2:
shipping_rate = 1.50
elif weight_of_package > 2 and weight_of_package <= 6:
shipping_rate = 3.75
elif weight_of_package > 6 and weight_of_package <= 10:
shipping_rate = 5.25
else:
print('Sorry, we only ship packages of 10 pounds or less')
shipping_charge = weight_of_package//num_miles_ship * shipping_rate
print(("To ship a " +str(weight_of_package) + "pound package" + str(num_miles_ship)
+ "your shipping charge is" + str(shipping_charge,".2f")))
There are several problems with your code.
The input method does probably do something else than you think. I does not convert anything, but it ask the user (you) for input and return this input. a=input("enter value for a:") will just open a prompt that will let you type something on your keyboard and when you press enter this will be copied into variable a here. So you may want to do weight_of_package=int(input("enter weight of package: ")) etc.
In your if/elif sequence: careful! python uses indentation to understand your scoping! This is critical in python and wrong in your code. You have to intend code in the if/elif blocks.
You can save some typing in the elif statements, since all the weight_of_package > XXX statements have no effect because of the preceding if statements (this would be just the else)
Before you second-last line shipping_charge = ... you need to protect against shipping_rate equal to zero. This will happen for a weight_of_package > 10 and will just fail in the calculation. Thus you need to add if shipping_rate>0: ...
Division operator in python is / not //
Best leave away the ,"2.f" in str(shipping_charge,".2f") since this does not do what you believe. If you do want to use formatted output use the standard python format syntax "{:.2f}".format(shipping_charge)`. Please consult https://docs.python.org/3/library/string.html#formatspec which is very interesting and relevant.
Here is the full example:
# Package of Weight Rate per 500 miles shipped
# 2 pounds or less $1.50
# More than 2 but not more than 6 $3.75
# More than 6 but not more than 10 $5.25
weight_of_package = int(input("please enter weight of package: "))
num_miles_ship = int(input("please enter miles to ship: "))
shipping_rate = 0
if weight_of_package > 0 and weight_of_package <= 2:
shipping_rate = 1.50
elif weight_of_package <= 6:
shipping_rate = 3.75
elif weight_of_package <= 10:
shipping_rate = 5.25
else:
print('Sorry, we only ship packages of 10 pounds or less')
if shipping_rate > 0:
shipping_charge = weight_of_package / num_miles_ship * shipping_rate
print("To ship a {} pound package {} miles "
"your shipping charge is {:.2f} ".format(
weight_of_package, num_miles_ship, shipping_charge))
Your print statement is probably not being executed at all right now
I am guessing that 1.5 which you are probably seeing is the result of this line probably
weight_of_package = int(input("1.5"))
The input() function in python takes an argument that tells the user about the input being required. So, if you change it to
weight_of_package = float(input("Enter the weight of package"))
and then run the program. You'll be prompted to Enter the weight of package following which you need to give the program input for the weight of the package ( and you'll enter 1.5 )
Also, you need to use float instead of int in that line as 1.5 is a decimal value
Making this change, it'll be easier for you to debug the print statements that are at the bottom of the code as 1.5 won't confuse you.
I'm creating this program in python that calculates you total cost according to how much you choose.
so the program is pizza delivery, and the user has to choose their choice of pizza out of the menu.
what I cant figure out is that how to tell python that whatever the users first,second and third choice is, the cost will be 3 dollars and the rest would be 5 dollars.
what I mean in more dept would be that how do i tell python that the users 1st,2nd,3rd choice/input = $3.
I tried writing: menu[0:3] = 3 but that just changes the food in the array/list.
this is a sample of my code(not the full code)
Code :
i = 1
total_cost = 0
while(True):
choice = input("Please Enter Your Choice:")
if(i<4):
price = 3
total_cost = total_cost + price
else:
price = 5
total_cost = total_cost + price
i = i + 1
check = input("Do you want to enter another choice? (y/n)")
if(check=="N" or check="n" or check=="No" or check=="no"):
break
print("Total Cost : $",total_cost)
Output :
Please Enter Your Choice:tea
Do you want to enter another choice? (y/n)y
Please Enter Your Choice:coffe
Do you want to enter another choice? (y/n)y
Please Enter Your Choice:apple
Do you want to enter another choice? (y/n)n
Total Cost : $ 9
Try this function:
def price(choice):
if choice <= 3:
cost = 3
else:
cost = 5
return cost
price(4)
> 5
You can create a counter variable for tracking inputs, increment it after taking each input. And then in the price section of your code, use an if statement to set price to 3 if counter < 4, else set price to 5.
# Create counter variable
counter = 0
# Taking user input code here
counter = counter + 1
# Later when setting price in code
if counter < 4:
price = 3
else:
price = 5
Hope this gives you some ideas, feel free to comment and ask for more clarification if you need to!
You should do something like this:
for i in range(1, number_of_pizza+1):
if i < 4:
total_cost += 3
if i >= 4:
total_cost += 5
According to my understanding of your question, you would want to have the menu items separated in the list as :
menu = ['Cheese', 'Vege delight', 'pineapple', 'pepperoni','meat lovers', 'butter chicken', 'spicy corn delight', 'veg slingshot']
and not in the way in which you had shown it in your image.
Evening Stack Overflow. Im a beginner in Python, which is why i decided to come on here for some help. Specifically, i'm having trouble understanding "do-while loop".
Here is the assignment i where given:
[Design the logic for a program that allows the user to enter a number. The program will display the sum of every number from 1 through the entered number. The program will allow the user to continuously enter numbers until the user enters 0.]
Here is my code without the "Do-while loop":
#Number Sum Conversion Calculator - V 0.0.1
#Author: Dena, Rene
print('Welcome to "Sum Conversion Calculator!"')
print('\nThis script will allow you to insert an integer and will thus display the total \ sum of the number you entered using summation methodology.')
print("\n Let's begin.")
name = input("In starting, what is your name?")
print('\n')
print("Hello %s. Let's get started." % (name))
base_number = 1
user_number = int(input("Insert your integer:"))
par = user_number + 1
n = user_number
num = 2
dom = par * n
answer = dom / num
print ("\n\nThe sum of the integer you entered is %s." % (answer))
print ('\nThank you for using "Number Sum Conversion Calculator". \
Please press ENTER to exit.')
Works great. Essentially do what i want it to do.
Now, from the assignment......it states:
The program will allow the user to continuously enter numbers until the user enters 0.
So here is my code/attempt for that:
#Number Sum Conversion Calculator - V 0.0.1
#Author: Dena, Rene
print('Welcome to "Sum Conversion Calculator!"')
print('\nThis script will allow you to insert an integer and will thus display \
the total sum of the number you entered using summation methodology.')
print("\n Let's begin.")
name = input("In starting, what is your name?")
print('\n')
print("Hello %s. Let's get started." % (name))
base_number = 1
user_number = int(input("Insert your integer:"))
def equation_run(EQ):
par = user_number + 1
n = user_number
num = 2
dom = par * n
answer = dom / num
print ("\n\nThe sum of the integer you entered is %s." % (answer))
zero = 0
while zero < user_number:
print (equation_run)
elif zero == user_number:
print ('Thank you for using "Number Sum Conversion Calculator". \
Please press ENTER to exit.')
When running this code, i get a syntax error. It highlights the elif part. Ive tried trial-and-error, but cant seem to get it to work. Please help.
Any comments/suggestion would be greatly appreciated. Thank you in advance and good day.
elif comes after an if, not a while. Replace it with a simple if:
while zero < user_number:
...
if zero == user_number:
...
something like:
while True:
number = int(input("Enter a number: "))
if number == 0:
break
print(0.5*number*(number+1))
should work