Question about the while loop for supermarket checkout case - python

I tried to make simple codes for supermarket checkout, but I have an issue with the while loop statement. Please check the code below and picture I sent.
I don't know why after I input "n", it does not go back to the loop.
def start():
quan = 1
price = 0
end = False
total = 0
while end == False:
food = (input("Enter your food: "))
quan = int(input("Enter quantative: "))
price = float(input("Price of food: "))
disscount = float(input("Do you have disscount? enter '0' for no disccount. "))
end = input("Finish? y or n: ")
sum = price * quan
sub_total = sum - (sum * disscount * 0.01)
total += sub_total
if end == "y":
print("Total price is ", total)
end = True
elif end == "n":
end = False
else:
again = input("Wrong message! Do you want to try again? enter 'y' to try again or 'n' to end: ")
if again == "y":
return start()
elif again == "n":
print("Bye!")
break
start()

The if again block needs to be indented:
else:
again = input("Wrong message! Do you want to try again? enter 'y' to try again or 'n' to end: ")
if again == "y":
return start()
elif again == "n":
print("Bye!")
break
Otherwise, you hit your if statement without necessarily having defined again. If it is not defined, you get the error you cite.

Related

How to get a variable to keep a running total on Python?

I am trying to get this function take_input to add to the total whenever the function is run. However, I am unable to get the variable daily_expense to accumulate when an expense is added a second time.
def take_input():
daily_expense = 0
inp = int(input("How much did you spend?: "))
daily_expense += inp
print(f"Total expenses = {daily_expense}")
while True:
x = input("Add another expense? Y/N: ").lower()
if x == "y":
take_input()
elif x == "n":
break
else:
print("Please return a valid response")
def start_program():
start = input("Add expense? Y/N: ").lower()
if start == "y":
take_input()
start_program()
This is the working code
def take_input(daily_expense:int):
inp = int(input("How much did you spend?: "))
daily_expense += inp
print(f"Total expenses = {daily_expense}")
while True:
x = input("Add another expense? Y/N: ").lower()
if x == "y":
take_input(daily_expense)
elif x == "n":
break
else:
print("Please return a valid response")
def start_program():
daily_expense = 0
start = input("Add expense? Y/N: ").lower()
if start == "y":
take_input(daily_expense)
start_program()
You're currently defining daily_expense inside of the function; which means every time take_input() is called, you are resetting daily_expense to 0.
Instead, you should either define daily_expense outside of the function so it will no longer be reset each time; or you should accumulate it all within the loop and then print the final value, like so:
def take_input():
daily_expense = 0
more_expenses = input("Add expense? Y/N: ").lower()
while(more_expenses == "y"):
inp = int(input("How much did you spend?: "))
daily_expense += inp
more_expenses = input("Add expense? Y/N: ").lower()
if(more_expenses == "n"):
break
elif(more_expenses == "y"):
continue
else:
print("Please return a valid response")
more_expenses = input("Add expense? Y/N: ").lower()
print(f"Total expenses = {daily_expense}")
def start_program():
take_input()
start_program()
Edit:
Additional notes:
Every time this function is called, the value resets again and reaccumulates.
If you want to store this value in a database, then I recommend returning it and then using the returned value to update a database entry like so:
def take_input():
daily_expense = 0
more_expenses = input("Add expense? Y/N: ").lower()
while(more_expenses == "y"):
inp = int(input("How much did you spend?: "))
daily_expense += inp
more_expenses = input("Add expense? Y/N: ").lower()
if(more_expenses == "n"):
break
elif(more_expenses == "y"):
continue
else:
print("Please return a valid response")
more_expenses = input("Add expense? Y/N: ").lower()
print(f"Total expenses = {daily_expense}")
return daily_expense
def start_program():
save_this_number_to_db = take_input()
# store save this number into database
start_program()
Use a while loop instead of recursion to continually process user input.
def start_program():
daily_expense = 0
extra = ""
while 1:
x = input(f"Add {extra}expense? Y/N: ").lower()
if x == "y":
inp = int(input("How much did you spend?: "))
daily_expense += inp
print(f"Total expenses = {daily_expense}")
extra = "another "
elif x == "n":
break
else:
print("Please return a valid response")

removes the writing "none" in the python calculator

