Python not loading information correctly? - python

I don't understand. When I run the SaveModule.open function in this code, it's able to save ShoppingCart.items_in_cart in the correct variable correctly, but not users. Did I do something wrong in this code?
(I realize this might not be the most efficient code in the world, it's still a work in progress. Just trying to get everything working first.)
I tested this in the IDLE program, and everything worked the way it was supposed to, I just don't get what I did wrong here.
As for why I'm trying to do this, it's just a challenge I set for myself. Nothing more.
import os
import linecache
import ast
users = {}
logged_in = False
mspw = '00415564'
class ShoppingCart(object):
#Creates shopping cart objects for users of our fine website.
items_in_cart = {}
def __init__(self, customer_name):
self.customer_name = customer_name
def __repr__(self):
return(self.customer_name)
def __str__(self):
print('Hello ' + self.customer_name)
print('You have ' + str(len(self.items_in_cart)) + ' items in your cart.')
for item in self.items_in_cart:
print(' ' + item, self.items_in_cart[item])
return('Thank you for shopping at Job Simulator!')
def add_item(self, product, price):
#add a product to the cart
if not product in self.items_in_cart:
self.items_in_cart[product] = price
print(product + ' added.')
else:
print(product + ' is already in the cart.')
def change_price(self, product, price):
if product in self.items_in_cart:
self.items_in_cart[product] = price
print('Price Changed')
else:
print('Impossible!')
def change_item(self, product, newproduct):
if product in self.items_in_cart:
tempstor = self.items_in_cart[product]
del self.items_in_cart[product]
self.items_in_cart[newproduct] = tempstor
print('Item changed')
else:
print('Impossible')
def remove_item(self, product):
#Remove product from the cart.
if product in self.items_in_cart:
del self.items_in_cart[product]
print(product + ' removed.')
else:
print(product + ' is not in the cart.')
class UserModule(object):
def add_user(usnm, pswd):
if logged_in == False:
if not usnm in users:
users[usnm] = pswd
s = True
else:
s = False
else:
s = False
return s
def remove_user(usnm, pswd):
if logged_in == False:
if usnm in users:
if pswd == users[usnm]:
del users[usnm]
s = True
else:
s = False
else:
s = False
else:
s = False
return s
def check_users(mst):
if mst == mspw:
for item in users:
print(' ' + item, users[item])
else:
print('Need master password')
class SaveModule(object):
def save(file):
svflu = open(file + '.sbcu', 'w')
svfli = open(file + '.sbci', 'w')
svflu.truncate()
svfli.truncate()
svflu.write(str(users))
svfli.write(str(ShoppingCart.items_in_cart))
svflu.close()
svfli.close()
def open(file):
if os.path.isfile(file + '.sbcu') and os.path.isfile(file + '.sbci'):
svfl = open(file + '.sbcu', 'r')
users = ast.literal_eval(linecache.getline(file + '.sbcu', 1))
svfl.close()
svfl = open(file + '.sbci', 'r')
ShoppingCart.items_in_cart = ast.literal_eval(linecache.getline(file + '.sbci', 1))
svfl.close()
else:
print('This file doesn\'t exits.')

I fixed the problem; it was solved by nesting the users variable inside the UserModule module. I don't know why that fixed it; if anyone can answer that, then let me know.

Related

Budget tracker program not working in Linux

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)

how to past list to template

