Hi i am albert i am learning python, in this block of code i wrote i intend it to print the total, but the input statements just keep going in a loop
print("this program prints your invoice")
while True:
ID = input("item identification: ")
if ID == "done":
break
if len(ID) < 3:
print("identification must be at least 3 characters long")
exit(1)
break
try:
Quantity = int(input("quantity sold: "))
except ValueError:
print("please enter an integer for quantity sold!!!")
exit(2)
if Quantity <= 0:
break
print("please enter an integer for quantity sold!!!")
exit(3)
try:
price = float(input("price of item"))
except ValueError:
print("please enter a float for price of item!!")
exit(4)
if price <= 0:
print("please enter a positive value for the price!!!")
exit(5)
break
cost = 0
total = cost + (Quantity*price)
print(total)
I think you need this
cost = 0
total = cost + (Quantity*price)
print(total)
to be inside the while loop. Else, skip the loop completely.
Try this:
print("This program prints your invoice")
total = 0
more_to_add = True
while more_to_add == True:
ID = input("Item identification: ")
if len(ID) < 3:
print("Identification must be at least 3 characters long")
continue
try:
Quantity = int(input("Quantity sold: "))
except ValueError:
print("Please enter an integer for quantity sold!!!")
continue
if Quantity <= 0:
print("Please enter an integer for quantity sold!!!")
continue
try:
price = float(input("Price of item: "))
except ValueError:
print("Please enter a float for price of item!!")
continue
if price <= 0:
print("Please enter a positive value for the price!!!")
continue
total = total + (Quantity*price)
answer = input("Want to add more? (Y/N)" )
if answer == 'Y':
more_to_add = True
else:
more_to_add = False
print(total)
Related
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
d = {}
temp = 10000
total = 0
def Expanse_calculator():
global temp
buy = True
while buy == True:
x = input("Enter the expenditure name:")
if x in d.keys():
price =float(input(f" Enter the '{x}' amount:"))
if temp>=price:
d[x]+=price
temp-=price
else:
print("insufficint found")
break
else:
price =float(input(f"Enter the '{x}'amount:"))
if temp>=price:
d[x]=price
temp-=price
else:
print("insufficint found")
break
total=sum(d.values())
while True:
ip = input("If you want to add any more expenditure [YES|NO]:").lower()
if ip == 'no':
buy = False
break
elif ip == 'yes':
Expanse_calculator()
else:
print("Invalid Entry")
Expanse_calculator()
print(total)
Above is my sample code
While entering 'no' to my query in while loop its not terminating in first attempt
output i'm getting:
Enter the expenditure name:asd
Enter the 'asd'amount:123
If you want to add any more expenditure [YES|NO]:yes
Enter the expenditure name:asf
Enter the 'asf'amount:124
If you want to add any more expenditure [YES|NO]:no
If you want to add any more expenditure [YES|NO]:no
iam new to python plz help.
d = {}
temp = 10000
total = 0
def Expanse_calculator():
global temp,total
buy = True
while buy == True:
x = input("Enter the expenditure name: ")
if x in d.keys():
price =float(input(f" Enter the '{x}' amount: "))
if temp>=price:
d[x]+=price
temp-=price
else:
print("insufficient funds")
break
else:
price =float(input(f"Enter the '{x}'amount: "))
if temp>=price:
d[x]=price
temp-=price
else:
print("insufficient funds")
break
total=sum(d.values())
while True:
ip = input("If you want to add any more expenditure [YES|NO]:").lower()
if ip == 'no':
buy = False
break
elif ip == 'yes':
Expanse_calculator()
else:
print("Invalid Entry")
print(total)
quit()
Expanse_calculator()
I am creating a program where you will have to loop through multiple questions each with a condition. If user input for the question does not meet the requirement, it will print out the error and prompt user to re-enter. Else, it will continue with the next question. And not only prompting user to re-enter after all 3 questions are answered.
This it the output I am getting now:
while True:
amount = int(input("Enter amount: "))
rate = int(input("Enter rate: "))
year = float(input("Enter year: "))
if amount<4000:
print("Invalid amount")
continue
elif rate<0:
print("invalid rate")
continue
elif year<0:
print("invalid year")
break
Output:
Enter amount: 1
Enter rate: 3
Enter year: 4
Invalid amount
Enter amount:
Expected output:
Enter amount: 4
Invalid amount
Enter amount:
It's not very clear what are you trying to achieve, but I think you want this:
while True:
amount = int(input("Enter amount: "))
if amount < 4000:
print("Invalid amount")
continue
break
while True:
rate = int(input("Enter rate: "))
if rate < 0:
print("invalid rate")
continue
break
while True:
year = float(input("Enter year: "))
if year < 0:
print("invalid year")
continue
break
This will only ask to re-enter the invalid values.
Another more reusable method would be:
def loop_user_input(input_name, meets_condition):
while True:
value = int(input(f"Enter {input_name}: "))
if not meets_condition(value):
print(f"Invalid {input_name}")
else:
return value
loop_user_input('amount', lambda val: val < 4000)
loop_user_input('rate', lambda val: val < 0)
loop_user_input('year', lambda val: val < 0)
Here you have a loop that only returns when the input value meets the condition, that you pass in. I recommend you check your conditions, because a year normally shouldn't be negative (rate < 0). Also your solution throws an exception, if the user enters something else then an int. Maybe add a try-catch to your solution:
try:
value = int(input(f"Enter {input_name}: "))
except:
print(f"Invalid {input_name}")
continue
I just started learning python 3 recently and i have a problem of my code being too repetitive and lengthy.
i wrote a code to calculate the interest earned.
I have read about using functions to simplify my code but i am not sure how to go about doing this.
Thanks for anyone who is willing to help me out! The code i have written is as follows:
print("Welcome to the monthly interest rate calculator")
original_interest = 0.0005/12
additional_food_interest_1 = 0.0055/12
additional_food_interest_2 = 0.0085/12
additional_interest_3 = 0.0090/12
additional_interest_4 = 0.0015/12
additional_interest_5 = 0.0095/12
additional_interest_6 = 0.0035/12
interest = [original_interest]
#asks user for the amount of money they have in the bank
while True:
try:
account = float(input("Enter your account balance: "))
except ValueError:
print("Try Again.")
continue
else:
break
# checks if condition 1 is met before adding either food_interest_1 or food_interest_2 variable to the list
while True:
try:
food_spending = float(input("How much did you spend on food?: "))
except ValueError:
print("Try Again.")
continue
else:
break
if food_spending >= 100 and food_spending < 200:
interest.append(additional_food_interest_1)
elif food_spending >= 200:
interest.append(additional_food_interest_2)
else:
pass
# checks if condition 2 is and if so adds additional_interest_3 to the list
while True:
try:
drinks_spending = float(input("How much did you spend on drinks?: "))
except ValueError:
print("Try Again.")
continue
else:
break
if drinks_spending >= 100:
interest.append(additional_interest_3)
else:
pass
# checks if condition 3 is met and if so adds additional_interest_4 to the list
while True:
try:
insurance_spending = float(input("How much did you spend on insurance?: "))
except ValueError:
print("Try Again.")
continue
else:
break
if insurance_spending >= 100:
interest.append(additional_interest_4)
else:
pass
# checks if condition 4 is met and if so adds additional_interest_5 to the list
while True:
try:
debitcard_spending = float(input("How much did you spend on your debit card??: "))
except ValueError:
print("Try Again.")
continue
else:
break
if debitcard_spending >= 100:
interest.append(additional_interest_5)
else:
pass
# This checks for 4 inputs from the user and if satisfies the condition, adds additional_interest_6 to the list
while True:
try:
first_receipt = float(input("Enter the amount on your first receipt: "))
except ValueError:
print("Try Again.")
continue
else:
break
while True:
try:
second_receipt = float(input("Enter the amount on your second receipt: "))
except ValueError:
print("Try Again.")
continue
else:
break
while True:
try:
third_receipt = float(input("Enter the amount on your third receipt: "))
except ValueError:
print("Try Again.")
continue
else:
break
while True:
try:
four_receipt = float(input("Enter the amount on your fourth receipt: "))
except ValueError:
print("Try Again.")
continue
else:
break
if first_receipt > 20 and second_receipt > 20 and third_receipt >20 and four_receipt > 20:
interest.append(additional_interest_6)
#calculates the total interest earned
if account <= 20000:
print("your monthly interest earned is", round(account*(sum(interest)),2))
else:
print(20000*sum(interest) + (account-20000)*original_interest)
This is about as concise as I can make it with a quick pass.
I refactored things so all inputs are requested first, all computation done second. Should you refactor the calculation bits into a function, that'd make the function easier to test. I also refactored the computation into a function of its own.
def prompt_float(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
print("Try Again.")
def prompt_receipts():
receipts = []
while True:
receipt_value = prompt_float(
f"Enter the amount on receipt {len(receipts) + 1}, or <= 0 for no more receipts."
)
if receipt_value <= 0:
break
receipts.append(receipt_value)
if len(receipts) >= 4:
break
return receipts
def compute_interest(
*,
original_interest,
receipts,
debitcard_spending,
drinks_spending,
food_spending,
insurance_spending,
):
additional_food_interest_1 = 0.0055 / 12
additional_food_interest_2 = 0.0085 / 12
additional_interest_3 = 0.0090 / 12
additional_interest_4 = 0.0015 / 12
additional_interest_5 = 0.0095 / 12
interest = [original_interest]
if 100 <= food_spending < 200:
interest.append(additional_food_interest_1)
elif food_spending >= 200:
interest.append(additional_food_interest_2)
if drinks_spending >= 100:
interest.append(additional_interest_3)
if insurance_spending >= 100:
interest.append(additional_interest_3)
if debitcard_spending >= 100:
interest.append(additional_interest_4)
if all(receipt_value > 20 for receipt_value in receipts):
interest.append(additional_interest_5)
return interest
def main():
print("Welcome to the monthly interest rate calculator")
# Get user inputs.
account = prompt_float("Enter your account balance: ")
food_spending = prompt_float("How much did you spend on food?: ")
drinks_spending = prompt_float("How much did you spend on drinks?: ")
insurance_spending = prompt_float("How much did you spend on insurance?: ")
debitcard_spending = prompt_float(
"How much did you spend on your debit card??: "
)
receipts = prompt_receipts()
# Compute things.
original_interest = 0.0005 / 12
interest = compute_interest(
original_interest=original_interest,
receipts=receipts,
debitcard_spending=debitcard_spending,
drinks_spending=drinks_spending,
food_spending=food_spending,
insurance_spending=insurance_spending,
)
# Output things.
if account <= 20000:
print(
"your monthly interest earned is",
round(account * (sum(interest)), 2),
)
else:
print(20000 * sum(interest) + (account - 20000) * original_interest)
if __name__ == "__main__":
main()
You can wrap you try/except approach as:
def get_input(text)
while True:
try:
return float(input(text))
except ValueError:
print("Try Again.")
account = get_input("Enter your account balance: ")
food_spending = get_input("How much did you spend on food?: ")
....
I am writing a simple program that executes if-else condition. my program receives from the user as input the weight of an object in kg. , a floating number, and print out the price for shipment. by using while I want to Expand the program to function and calculate the total price for multiple packages. The program should load packet weight until the user enters a blank line or a number that is 0 or less. The program will then print the total price for all the packages
the code looks like this:
def packagePrice():
weightInKg = float(input(" Enter the value of weight:"))
totalPrise = 0
while weightInKg != "" or weight <= 0:
if weightInKg <= 10:
price = 149
elif 10 < weightInKg <= 100:
price = 500
elif weightInKg > 100:
print ("Not allowed")
totalPrise+= price
print(totalPrise)
weightInKg = float(input(" Enter the value of weight:"))
packagePrice()
but it does not properly run
anyone help
Does this answer the question ?
def packagePrice():
totalPrise = 0
while True:
weightInKg = input(" Enter the value of weight:")
if weightInKg == '':
break
try:
weightInKg = float(weightInKg)
except ValueError:
print("Text not allowed")
continue
if weightInKg <= 0:
break
if weightInKg <= 10:
totalPrise += 149
elif weightInKg <= 100:
totalPrise += 500
else:
print("Not allowed")
return totalPrise
print(packagePrice())
So here I am again, clueless as always. I'm somewhat of a novice, so this is probably biting off more than I can chew, but whatever.
The point of this program is to provide an output based off of input values from the user. It's meant to implement an input trap should the user not enter the correct input.
I'm trying to make it so the input of a letter or a non-integer value causes the message "Please enter only whole numbers." It works for the float points, but not letters. I should note that the "Enter a number between 0 and 10" message is working fine.
Also, the loop is supposed to close when the user inputs 'done', but that only results in a "ValueError: could not convert string to float: 'done'".
I haven't written this in While True format as it's more comfortable for me to stick away from that method of writing while loops.
setCount = 1
allScore = 0
done = False
while not done:
strScore = float (input ( "Enter Set#" + str(hwCount) + " score: "))
if (strScore == int (strScore) and strScore >=0 and strScore <=10):
totalScore = totalScore + (strScore)
setCount = setCount + 1
elif ( setScore == int (strScore) and( setScore < 0 or setScore > 10)):
print ("Please enter a number between 0 and 10.")
elif setScore != "done":
print ("Please enter only whole numbers.")
else:
done = True
You immediately convert the input string to a float on the same line where you read it:
strScore = float (input ( "Enter HW#" + str(hwCount) + " score: "))
In order to accept "done" as an input, you need to keep it as a string, and convert it to float (or int) after you have done all input validation.
drop float() and strScore will be a string. Then check if it equals "done". Finally, convert it to an integer inside a try block
print ( "Enter the homework scores one at a time. Type \"done\" when finished." )
hwCount = 1
totalScore = 0
while True:
strScore = input ( "Enter HW#" + str(hwCount) + " score: ")
if strScore == "done":
break
try:
intScore = int(strScore)
except ValueError:
print ("Please enter only whole numbers.")
continue
if (intScore >=0 and intScore <=10):
totalScore += intScore
hwCount += 1
else:
print ("Please enter a number between 0 and 10.")
You should really clean your code up, all those extra spaces hurts readability. I'd suggest using PyLint (pip install pylint, pylint file.py).
I'm not going to refactor your code too much, but you need to check for 'done' before converting to a float. And you'll want to catch ValueErrors incase somebody enters an invalid answer and handle it gracefully.
print("Enter the homework scores one at a time. Type \"done\" when finished. Ctrl+c to quit at any time.")
hwCount = 1
totalScore = 0
try:
while True:
strScore = input("Enter HW#" + str(hwCount) + " score: ")
if strScore == 'done':
break #done
else:
try:
strScore = float(strScore)
except ValueError:
print('Invalid input: must be a numerical score or "done"')
continue
if (strScore == int (strScore) and strScore >=0 and strScore <=10):
totalScore = totalScore + (strScore)
hwCount = hwCount + 1
elif ( strScore == int (strScore) and( strScore < 0 or strScore > 10)):
print ("Please enter a number between 0 and 10.")
elif strScore != "done":
print ("Please enter only whole numbers.")
except KeyboardInterrupt:
pass #done
Heres a more complete version of your program, for reference. It's how I would have refactored it.
#!/usr/bin/env python3
def findmode(lst):
bucket = dict.fromkeys(lst, 0)
for item in lst:
bucket[item] += 1
return max((k for k in bucket), key=lambda x: bucket[x])
print("Enter the homework scores one at a time.")
print("Type 'done' when finished or ctrl+c to quit.")
scores = []
try:
while True:
strScore = input("Enter score: ")
if strScore == 'done':
break #done
else:
try:
strScore = int(strScore)
except ValueError:
print('Invalid input: must be a score or "done"')
continue
if (0 <= strScore <= 10):
scores.append(strScore)
else:
print("Please enter a valid score between 0 and 10.")
except KeyboardInterrupt:
pass # user wants to quit, ctrl+c
finally:
print("Total scores graded: {}".format(len(scores)))
print("Highest score: {}".format(max(scores)))
print("Lowest score: {}".format(min(scores)))
print("Mean score: {}".format(sum(scores)/len(scores)))
print("Mode score: {}".format(findmode(scores)))