I just created a simple calculator program using python language, but there is a little problem here, when I end the program by inputting number 1, there is always the text none.
The question is how do I get rid of the text none in the program that I created? Because to be honest it is very annoying and will damage the image of the program that I created.
def pilihan():
i = 0
while i == 0:
print('\n\tWelcome to the Simple Calculator Program')
print("\nPlease Select Existing Operations", "\n1. subtraction", "\n2. increase", "\n3. division", "\n4. multiplication")
pilihan2 = int(input('Enter your choice (1/2/3/4): '))
if pilihan2 == 1:
angka1 = int(input('Enter the First Number: '))
angka2 = int(input('Enter the Second Number: '))
print(angka1, "-", angka2, "=", angka1 - angka2)
elif pilihan2 == 2:
angka1 = int(input('Enter the First Number: '))
angka2 = int(input('Enter the Second Number: '))
print(angka1, "+", angka2, "=", angka1 + angka2)
elif pilihan2 == 3:
angka1 = int(input('Enter the First Number: '))
angka2 = int(input('Enter the Second Number: '))
print(angka1, ":", angka2, "=", angka1 / angka2)
elif pilihan2 == 4:
angka1 = int(input('Enter the First Number: '))
angka2 = int(input('Enter the Second Number: '))
print(angka1, "x", angka2, "=", angka1 * angka2)
else:
print('Error option, please try again')
continue
print('Program finished, want to restart?')
y = 0
while y == 0:
ulang = int(input('Type 0 for YES and 1 for NO = '))
if ulang == 0:
y += 1
break
elif ulang == 1:
y += 2
break
else:
print('\nThe command you entered is an error, please try again')
continue
if y == 1:
continue
else:
break
print(pilihan())
Change the print(pilihan()) to pilihan(), the return value of pilihan() is None :)

Outer Loop of nest won't trigger

This is some of my homework but i am really stuck and can't find any advice online.
def main():
endProgram = 'n'
print()
while endProgram == 'n':
total = 0
totalPlastic = 0
totalMetal= 0
totalGlass = 0
endCount = 'n'
while endCount == 'n':
print()
print('Enter 1 for Plastic')
print('Enter 2 for Metal')
print('Enter 3 for Glass')
option = int(input('Enter now: '))
if option == 1:
totalPlastic = getPlastic(totalPlastic)
elif option == 2:
totalMetal = getMetal(totalMetal)
elif option == 3:
totalGlass = getGlass(totalGlass)
else:
print('You have entered an invalid input')
return main()
endCount = input('Do you want to calculate the total? (y/n): ')
print()
total = calcTotal(totalPlastic, totalMetal, totalGlass)
printNum(total)
break
endProgram = input('Do you want to end the program? (y/n): ')
def getPlastic(totalPlastic):
plasticCount = int(input('Enter the number of Plastic bottles you have: '))
totalPlastic = totalPlastic + plasticCount * .03
return totalPlastic
def getMetal(totalMetal):
metalCount = int(input('Enter the number of Metal cans you have: '))
totalMetal = totalMetal + metalCount * .05
return totalMetal
def getGlass(totalGlass):
glassCount = int(input('Enter the number of Glass bottles you have: '))
totalGlass = (totalGlass + glassCount * .10)
return totalGlass
def calcTotal(totalPlastic, totalMetal, totalGlass):
total = totalPlastic + totalMetal + totalGlass
return total
def printNum(total):
print('Your total recyclable value is $', total)
main()
My problem is I run the code and it works fine for 99% of it. The program will ask any type and amount of bottle, and it totals it correctly too, the issue is that the outer loop never gets asked. After it prints the total it just goes right back to asking what type of bottle you have instead of asking you whether or not you want to end the program. Any help is appreciated thanks.
Remove the break just before Do you want to end the program? (y/n)
print()
total = calcTotal(totalPlastic, totalMetal, totalGlass)
printNum(total)
break
Here you are using break and the loop gets out and does not go forward.
break is used in while loop endProgram == 'n' and it breaks and never goes forwards.
One more thing it is a bad habbit of making defining first. Always define main after the other functions and do not just call main().
Use this -
if(__name__ == '__main__'):
main()
The break statement was exiting your script, therefore your line endProgram = input('Do you want to end the program? (y/n): ') was unreachable, that is why it was never "asked".
Also, fixed some of your indentation, give it a go.
def main():
endProgram = 'n'
print()
while endProgram == 'n':
total = 0
totalPlastic = 0
totalMetal = 0
totalGlass = 0
endCount = 'n'
while endCount == 'n':
print()
print('Enter 1 for Plastic')
print('Enter 2 for Metal')
print('Enter 3 for Glass')
option = int(input('Enter now: '))
if option == 1:
totalPlastic = getPlastic(totalPlastic)
elif option == 2:
totalMetal = getMetal(totalMetal)
elif option == 3:
totalGlass = getGlass(totalGlass)
else:
print('You have entered an invalid input')
return main()
endCount = input('Do you want to calculate the total? (y/n): ')
print()
total = calcTotal(totalPlastic, totalMetal, totalGlass)
printNum(total)
endProgram = input('Do you want to end the program? (y/n): ')
def getPlastic(totalPlastic):
plasticCount = int(input('Enter the number of Plastic bottles you have: '))
totalPlastic = totalPlastic + plasticCount * .03
return totalPlastic
def getMetal(totalMetal):
metalCount = int(input('Enter the number of Metal cans you have: '))
totalMetal = totalMetal + metalCount * .05
return totalMetal
def getGlass(totalGlass):
glassCount = int(input('Enter the number of Glass bottles you have: '))
totalGlass = (totalGlass + glassCount * .10)
return totalGlass
def calcTotal(totalPlastic, totalMetal, totalGlass):
total = totalPlastic + totalMetal + totalGlass
return total
def printNum(total):
print('Your total recyclable value is $', total)
main()

