can someone help me troubleshoot my code the reply from going through the code at the end just loops instead of begining the program again completely would be brilliant is someone could help me thanks and i know its very basic and maybe not the best way to do it but as long as it works its fine.
start = input("Do you want to make an order? ")
while start == "Y" or start == "y" :
title = input("Enter book title: ")
sPrice = float(input("Enter price of book: "))
voucher = input("Do you have a voucher? ")
while sPrice >0 :
amount = float(input("Enter amount of books: "))
while amount >= 1 and amount <= 80 :
if amount >= 5 and amount <= 10 :
disc = 5
elif amount >= 11 and amount <= 50 :
disc = 7.5
elif amount >= 51 and amount <= 80 :
disc = 10
else :
disc = 0
base = sPrice * amount
discVal = (base * disc) / 100
dPrice = base - discVal
if voucher == "Y" or voucher == "y" and dPrice >= 25 :
voucherValue = 25
else :
voucherValue = 0
fPrice = dPrice - voucherValue
print (f"Discount rate: {disc}%")
print (f"Discount value: £{discVal:.2f}")
print (f"Total before discount: £{base:.2f}")
print (f"Total after discount: £{dPrice:.2f}")
if voucher == "Y" or voucher == "y" and dPrice >= 25 :
print (f"Value of voucher: £{voucherValue:.2f}")
print (f"Final cost of order: £{fPrice:.2f}")
else :
print ("ERROR - Invalid amount!")
amount = float(input("Enter amount of books: "))
else :
print ("ERROR - Price too low!")
sPrice = float(input("Enter price of book: "))
else :
start = input("Do you want to make an order? ")
You need to include if at two place just to validate the input value.
Change while sPrice >0 : to if sPrice >0 : and line while amount >= 1 and amount <= 80 : to if amount >= 1 and amount <= 80 :
Related
The error I get from the program is undefined variable.
*
# Python 3.9.4
# import sys
# print(sys.version)
SubjectT = input("Enter your subject: ")
Tutor_Name = input("Enter your name: ")
Iterate = int(input("How many students are there? "))
# Set counter
# create count for each student
Accumulate = 0
for i in range(Iterate): # It will run how many time based on Iterate input
Score = float(input("Enter score: "))
Counter = True
while Counter:
if 80 <= Score < 100:
Accumulate1 = Accumulate + 1
elif 80 > Score >= 65:
Accumulate2 = Accumulate + 1
elif 65 > Score >= 50:
Accumulate3 = Accumulate + 1
elif Score < 50:
Accumulate4 = Accumulate + 1
else:
print("The number is a negative value or incorrect")
Again = input("Enter yes for restarting again or if you want to exit the program please press anything: ")
if Again in ("y", "Y", "YES", "Yes", "yes"):
continue
else:
break
print(f"Subject title:", {SubjectT}, "\nTutor:", {Tutor_Name})
print("Grade", " Number of students")
print("A", "Students: ", Accumulate1)
print("B", "Students: ", Accumulate2)
print("C", "Students: ", Accumulate3)
print("D", "Students: ", Accumulate4)
This is my first post in Stackoverflow.
pardon me for any inappropriate content.
Thanks you so much.
You stated
Counter = True
without iteration, thus it will run indefinitely. With while loop you need to set some constraints.
I realised why you had the While loop in there, but it still wasn't working for me effectively - if all answers were within range it never terminated. This should work for you, it does for me. I changed it so it checks every time somebody enters a score that it is within the correct range, so you don't have to repeat the whole loop in the event of incorrect values
SubjectT = input("Enter your subject: ")
Tutor_Name = input("Enter your name: ")
NoOfStudents = int(input("How many students are there? "))
# Set counter
# create count for each student
Accumulate = 0
Accumulate1 = 0
Accumulate2 = 0
Accumulate3 = 0
Accumulate4 = 0
def validRange(score):
if 0 <= score <=100:
return True
else:
return False
i = 1
while (i <= NoOfStudents): # It will run how many time based on Iterate
validInput = False
while (not validInput):
Score = float(input("Enter score: "))
if ( not validRange(Score)):
print("The number is a negative value or incorrect")
else:
validInput = True
if 80 <= Score < 100:
Accumulate1 = Accumulate1 + 1
elif 80 > Score >= 65:
Accumulate2 = Accumulate2 + 1
elif 65 > Score >= 50:
Accumulate3 = Accumulate3 + 1
elif Score < 50:
Accumulate4 = Accumulate4 + 1
i = i+1
print(f"Subject title:", {SubjectT}, "\nTutor:", {Tutor_Name})
print("Grade", " Number of students")
print("A", "Students: ", Accumulate1)
print("B", "Students: ", Accumulate2)
print("C", "Students: ", Accumulate3)
print("D", "Students: ", Accumulate4)
array = []
total = 0
text = int(input("How many students in your class: "))
print("\n")
while True:
for x in range(text):
score = int(input("Input score {} : ".format(x+1)))
if score <= 0 & score >= 101:
break
print(int(input("Invalid score, please re-enter: ")))
array.append(score)
print("\n")
print("Maximum: {}".format(max(array)))
print("Minimum: {}".format(min(array)))
print("Average: {}".format(sum(array)/text))
I tried to make a python program, to validate the score, but it's still a mistake, I want to make a program if I enter a score of less than 0 it will ask to re-enter the score as well if I input more than 100. Where is my error?
Change the if statement:
array = []
total = 0
text = int(input("How many students in your class: "))
print("\n")
for x in range(text):
score = int(input("Input score {} : ".format(x+1)))
while True:
if 0 <= score <= 100:
break
score = int(input("Invalid score, please re-enter: "))
array.append(score)
print("\n")
print("Maximum: {}".format(max(array)))
print("Minimum: {}".format(min(array)))
print("Average: {}".format(sum(array)/text))
Here, the score at the same time can't be less than 0 and greater than 100. So as you want to break of the score is between 0 and 100, we use 0 <= score <= 100 as the breaking condition.
Also the loops were reversed, since you won't get what you expected to.
try this one:
array = []
total = 0
num_of_students = int(input("How many students in your class: "))
print("\n")
for x in range(num_of_students):
score = int(input("Input score {} : ".format(x + 1)))
while True:
if score < 0 or score > 100:
score = int(input("Invalid score, please re-enter: "))
else:
array.append(score)
break
print("\n")
print("Maximum: {}".format(max(array)))
print("Minimum: {}".format(min(array)))
print("Average: {}".format(sum(array)/num_of_students))
I renamed some of your variables. You should always try to using self explanatory variable names. I am also using string interpolation (should be possible for Python +3.6) and comparison chaining.
score_list = []
total = 0
number_of_students = int(input("How many students in your class: "))
print("\n")
for student in range(number_of_students):
score_invalid = True
while score_invalid:
score_student = int(input(f"Input score {student + 1} : "))
if (0 <= score_student <= 100):
score_invalid = False
else:
score_invalid = True
if score_invalid:
print("Invalid score!\n")
score_list.append(score_student)
print("\n")
print(f"Maximum: {max(score_list)}")
print(f"Minimum: {min(score_list)}")
print(f"Average: {sum(score_list) / number_of_students}")
You could try something like this:
score = -1
first_time = True
while type(score) != int or score <= 0 or score >= 101 :
if first_time:
score = int(input("Input score: "))
first_time = False
else:
score = int(input("Invalid score, please re-enter: "))
array.append(score)
I have made a program that adds up the orders of a fast food menu. I need to add a running subtotal after I have made an order. As I am a python novice, I am not quite sure what to do. I also need to make sure my order dictionary is modified, but am unsure how to do so.
I thought about making a loop with a range to keep the total but I do not want a range as I want the program to be able to take as many orders as possible.
# menu and order options
menu = {"burger":5.00, "fries":3.50, "drink":1.00}
order = {"burger":0, "fries":0, "drink":0}
bcount = 0
fcount = 0
dcount = 0
while True:
print("Please make a selection:")
print("1. Burger = $5.00")
print("2. Fries = $3.50")
print("3. Drink = $1.00")
print("4. Quit")
choice = int(input('Please order: '))
if choice == 1:
amount = int(input("Enter number of Burgers: "))
bcount += amount
elif choice == 2:
amount = int(input("Enter number of Fries: "))
fcount += amount
elif choice == 3:
amount = int(input("Enter number of Drinks: "))
dcount += amount
elif choice == 4:
sub = (bcount * 5.00) + (fcount * 3.50) + (dcount * 1.00)
tax = sub * 0.075
total = sub + tax
print('Number of Burgers: {0}'.format(bcount))
print('Number of Fries: {0}'.format(fcount))
print('Number of Drinks: {0}'.format(dcount))
print('Subtotal: {:0.2f}'.format(sub))
print('Tax: {:0.2f}'.format(tax))
print('Total: {:0.2f}'.format(total))
break
The expected result is after each order, the program would give me a running subtotal.
Example: after an order of a burger is entered would look like:
Your subtotal is: $5.00
Then the next order is an order of fries and a drink
Your subtotal is: $9.50 (adding the burger from the previous order)
One way to do this is to add a variable called subtotal in the beginning called subtotal. Attached one example for the burger that can be applied to the rest. I agree with previous commenter regarding reset of variables instead of break.
subtotal=0
bcount = 0
fcount = 0
dcount = 0
if choice == 1:
amount = int(input("Enter number of Burgers: "))
bcount += amount
subtotal+=(amount*5)
print("Your total is: ",subtotal)
I assume, for option 1 - 3, you need to show the subtotal and for option 4 you need to show the full report.
I have updated the code as following:
added calculate_sub_total method.
displayed subtotal for option 1-3.
separated the if-elif-else to two partitions.
Used the menu dictionary to fetch prices for items both in sub total calculation and in displaying the menu.
Used the order dictionary to keep track of the number of items as intended. Removed bcount, dcount, fcount variables as they are not needed anymore.
Updated code:
# menu and order options
menu = {"burger":5.00, "fries":3.50, "drink":1.00}
order = {"burger":0, "fries":0, "drink":0}
def calculate_sub_total():
return (order["burger"] * menu["burger"]) + \
(order["fries"] * menu["fries"]) + \
(order["drink"] * menu["drink"])
while True:
print("Please make a selection:")
print("1. Burger = ${}".format(menu["burger"]))
print("2. Fries = ${}".format(menu["fries"]))
print("3. Drink = ${}".format(menu["drink"]))
print("4. Quit")
choice = int(input('Please order: '))
show_subtotal = False
if choice == 1:
amount = int(input("Enter number of Burgers: "))
order["burger"] += amount
show_subtotal = True
elif choice == 2:
amount = int(input("Enter number of Fries: "))
order["fries"] += amount
show_subtotal = True
elif choice == 3:
amount = int(input("Enter number of Drinks: "))
order["drink"] += amount
show_subtotal = True
sub = calculate_sub_total()
if show_subtotal:
print('Subtotal: {:0.2f}'.format(sub))
if choice == 4:
tax = sub * 0.075
total = sub + tax
print('Number of Burgers: {0}'.format(order["burger"]))
print('Number of Fries: {0}'.format(order["fries"]))
print('Number of Drinks: {0}'.format(order["drink"]))
print('Subtotal: {:0.2f}'.format(sub))
print('Tax: {:0.2f}'.format(tax))
print('Total: {:0.2f}'.format(total))
break
Output:
I am a beginner with python and I am working with this project that will print the result of the students.I am done with nearly everything execpt the percentage.See,in my code,the program will only print the percentage of the last person's marks.I need to make it so that it calculates percentage for everyone individually and then print it at the end.Your help will be much appreciated.Thanks
T_marks = 1100
data = {}
while True:
ask = input("What do you want? ")
if ask == "y":
name = input("Enter your name: ")
marks = int(input("Enter marks: "))
data[name] = marks
percentage =(marks / T_marks) * 100
elif ask == "print":
for (key,value) in data.items():
print(key,"::",value)
if percentage > 90:
print("Passed with A grade")
elif percentage >= 70 and percentage < 90:
print("Passed with B grade")
elif percentage >= 60 and percentage < 70:
print("Passed with C grade")
elif percentage >= 50 and percentage < 60:
print("passed with D Grade")
else:
print("You failed")
else:
print("Your work has ended")
break
You need to compute percentage under the print case, this should get you what you want:
T_marks = 1100
data = {}
while True:
ask = input("What do you want? ")
if ask == "y":
name = input("Enter your name: ")
marks = int(input("Enter marks: "))
data[name] = marks
elif ask == "print":
for (key,value) in data.items():
# NOTE percentage is under the case when user asks for print
percentage =(value / T_marks) * 100
print(key,"::",value)
if percentage > 90:
print("Passed with A grade")
elif percentage >= 70 and percentage < 90:
print("Passed with B grade")
elif percentage >= 60 and percentage < 70:
print("Passed with C grade")
elif percentage >= 50 and percentage < 60:
print("passed with D Grade")
else:
print("You failed")
else:
print("Your work has ended")
break
Also two hints: This code will output "You failed" if someone got a grade of 90. You need to set equality at 90 for one of the cases. Also python has simplified comparisons where and is not needed. Here is a simplified version, and corrected for case of 90 to get an A grade:
T_marks = 1100
data = {}
while True:
ask = input("What do you want? ")
if ask == "y":
name = input("Enter your name: ")
marks = int(input("Enter marks: "))
data[name] = marks
elif ask == "print":
for (key,value) in data.items():
percentage =(value / T_marks) * 100
print(key,"::",value)
if percentage >= 90:
print("Passed with A grade")
elif 90 > percentage >= 70:
print("Passed with B grade")
elif 70 > percentage >= 60:
print("Passed with C grade")
elif 60 > percentage >= 50:
print("passed with D Grade")
else:
print("You failed")
else:
print("Your work has ended")
break
The input() method reads a string, but you cannot convert e. g. "4 4 4 5" to int. Method split() without arguments creates a list of the words in string as follow:
"4 5 5" -> ["4", "5", "5"]
Change your input to:
marks_string = input("Enter marks: ")
marks = [int(mark) for mark in marks_string.split()] # convertion to int
And change calculate of percentage:
percentage =(sum(marks) / T_marks) * 100
Indentation, fixed in edit:
T_marks = 1100
data = {}
while True:
ask = input("What do you want? ")
if ask == "y":
name = input("Enter your name: ")
marks = int(input("Enter marks: "))
data[name] = marks
percentage =(marks / T_marks) * 100
elif ask == "print":
for (key,value) in data.items():
print(key,"::",value)
if percentage > 90:
print("Passed with A grade")
elif percentage >= 70 and percentage < 90:
print("Passed with B grade")
elif percentage >= 60 and percentage < 70:
print("Passed with C grade")
elif percentage >= 50 and percentage < 60:
print("passed with D Grade")
else:
print("You failed")
else:
print("Your work has ended")
break
>>> What do you want? y
>>>Enter your name: Alex
>>>Enter marks: 12
>>>What do you want? y
>>>Enter your name: Michael
>>>Enter marks: 22
>>>What do you want? print
>>>Alex :: 12
>>>You failed
>>>Michael :: 22
>>>You failed
>>>What do you want?
I'm pretty new to coding so bear with me but how do I make this code work? I'm trying to take the information that is entered by the user and input it into my functions so I can print the total.
def hotel_cost(nights):
return nights * 140
def plane_cost(city):
if city == "Atlanta":
return 220
elif city == "Boston":
return 550
elif city == "Chicago":
return 900
def rental_car_cost(days):
if days >= 7:
return days * 100 - 50
elif days >= 1 and days <= 5:
return days * 100 - 20
a = raw_input("Please choose number of nights: ")
b = raw_input("Please choose which city you are flying to (Atlanta, Boston, Chicago) ")
c = raw_input("Please choose days of rental car use: ")
d = raw_input("Please choose how much spending money you plan on spending: ")
a = nights
b = city
c = days
total = a + b + c + d
print "Your total cost of trip is %d" % total
You need to first convert your numeric input values to numbers and then pass your input values to your functions.
Delete the lines
a = nights
b = city
c = days
Calculate your total with
total = hotel_cost(int(a)) + plane_cost(b) + rental_car_cost(int(c)) + float(d)
I assumed that for the number of nights and rental car days only integers make sense.
I am not sure if this applies in Python version 2. However, you could try this:
a = int(raw_input("Please choose number of nights: ") * 140 )
# Multiplies by 140, but this would defeat the purpose of your functions.
And apply the int function to convert all of your inputs into integers.
You can use input() in Python 2 as it evaluates the input to the correct type. For the functions, you just need to pass your values into them, like this:
def hotel_cost(nights):
return nights * 140
def plane_cost(city):
if city == "Atlanta":
return 220
elif city == "Boston":
return 550
elif city == "Chicago":
return 900
def rental_car_cost(days):
if days >= 7:
return days * 100 - 50
elif days >= 1 and days <= 5:
return days * 100 - 20
nights = input("Please choose number of nights: ")
city = raw_input("Please choose which city you are flying to (Atlanta, Boston, Chicago) ")
rental_duration = input("Please choose days of rental car use: ")
spending_money = input("Please choose how much spending money you plan on spending: ")
total = hotel_cost(nights) + plane_cost(city) + rental_car_cost(rental_duration) + spending_money
print "Your total cost of trip is %d" % total