Budget tracker program not working in Linux - python

I am trying to improve this program. I am working with Linux. I want to add a menu function where the user can pick an option and based on the option call the respective function, but the program is not working, when I run it in the Terminal it doesn't do anything and doesn't show any errors. Please, I need help to solve the problem and make the program works. Thanks!
Here's what I have so far, still there are some functions that need to develop:
#! /usr/bin/python3
import sys
def menu(self):
print ("""
1. Add an Expense
2. Remove an Expense
3. Add revenue
4. Remove Revenue
5. Exit
""")
option = input ("What would you like to do [Number Only]?")
if option == "1":
self.add_expense()
elif option == "2":
self.remove_expense()
elif option == "3":
self.add_revenue()
elif option == "4":
self.remove_revenue()
else:
self.reset_program()
self.close_program()
return option
def add_expense(self):
def __init__(self):
self.month_balance = 0
self.expenses = 0
self.expense_list = []
self.expense_name = []
self.month_balance_name = []
self.month_balance_list = []
self.prompt_income()
def month_balance_ask(self):
add_month_balance = input('Add monthly balance? [y/n]: ')
return add_month_balance
def month_balance_sum(self):
self.month_balance = sum(self.month_balance_list)
def expense_ask(self):
add_expense = input('Add expense? [y/n]: ')
return add_expense
def expense_sum(self):
self.expenses = sum(self.expense_list)
def month_balance_check(self):
if not self.month_balance_list:
print('Please enter at least one monthly balance. ')
self.prompt_month_balance()
def expense_check(self):
if not self.expense_list:
print('Please enter at least one expense. ')
self.prompt_expense()
def prompt_month_balance(self):
x = False
while not x:
result = self.month_balance_ask()
if result == 'y':
month_balance_input = int(input('Enter monthly balance. [Numbers Only]: '))
self.month_balance_list.append(month_balance_input)
month_balance_name = input('Enter monthly balance name. [Name Only]: ')
self.month_balance_name.append(month_balance_name)
else:
self.month_balance_check()
x = True
self.month_balance_sum()
name = [name for name in self.month_balance_name]
month_balance = [month_balance for month_balance in self.month_balance_list]
month_balancedict = dict(zip(name, month_balance))
for k in incomedict:
print(k + ': ', '$' + str(month_balancedict[k]))
print('Total user monthly balance: ', '$' + str(self.month_balance))
self.prompt_expense()
def prompt_expense(self):
x = False
while not x:
result = self.expense_ask()
if result == 'y':
expense_input = int(input('Enter expense amount. [Numbers Only]: '))
self.expense_list.append(expense_input)
expense_name = input('Enter expense name. [Name Only]: ')
self.expense_name.append(expense_name)
else:
self.expense_check()
x = True
self.expense_sum()
name = [name for name in self.expense_name]
expense = [income for income in self.expense_list]
expensedict = dict(zip(name, expense))
for k in expensedict:
print(k + ': ', '$' + str(expensedict[k]))
print('Total user expenses: ', '$' + str(self.expenses))
self.added_expense()
def added_expense(self):
expenseadded = self.month_balance - self.expenses
if expenseadded < 0:
print('You are in the negative, you have a deficit of ' + '$' + str(expenseadded))
if expenseadded == 0:
print('You have broken even, you are spending exactly as much as you make.')
if expenseadded > 0:
print('You are in the positive, you have a surplus of ' + '$' + str(expenseadded))
another = input('Would you like to run another analysis? [y/n]: ')
if another == 'y':
self.menu()
else:
self.reset_program()
self.close_program()
def remove_expense(self):
print("code goes here")
def add_revenue(self):
print("code goes here")
def remove_revenue(self):
print("code goes here")
def reset_program(self):
self.month_balance = 0
self.expenses = 0
del self.expense_list[0:]
del self.expense_name[0:]
del self.month_balance_name[0:]
del self.month_balance_list[0:]
self.prompt_month_balance()
def close_program(self):
print('Exiting Program.')
sys.exit(0)

Related

Why is the menu of my program stuck in an infinite loop?

