How to get a variable to keep a running total on Python? - 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")

Related

An attribute error appeared when I tried to make a code allowing a user to create their own record

I am trying to allow a user to create their own record and output their record. When I run my code this message appears:
File "filename", line 25, in
record = user_class(fact_list)
File "filename", line 17, in init
self.feild_list[i]=feild_list[i]
AttributeError: 'user_class' object has no attribute 'feild_list'
This is my code:
user_list = []
choice=input("Enter choice (Y/N):")
if choice == "Y":
feild_list = []
record_length = int(input("Enter record length:"))
for i in range(record_length):
feild = input("Enter a feild:")
feild_list.append(feild)
class user_class():
def __init__(self, feild_list):
for i in range(record_length):
self.feild_list[i]=feild_list[i]
fact_list = []
for i in range(len(feild_list)):
fact = input("Enter a fact:")
fact_list.append(fact)
record = user_class(fact_list)
user_list.append(record)
print(user_list)
choice=input("Enter choice (Y/N):")
elif choice == "N":
print("Program Ended.")
else:
while choice != "Y" or choice != "N":
print("Invalid choice")
choice = input("Enter choice (Y/N):")
In user_class.__init__() you don't have a self.feild_list variable. I assume you want one (see below). Alternatively you could just clone the list self.feild_list = feild_list[:].
user_list = []
choice = input("Enter choice (Y/N):")
if choice == "Y":
feild_list = []
record_length = int(input("Enter record length:"))
for i in range(record_length):
feild = input("Enter a feild:")
feild_list.append(feild)
class user_class():
def __init__(self, feild_list):
self.feild_list = []
for i in range(record_length):
self.feild_list.append(feild_list[i])
fact_list = []
for i in range(len(feild_list)):
fact = input("Enter a fact:")
fact_list.append(fact)
record = user_class(fact_list)
user_list.append(record)
print(user_list)
choice = input("Enter choice (Y/N):")
elif choice == "N":
print("Program Ended.")
else:
while choice != "Y" and choice != "N":
print("Invalid choice")
choice = input("Enter choice (Y/N):")
Also fixed the logic error in the choice retry. Consider moving that retry logic to the start so always get a valid choice:
while True:
choice = input("Enter choice (Y/N):")
if choice in "NY":
break
print("Invalid choice")

Can't find a way to incorporate addition, division, subtraction and multiplication inside of my small game

I am trying to use the variables user_ans_a, user_ans_s, user_ans_m and user_ans_d inside of my game as questions randomly chosen by python. My dilemma is coming from matching the randomly chosen variable to an answer coresponding to that variable. I want the user to be able to enter an anser to those questions.
import random
import re
while True:
score = 0
top = "--- Mathematics Game ---"
print(len(top) * "━")
print(top)
print(len(top) * "━")
print(" Type 'Play' to play")
start_condition = "Play" or "play"
def checkint(input_value):
while True:
try:
x = int(input(input_value))
except ValueError:
print("That was a bad input")
else:
return x
while True:
inp = input()
if inp == "Play":
break
else:
print("Try again")
if inp == "Play":
print("What's your name?")
name = input()
print(f"Hello {name}")
while True:
try:
no_of_rounds = int(input("how many rounds do you want to play? "))
break
except ValueError:
print('Please enter a number.')
for i in range(no_of_rounds):
ran_int1 = (random.randint(1,10))
ran_int2 = (random.randint(1,10))
answer_a = (ran_int1 + ran_int2)
answer_s = (ran_int1 - ran_int2)
answer_m = (ran_int1 * ran_int2)
answer_d = (ran_int1 / ran_int2)
user_ans_a = (f"What does {ran_int1} + {ran_int2} = ")
user_ans_s = (f"What does {ran_int1} - {ran_int2} = ")
user_ans_m = (f"What does {ran_int1} * {ran_int2} = ")
user_ans_d = (f"What does {ran_int1} / {ran_int2} = ")
if checkint(user_ans_a) == int(answer_a):
print(f"That was correct {name}.")
score = score+1
else:
print(f"Wrong {name}, the answer was {answer_a}, try again")
print(f"Score was {score}")
while True:
answer = str(input('Run again? (y/n): '))
if answer in ('y', 'n'):
break
print("invalid input.")
if answer == 'y':
continue
else:
print("Goodbye")
break

Unable to pass/exit a python function

Just starting out with python functions (fun_movies in functions.py) and I can't seem to get out (via "no" or False) once in the loop:
main_menu.py
from functions import *
def menu():
print("Press 1 for movies.")
print("Press 2 to exit.")
menu()
option = int(input("Input a number: "))
while option != 0:
#try:
if option == 1:
fun_movies()
elif option == 2:
print("Goodbye! ")
break
else:
print ("Wrong input")
functions.py
global movies
movies = {}
def fun_movies():
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies [name] = [genre]
a = True
while a:
query = input("Do you want to input another movie? (yes/no) ")
if query == "yes":
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies_if = {}
movies_if [name] = [genre]
movies.update(movies_if)
elif query == "no":
break
else:
print ("Wrong input!")
return movies
Code works fine when not called via import. When called via import (in main_menu.py), it keeps asking for infinite movies even when I input a "no". I can't find a way to exit the loop. Initially I had a "pass" but that didn't work.
Thanks in advance!
global movies
movies = {}
def fun_movies():
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies [name] = [genre]
a = True
while a:
query = input("Do you want to input another movie? (yes/no) ")
if query == "yes":
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies_if = {}
movies_if [name] = [genre]
movies.update(movies_if)
elif query == "no":
a = False
else:
print ("Wrong input!")
return movies
A few things:
Firstly, you don't need a==True as this statement returns True when a is True and False when a is False, so we can just use a as the condition.
Secondly, only use the input at the start of the loop as you want to ask once per iteration
Thirdly, place your return outside the loop so you only return when a==False and you don't want to input another movie.
edit:
main file>
from functions import *
def menu():
print("Press 1 for movies.")
print("Press 2 to exit.")
menu()
option = int(input("Input a number: "))
while option != 0:
if option == 1:
fun_movies()
elif option == 2:
print("Goodbye! ")
break
else:
print ("Wrong input")
option = int(input("Input a number"))
global movies
movies = {}
def fun_movies():
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies[name]= genre
a = True
while a:
query = input("Do you want to input another movie? (yes/no) ")
if query == "yes":
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies_if = {}
movies_if [name] = genre
movies.update(movies_if)
elif query == "no":
break
else:
print ("Wrong input!")
# continue
return movies
print(fun_movies())
Hope It works for you!

Question about the while loop for supermarket checkout case

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.

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')

Categories

Resources