I am trying to pass this eligable list to my template so that I can display it in my website but when I run the website it says that local variable 'eligable' referenced before assignment. I dont understand because this is the only time I used the word eligable in my code.
code:
def specificDate(response):
empName = employeeName.objects.all
if 'checkEmployee' in response.POST:
n = response.POST.get("nameEmployee")
specDate = response.POST.get("date")
if employeeName.objects.filter(employee=n).exists() and Name.objects.filter(date=specDate).exists():
emp = employeeName.objects.get(employee=n)
t = Name.objects.get(name=emp, date=specDate)
overT = Name.objects.filter(name=emp, overtime=True)
eligable = []
for item in overT:
eligable.append(item.date)
print('Hello')
checkIn = t.timeIn.strftime("%H:%M:%S")
checkOut = t.timeOut.strftime("%H:%M:%S")
datee = datetime.strptime(specDate,'%Y-%m-%d')
print("Here:: ",t.date)
print("Month:: ",datee.month)
messages.info(response, checkIn + ' - ' + checkOut)
return redirect('/specificDate')
else:
messages.info(response, 'Name does not exist')
else:
pass
return render(response, "main/specificDate.html", context={"empName":empName, "eligable":eligable})
def specificDate(response):
empName = employeeName.objects.all
eligable = []
if 'checkEmployee' in response.POST:
n = response.POST.get("nameEmployee")
specDate = response.POST.get("date")
if employeeName.objects.filter(employee=n).exists() and Name.objects.filter(date=specDate).exists():
emp = employeeName.objects.get(employee=n)
t = Name.objects.get(name=emp, date=specDate)
overT = Name.objects.filter(name=emp, overtime=True)
eligable = []
for item in overT:
eligable.append(item.date)
print('Hello')
checkIn = t.timeIn.strftime("%H:%M:%S")
checkOut = t.timeOut.strftime("%H:%M:%S")
datee = datetime.strptime(specDate,'%Y-%m-%d')
print("Here:: ",t.date)
print("Month:: ",datee.month)
messages.info(response, checkIn + ' - ' + checkOut)
return redirect('/specificDate')
else:
messages.info(response, 'Name does not exist')
else:
pass
return render(response, "main/specificDate.html", context={"empName":empName, "eligable":eligable})
The error was correct to be there, because in cases where your control would not inside the if block, eligable list won't get intialized , so after encountering the last statement, it would raise the error.
The fix was to pre-initialize the list beforehand.

How to store the total withdrawal amount for each category object?