I'm creating a program so that a track coach can easily pull up runners times as well as input them.
I'm trying to figure out why when I start my program, it runs the function 'MENU', looping it.
user_input = 0
print('MENU')
print('1 - Add runner data to file')
print('2 - Display runners and their times')
print('3 - Calculate the average run time')
print('4 - Display the fastest time')
print('5 - EXIT')
print()
def MENU():
user_input = int(input('Enter your Menu choice >> '))
return -1
def DATA(f_runner, f_time):
f_runner = str(input('Enter runners name >> '))
f_time = str(input('Enter the runners time in hours >> '))
print('Runners data entered into the file.')
f = open('myFile.txt', 'w')
f.write(str(f_runner))
f.write(str(f_time))
f.close()
return f_runner, f_time
def DISPLAY():
contents = f.readlines()
f = open('myFile.txt')
print(contents)
runners_data = 0
runner = 0
runner_time = 0
average_time = 0
file_runner = ''
file_time = 0.0
contents = ''
program_exit = False
menu_start = 0
while program_exit == False:
menu_start = MENU()
while user_input > 0 and user_input < 6:
if user_input == '1':
DATA(file_runner, file_time)
elif user_input == '2':
Display()
elif user_input == '5':
program_exit = True
You are returning -1 instead of user_input in MENU()
Alongside what Samraj said, I believe it's also because your if statement is comparing if the user input is returned as a string, when you're expecting the user to return an int.
You could just remove it from the bottom and have it run inside menu and just call MENU().
Try this and edit it to what you need
print('MENU')
print('1 - Add runner data to file')
print('2 - Display runners and their times')
print('3 - Calculate the average run time')
print('4 - Display the fastest time')
print('5 - EXIT')
print()
def MENU():
the_input = int(input('Enter your Menu choice >> '))
if the_input == 1:
print("hello")
DATA(file_runner, file_time)
elif the_input == 2:
Display()
elif the_input == 5:
exit()
return the_input
def DATA(f_runner, f_time):
f_runner = str(input('Enter runners name >> '))
f_time = str(input('Enter the runners time in hours >> '))
print('Runners data entered into the file.')
f = open('myFile.txt', 'w')
f.write(str(f_runner))
f.write(str(f_time))
f.close()
return f_runner, f_time
def DISPLAY():
contents = f.readlines()
f = open('myFile.txt')
print(contents)
runners_data = 0
runner = 0
runner_time = 0
average_time = 0
file_runner = ''
file_time = 0.0
contents = ''
program_exit = False
menu_start = 0
MENU()

I am getting an error if acc[0] == var[0]: TypeError: 'NoneType' object is not subscriptabl. how do I fix this?

I am writing a car rental program on python.
In this function I am trying to modify car details which are added in the details.txt file but I am getting an error "if acc[0] == var[0]:TypeError:'NoneType' object is not subscriptable"
how do I fix this error ?
def modifying():
global acc
exist = False
mod_file = open("details.txt")
count = 0
for s in mod_file:
var = s.split(",") # spilt the data into list
var[2] = var[2].strip()
if acc[0] == var[0]:
exist = True
break
count += 1
mod_file.close()
if exist != True:
print("!!! Can NOT Find The Data !!!")
elif exist == True:
s_list = []
mod_file = open("details.txt", "r")
for s in mod_file:
s = s.strip()
s_list.append(s)
mod_file.close
choice = "Y"
while choice == "Y":
print("\n===============================")
print("---------- MODIFY Cars ----------")
print("---------------------------------")
print("Select the details you wish to modify")
print("1. Type")
print("2. Manufactured Year")
print("3. details of the car")
print("4. car code")
print("5. Daily price rate ( USD $ )")
print("6. back")
while True:
try:
c = int(input("please select a number (1 - 5): "))
modify = ["Type", "Manufactured Year", "details of the car", "car code", "Daily price rate ( USD $ )"]
if c > 0 and c < 6:
new = input("\nType the New " + modify[c - 1] + ":")
var[c - 1] = new
temp = ",".join(var)
s_list[count] = temp
mod_file = open("details.txt", "w")
mod_file.write("")
mod_file.close()
count_file = 0
for s in range(len(s_list)):
mod_file = open("details.txt", "r")
for counting in mod_file:
count_file += 1
mod_file.close()
mod_file = open("details.txt", "a")
if count_file == 0:
mod_file.write(s_list[s])
else:
mod_file.write("\n")
mod_file.write(s_list[s])
mod_file.close()
print("\nDetails UPDATED")
be_exit = input("\nDo you want to modify again? (Y/N): ").upper()
if be_exit == "y":
choice = "y"
else:
modifying(acc)
elif c == 6:
modifying(acc)
else:
print("\n!!! Incorrect Input !!!\n")
continue
except:
print("\n!! NOT a Number !!!\n")
continue
modifying()
You have to do
acc = some_value
def modifying():
global acc
exist = False
mod_file = open("details.txt")
count = 0
for s in mod_file:
var = s.split(",") # spilt the data into list
var[2] = var[2].strip()
if acc[0] == var[0]:
exist = True
break
In your example you haven't defined the variable acc. Using global just say that the variable is a global variable, but you're not assigning a value to it