Python array loop not looping/validator issues

I'm not exactly sure what I did, but when testing my code it either crashes immediately or gets stuck in a loop. If the first input is a value error (string) and the next is a number it loops as long as the pattern is kept. But if first user entry is int then program crashes. Please any help would be appreciated.
def main():
courseArray = []
keepGoing = "y"
while keepGoing == "y":
courseArray = getValidateCourseScore()
total = getTotal(courseArray)
average = total/len(courseArray)
print('The lowest score is: ', min(courseArray))
print('The highest score is: ', max(courseArray))
print('the average is: ', average)
keepGoing = validateRunAgain(input(input("Do you want to run this program again? (Y/n)")))
def getValidateCourseScore():
courseArray = []
counter = 1
while counter < 6:
try:
courseArray.append(int(input("Enter the number of points received for course: ")))
valScore(courseArray)
except ValueError:
print("Please enter a valid score between 0-100")
courseArray.append(int(input("Enter a number between 1 and 100: ")))
counter += 1
return courseArray
def valScore(courseArray):
score = int(courseArray)
if score < 0:
print("Please enter a valid score between 0-100")
courseArray.append(int(input("Enter a number between 1 and 100: ")))
elif score > 100:
print("Please enter a valid score between 0-100")
courseArray.append(int(input("Enter a number between 1 and 100: ")))
else:
return courseArray
def validateRunAgain(userInput):
if userInput == "n" or userInput == "N":
print("Thanks for using my program")
return "n"
elif userInput == "y" or userInput == "Y":
return "y"
else:
print("Please enter y or n")
validateRunAgain(input("Do you want to run this program again? (Y/n)"))
return getValidateCourseScore()
def getTotal(valueList):
total = 0
for num in valueList:
total += num
return total
main()
There are too many inputs from the user, so I have cut down on them and changed it.
Here are the sections of your code which I have changed :
Here valScore() I presume validates the input score so, I also gave the index of element to be validated. If it is not valid we remove it from the array and raise ValueError, since it raises error our counter is not updated.
keepGoing = validateRunAgain()
def getValidateCourseScore():
courseArray = []
counter = 1
while counter < 6:
try:
courseArray.append(int(input("Enter the number of points received for course: ")))
valScore(courseArray, counter - 1)
counter += 1
except ValueError:
print("Please enter a valid score between 0-100")
continue
return courseArray
def valScore(courseArray, counter):
score = courseArray[counter]
if score < 0 or score > 100:
courseArray.pop()
raise ValueError
def validateRunAgain():
while True:
userInput = input("Do you want to run this program again? (Y/n)")
if userInput == 'y' or userInput == 'Y':
return 'y'
elif userInput == 'n' or userInput == 'N':
print('thank you for using my program')
return 'n'
else:
print('Enter Y or N')

Trying to create a confirmation for my code so that it will allow user to change answer

I wanted to add a confirmation for my code so that the user will be able to change their input. I haven't yet added the loop for the question but for some reason when I run this it fails to run def calc() and therefore the calculations I created cannot continue. Help!!
n=0
x=0
while True:
numbers = input("Please enter a, b,c, or, d to select a equation")
if numbers == "a":
n =3
x = 2
break
elif numbers =="b":
n = 4
x = 5
break
elif numbers == "c":
n=5
x=6
break
elif numbers == "d":
n=6
x=7
break
else:
print("Please enter a,b,c, or d")
w = float(input("Please enter weight"))
choice = input("Is this your answer?")
if choice == "yes":
def calc():
if n > w :
weight = (x - w)
weight2 = weight/n
print(weight)
elif w < x:
weight = (w - x)
weight2 = weight/n
print(weight)
calc()
elif choice =="no":
print ("Lets change it")
else:
print("Please respond with 'yes' or 'no'")

Categories

Resources