I have a Category class and there is a ledger attribute for each instance of this class. This ledger attribute is actually a list of dictionaries which contain the withdrawal and deposit amounts and descriptions in the form {"amount" : amount, "description" : description}. Now, I want to define a function create_spend_chart which will take a list of objects as the parameter, and will find the total amount of withdrawals. I have been able to do this successfully:
def create_spend_chart(categories):
total_withdrawn = 0
for i in categories:
for p in i.ledger:
if p["amount"] < 0:
total_withdrawn += -p["amount"]
But the problem I'm facing here is, I can't seem to store the total withdrawal amount for each category object separately. How can I do this?
My code-base might help you ins answering the question:
class Category:
def __init__(self, name):
self.name = name
self.ledger = list()
def get_balance(self):
total_balance = 0
for i in self.ledger:
total_balance += i["amount"]
return total_balance
def check_funds(self, amount):
if self.get_balance() >= amount:
return True
else:
return False
def deposit(self, amount, description = "Deposit"):
form = {"amount" : int(amount), "description" : description}
self.ledger.append(form)
def withdraw(self, amount, description = "Withdrawal"):
if description == None:
description = "Withdrawal"
form = {"amount" : -int(amount), "description" : description}
if self.check_funds(amount):
self.ledger.append(form)
return True
else:
return False
def transfer(self, amount, category_object):
form1 = {"amount" : -int(amount), "description" : f"Transfer to {category_object.name}"}
form2 = {"amount" : int(amount), "description" : f"Transfer from {self.name}"}
if self.check_funds(amount):
self.ledger.append(form1)
category_object.ledger.append(form2)
return True
else:
return False
def __repr__(self):
Ledger = ""
for i in self.ledger:
if len(i["description"]) > 23:
des = i["description"][:23]
else:
des = i["description"]
Ledger += des.ljust(23) + str(round(i["amount"], 2)).rjust(7) + "\n"
Ledger = Ledger + "Total: " + str(round(self.get_balance(), 2))
receipt = f"{self.name}".center(30, "*") + "\n" + Ledger
return receipt
def create_spend_chart(categories):
total_withdrawn = 0
withdrawals = list()
for i in categories:
for p in i.ledger:
if p["amount"] < 0:
total_withdrawn += -p["amount"]
PS: This function is not a method, it is defined outside of the class declaration.
Use a collections.defaultdict to make aggregations such as that easy as pie.
import collections
# ...
withdrawn_per_category = collections.defaultdict(int)
for i in categories:
for p in i.ledger:
if p["amount"] < 0:
withdrawn_per_category[i.name] += -p["amount"]
(I've opted to use int as the default data type, but it doesn't truly matter here, so long as it's a conversible numeric type.)
Without collections
If for some reason you don't want to use the handy, built-in collections module, you can emulate the same behavior yourself with a regular dict:
withdrawn_per_category = {}
for i in categories:
for p in i.ledger:
if p["amount"] < 0:
withdrawn_per_category[i.name] = withdrawn_per_category.get(i.name, 0) - p["amount"]

need help figuring out why method updating_sitting and custmor_increment are not adding and printing out the way they should

class Restaurant():
"""intalizing attributes rest._type and food_type"""
def __init__(self,resturant_type,*food_type):
self.rest_type = resturant_type
self.food = food_type
self.number_severd = 0
def opening(self):
"""Letting people know that the resturant is open"""
print(self.rest_type.title() + " is now open")
def describing_rest(self):
"""telling you about resturant"""
print("\nWelcome to " + self.rest_type.title() +
" here are what we have on the menu today: ")
for self.foods in self.food:
print("-" + self.foods)
def updating_sitting(self,new_chart):
"""updating sitting chart"""
self.number_served = new_chart
def custmor_increment(self,addition):
"""add number to custmor count"""
self.number_severd += addition
rest = Restaurant('High Spot','Turkey sandwich','pizza','deserts')
rest.opening()
rest.describing_rest()
rest.number_severd = 230
print("we have " + str(rest.updating_sitting(400)))
print("now we have " + str(rest.custmor_increment(100)))
i need help figuring out how to method updating_sitting to print out how many are sitting now
and for custmor_increment to print what the new amount of custmors there is.
To print how many are sitting, the methods need to return self.number_served.
You also need to fix the typos number_severd and your indentation.
class Restaurant():
def __init__(self,resturant_type,*food_type):
"""intalizing attributes rest._type and food_type"""
self.rest_type = resturant_type
self.food = food_type
self.number_served = 0
def opening(self):
"""Letting people know that the resturant is open"""
print(self.rest_type.title() + " is now open")
def describing_rest(self):
"""telling you about resturant"""
print("\nWelcome to " + self.rest_type.title() +
" here are what we have on the menu today: ")
for self.foods in self.food:
print("-" + self.foods)
def updating_sitting(self,new_chart):
"""updating sitting chart"""
self.number_served = new_chart
return self.number_served
def custmor_increment(self,addition):
"""add number to custmor count"""
self.number_served += addition
return self.number_served
rest = Restaurant('High Spot','Turkey sandwich','pizza','deserts')
rest.opening()
rest.describing_rest()
rest.number_served = 230
print("we have " + str(rest.updating_sitting(400)))
print("now we have " + str(rest.custmor_increment(100)))
BTW, the correct spelling of "custmor" is "customer"

loop instance method with list elements

I am trying to write a program (API testing) to loop through instance methods in a class. One of the methods "get_one_sale_license" has a variable "self.sale_sgid_in_test" I need to assign this variable each element in the list "sale_list_final" .The variable is used in the instance method as well as the main function. I put a for loop outside the class and it works fine with the output( this is modified part of a single file from the application using framework).
However, I want to remove the loop wrapping the class and try in a more pythonic way.
import json
from datetime import *
from N import NSession
from N import NArgParser
from i_data_provider import iDataProvider
sale_list = open("sales.txt").readlines()
sale_list_final = [s.rstrip() for s in sale_list]
tests_list = open("tests.txt").readlines()
tests_list_final = [t.rstrip() for t in tests_list]
cnt=0
cnt2=0
cnt3=0
cnt6=0
cnt11=0
for i in sale_list_final:
class iDeployChecks:
def __init__(self, badge, environment):
self.session = NSession(badge=badge,environment=environment)
self.logger = self.session.logger
# self.sale_sgid_list = []
self.sale_sgid_in_test = ''
self.i_session = iDataProvider(self.session)
def get_all_saleable_sales(self):
global cnt2
if cnt2 == 0:
self.i_session.get_sale_seller_info()
self.logger.info('SUCCESS..... Get all sales api\n')
cnt2 += 1
def get_all_sale_dashboard(self):
global cnt6
if cnt6 == 0:
self.i_session.get_All_sale()
self.logger.info('SUCCESS..... Get all sales on dashboard api\n')
cnt6 += 1
def get_current_user_sale_dashboard(self):
global cnt11
if cnt11 == 0:
self.i_session.get_current_user_sale()
self.logger.info('SUCCESS..... Get current sales on dashboard api\n')
cnt11 += 1
def get_one_sale_license(self):
self.logger.info('Getting sale details from:')
self.sale_sgid_list1 = [item.get('salesgid') for item in self.i_session.get_sale_seller_info()]
#self.sale_sgid_list =[item.get('salesgid') for item in self.i_session.get_sale_seller_info() if item.get('salesgid') == i]
print " for sale " + str(i)
self.sale_sgid_in_test = ''.join(i)
self.logger.info('\n')
self.logger.info('Get License for sale with sale sgid {}'.format(self.sale_sgid_in_test))
self.i_session.get_sale_license(self.sale_sgid_in_test)
self.logger.info('SUCCESS..... Get license api\n')
def get_weekly_stats_count(self):
global cnt
if cnt == 0:
self.i_session.get_weekly_statistics()
self.logger.info('SUCCESS..... Weekly statistics api\n')
cnt += 1
def get_sconfig_value_count(self):
self.i_session.get_sconfig_value(self.sale_sgid_in_test)
self.logger.info('SUCCESS..... sconfig api\n')
def main(self):
start = datetime.utcnow()
# check if the method in the list is present in the class, if yes run it.
for j in tests_list_final:
k = "self." + j + "()"
l= [x.strip() for x in j.split(',')]
m= "self."+l[0]+"(self,year)"
n= "self."+l[0]+"(self,year,month)"
if k == str("self.get_all_saleable_sales()"):
if cnt2 == 0:
self.logger.info('Get All sales')
self.get_all_saleable_sales()
self.logger.info('checking if sale with GSID ' + i + ' exists')
if i not in str(self.i_session.get_sale_seller_info()):
print "the sale with GSID " + i + " does not exist !!"
end1 = datetime.utcnow()
self.logger.info('i health check completed in {} seconds.'.format((end1 - start).seconds))
return
else:
print "sale exists !!"
continue
elif k == str("self.get_one_sale_license()"):
self.get_one_sale_license()
continue
elif k == str("self.get_sale_node_status_value()"):
try:
self.logger.info('Get sale node status for sale sgid {}'.format(self.sale_sgid_in_test))
self.get_sale_node_status_value()
except Exception as e: print e
else:
global cnt3
if (cnt3==0):
print '\n'
print " The testcase " +k + "test does not exist,please recheck test name !!"
print '\n'
cnt3 +=1
end = datetime.utcnow()
self.logger.info('IBDL health check completed in {} seconds.'.format((end - start).seconds))
if __name__ == '__main__':
parser = NArgParser(description='i Checks')
args = parser.parse_args()
iDeployChecks(args.badge, args.environment).main()
Remove the loop and include in the init
def __init__(self, badge, environment):
self.session = NSession(badge=badge,environment=environment)
self.logger = self.session.logger
self.sale_sgid_list = [i for i in sale_list_final]
self.sale_sgid_in_test = ''
self.i_session = iDataProvider(self.session)
Then loop for the same list element while calling the main
if __name__ == '__main__':
parser = NArgParser(description='i Checks')
args = parser.parse_args()
for i in sale_sgid_list:
iDeployChecks(args.badge, args.environment,i).main()

Categories

Resources