Python elif statements are changing type from float to list

First time posting so apologizes if formatting is incorrect. My program has 2 lists for now. I I will be adding 4 more after solving this initial issue. One for and item the user selects, and a second with prices for the each item. I have written a code for user selection which runs.
My issue comes with the code for the program associating the item selected with the price list. My first if statement registers item_price as a float, which I gives me what I need. Item_price in the following elif statements are being seen as a list. How can I change them to a float so that the price prints instead of the list?
food=["burger", "pizza", "hotdogs", "tacos"]
food_price=[8.99, 22.50, 3.50, 6.00]
def get_menu_item(item,item_list,):
phrase = "Would you like" + item + "? [y/n] "
response = input(phrase)
if response == "y":
print("Here are your menu options:", item_list)
idx = input("please enter the item you would like from our menu[1,2,3,4]: ")
idx = int(idx) -1
return item_list[idx]
#if user selects [n]
else:
return (None)
#item price function
def get_item_price(item_price,item,item_list):
if item == item_list[0]:
item_price = item_price[0]
elif item == item_list[1]:
item_price == item_price[1]
elif item == item_list[2]:
item_price == item_price[2]
elif item == item_list[3]:
item_price == item_price[3]
return item_price
entree_choice = get_menu_item(" dinner",food)
print('You have selected: ' + entree_choice + ".")
entree_price = get_item_price(food_price,entree_choice,food)
print(entree_price)
I answered this for myself shortly after. I was using == instead of = for all of my elif statements. I feel dumb but writing this out helped me solve it.
You could simplify things further by using a dictionary to store your data :
food_price = {"burger":8.99, "pizza":22.50, "hotdogs":3.50, "tacos":6.00}
def get_menu_item(item,item_list,):
phrase = "Would you like" + item + "? [y/n] "
response = input(phrase)
if response == "y":
print("Here are your menu options:", item_list)
idx = input("please enter the item you would like from our menu[1,2,3,4]: ")
idx = int(idx) -1
return item_list[idx]
else:
return (None)
entree_choice = get_menu_item(" dinner",food)
print('You have selected: ' + entree_choice + ".")
# if entree_choice is not found in the food_price dictionary, the output becomes the string "Entree choice not available."
entree_price = food_price.get(entree_choice, "Entree choice not available.")
print(entree_price)

While loop not terminating when the condition has been satisified

While programming in Python I got stuck in a case where the while loop is not terminating even after the condition is being satisified then also
the code is as follows:
print('--- Alex\'s Calculator ---')
print('1. ADDition')
print('2. SUBstraction')
print('3. MULtiply')
print('4. DIVide')
print('5. EXIT')
x = int(input())
command = ' Enter Your Two numbers To Perform The Operation : '
def ini():
a = int(input())
b = int(input())
return a, b
def resultoo():
result = ' Your Result after Performing The Operation from {} and {} is {}'
print(result.format(a,b,c))
print(' Want To Continue If Yes then Enter Your Choice else Press any number exept 1 - 4')
x = int(input())
while x < 5:
if x == 1:
print(command)
a, b = ini()
c = a + b
resultoo()
elif x < 5:
break
As kuro specified in the comment, x can't be seen by your while loop because it's local to resultoo().
To solve it easily just add :
return x
at the end of resultoo()
and
x = resultoo()
in your while loop
You can use global var to this, change the this:
def resultoo():
result = ' Your Result after Performing The Operation from {} and {} is {}'
print(result.format(a,b,c))
print(' Want To Continue If Yes then Enter Your Choice else Press any number exept 1 - 4')
x = int(input())
into:
def resultoo():
global x
result = ' Your Result after Performing The Operation from {} and {} is {}'
print(result.format(a,b,c))
print(' Want To Continue If Yes then Enter Your Choice else Press any number exept 1 - 4')
x = int(input())
Explnation:
x is a global argument, that will be the same out of the function closure, but not inside of it, the function has it own params, so if you want to change a global argument that is initalizing outside the function, you will need to call the global statement before, that will make x the global x
When option 5 is entered you want to exit.
I added
import sys
and changed
elif x < 5:
to
elif x == 5:
and added
sys.exit(0)
I also added the getMenu() function
This is the complete code that is working in my editor:
import sys
def ini():
command = ' Enter Your Two numbers To Perform The Operation : '
print(command)
a = int(input())
b = int(input())
return a, b
def resultoo(a, b, c):
result = ' Your Result after Performing The Operation from {} and {} is {}'
print(result.format(a, b, c))
def getMenu(x):
if x == 0:
print("Choose menu item")
x = int(input())
elif x != 0:
print(' Want To Continue If Yes then Enter Your Choice else Press any number exept 1 - 4')
x = int(input())
return x
def main():
x = 0
while x < 5:
print('\n\n1. ADDition')
print('2. SUBstraction')
print('3. MULtiply')
print('4. DIVide')
print('5. EXIT\n')
x = getMenu(x)
if x == 1:
a, b = ini()
c = a + b
resultoo(a, b, c)
elif x == 5:
sys.exit(0)
else:
print("No valid menu item")
if __name__ == '__main__':
print('----------------------------------------------------------------------------------------------------------')
print('-------------------------------------------- Alex\'s Calculator -------------------------------------------')
main()
I also formatted your code (alt+Enter in Pycharm) to comply to PEP8 standards ;)

Python making GUI windows

I wrote a program that makes 3 things which user may choose:
def createLeague(): #creates a list with all teams
file = open('league1.txt', 'r')
teams = []
for line in file:
team = line.split()
teams.append(team)
file.close()
return teams
def getTeam(teams): #this function gets a team that user inputs
result = ' '
choice = input('Enter the team: ')
checkforteam = False
for line in teams:
team = line[0]
if choice == team: #check for input team in all lines
result = team
games = line[1]
wins = line[2] #assign all statistics to the variables with
draws = line[3] #appropriate names
loses = line[4]
checkforteam = True
if checkforteam: #if it is True, it will return the team. If False, returns an error message
print(result, games, wins, draws, loses)
else:
print('No such a team')
def getWinner(teams): #returns a leader
winner = ' '
result = 0
loses = 100
for team in teams:
points = int(team[2])*3 + int(team[3])
lose = int(team[4])#counting all points
if points > result: #find a team with maximum points
result = points
winner = team[0]
loses = lose
elif points == result:
if lose < loses:
winner = team[0]
print('Winner: ', winner)
print('Points: ', result)
def updateScore(teams): #update the table
firsteam = input('Home: ')
secondteam = input('Away: ')
goal1 = int(input('Goals scored by home: '))
goal2 = int(input('Goals scored by away: '))
f = open('nhl.txt', 'w')
for team in teams:
komanda = team[0]
matches = int(team[1])
wins = int(team[2])
draws = int(team[3])
loses = int(team[4])
if firsteam == komanda:
if goal1 > goal2:
matches += 1
wins += 1
elif goal1 == goal2:
matches += 1
draws += 1
else:
matches += 1
loses += 1
elif secondteam == komanda:
if goal1 < goal2:
matches += 1
wins += 1
elif goal1 == goal2:
matches += 1
draws += 1
else:
matches += 1
loses += 1
newline = komanda+ ' '+ str(matches) + ' ' +str(wins)+ ' '+ str(draws) + ' '+ str(loses)+ '\n'
f.write(newline)
f.close()
print('Saved')
teams = createLeague()
loop = 1 #variable that makes 'while' working until user wants to close the program
while loop == 1:
print('0. Exit')
print('1. Find a team')
print('2. Get a leader')
print('3. Update the results')
x = input('Choose: ')
if x == '1':
getTeam(teams)
elif x == '2':
getWinner(teams)
elif x == '3':
updateScore(teams)
elif x == '0':
print('Goodbye!')
loop = 0
else:
print('Wrong!')
Now I want that when I choose 1, 2 or 3 in IDLE, there will be a GUI window appeared where the function that called in while loop will work. I am stucked about it. How I can do it? Please, just show an example for one of the function.

Categories

Resources