Jump to content

 

Currently my code will ask for a barcode, once you input a barcode and it's listed it'll ask how many you want and print out how much it'll cost I need to be able for it to ask if you want to input another barcode and it see if it's listed and if it is ask how many you want then add up both prices and ask it if you want to want to add more items (barcode) if the answer is no then it'll print the price all together, how do I do that?

 

import math
def text(line):
    with open("Text.txt","r") as f:
        lines = f.readlines()
        x = lines[line]
        y = lines[line+1]
        print(x)
        ask = int(input("How many would you want: "))
        print("That's a total of £",int(y)*ask)
def roundup(x):
    return int(math.ceil(x /10)) * 10
while True:
    strStock = input("Please input ID: ")
    intStock = 1
    try:
        intStock = int(intStock)
        if (len(strStock) == 7) or (len(strStock) == 8):
            total = int(strStock[0])*3+int(strStock[1])+int(strStock[2])*3+int(strStock[3])+int(strStock[4])*3+int(strStock[5])+int(strStock[6])*3
            rounded = roundup(total)
            digit8 = rounded - total
            if len(strStock) == 8:
                if int(strStock[7]) == digit8:
                    print("This is a correct 8 Digit Barcode!")
                    if strStock   == "34512340": text(0)
                    elif strStock == "98981236": text(2)
                    elif strStock == "56756777": text(4)
                    elif strStock == "90673412": text(6)
                    else: print("Barcode not listed!")
                else:   print("Incorrect Barcode! The check digit should be " + str(digit8) + ".")
            else:   print("The check digit is " + str(digit8) + ".")
        else:   print("Please input a correct length barcode.")
    except ValueError:  print ("Thats not an integer!")

 

 

Edited by alpenwasser
Fixed messed up code thingy :)
Link to comment
https://linustechtips.com/topic/540941-able-to-save-python-335/
Share on other sites

Link to post
Share on other sites

4 hours ago, mattonfire said:

 

You already have a loop that asks for barcodes so you are good with that, you just need to return price from your text function and store in a variable (first declare it and define as 0 then when you getting price from text function add it up to this variable).

If I would do that I would load items list to dictionary and then insted ifs and elifs I would just look if barcode exists by checking if dict has key defined by strStock. If python does it right by it is way faster, to implement and to compute because of binary search. So your barcode would be key of dictionary and value would be price of product.

Link to comment
https://linustechtips.com/topic/540941-able-to-save-python-335/#findComment-7164363
Share on other sites

Link to post
Share on other sites

2 hours ago, Mr_KoKa said:

You already have a loop that asks for barcodes so you are good with that, you just need to return price from your text function and store in a variable (first declare it and define as 0 then when you getting price from text function add it up to this variable).

If I would do that I would load items list to dictionary and then insted ifs and elifs I would just look if barcode exists by checking if dict has key defined by strStock. If python does it right by it is way faster, to implement and to compute because of binary search. So your barcode would be key of dictionary and value would be price of product.

The only thing is that I can't save it and saving it to a directory/txt file is a little annoying, doesn't look to nice either.

Link to comment
https://linustechtips.com/topic/540941-able-to-save-python-335/#findComment-7165287
Share on other sites

Link to post
Share on other sites

19 hours ago, Mr_KoKa said:

What do you want to save actually? I forgot about saving because you only mention it in your topic, but there is nothing about saving in your post.

Not save permanently, I mean temp. So they want to add barcode "123901823" and barcode "123891023" I need it to remember barcode 1 and the price. And then the price for barcode 2, when they stop asking to input barcodes it'll add up the prices.

Link to comment
https://linustechtips.com/topic/540941-able-to-save-python-335/#findComment-7170568
Share on other sites

Link to post
Share on other sites

Do you want to make possible for the user to add more barcodes and prices for them - like adding new product to database? Im kind of loosing what your app will be doing so let me guess:

 

User will be asked if he wants to add new product (its barcode and price) or choose existing product by barcode and count of product which price will sum up, right?

 

If so you would need to create a menu so user can choose what action he want to perform, which it would be adding new product or using barcode to add product to "basket" and summ it's price.

 

You're using many ifs right now to check if user entered existing barcode, it's hardcoded so you wont be able to add new barcodes right now in runtime. You would need use dictionary as I said above.

Link to comment
https://linustechtips.com/topic/540941-able-to-save-python-335/#findComment-7170942
Share on other sites

Link to post
Share on other sites

On 2/5/2016 at 3:49 PM, Mr_KoKa said:

-SNIP-

It's like shopping yes, they will input a barcode and it will ask if they want anymore barcodes (items) and then when they say they don't want to add anymore items it'll add up the cost and tell them.

 

I really need help quick, so if anyone has any idea's please help.

Edited by mattonfire
Link to comment
https://linustechtips.com/topic/540941-able-to-save-python-335/#findComment-7216143
Share on other sites

Link to post
Share on other sites

So make a file where you will have barcode:price, you would need to read from it to dictionary variable at application start, then make menu where user can choose what it want to do, either it is add new product or choose product to basket. Menu can be simple, lik choose 1 to add new product, choose 2 to add product to basket or choose 3 to checkout.

 

Your code looks ok, you would need just add menu and change your if-else tree to dictionary.

 

import os.path

def loadDatabase():
	if os.path.isfile('products.txt'):
		with open('products.txt') as f:
			lines = f.readlines();
		
		for line in lines:
			params = line.split(":");
			
			if len(params) == 3:
				
				try:
					barcode = int(params[0]);
					
					try:
						price = float(params[2]);
						
						if(not database.has_key(barcode)):
							database[barcode] = {'price': price, 'name': params[1]};
						else:
							print 'Database error, barcode', barcode, 'already exists in database.';
							
					except ValueError:
						print 'Database error, price', params[2], 'is not valid float value.';
						
				except ValueError:
					print 'Database error, barcode', params[0], 'is not valid int value.';
					
			else:
				print 'Database error, entry', line, 'has not enough parameters.';
		
		print('Database loaded.');

def saveDatabase():
	with open('products.txt', 'w') as f:
		for barcode, product in database.items():
			f.write("{0}:{1}:{2}\n".format(barcode, product['name'], product['price']));
			
	print('Database saved.')

def listProducts():
	for barcode, product in database.items():
		print '{0} {1} - {2}'.format(barcode, product['name'], product['price']);
		
def addProductToDatabase():
	print('TODO add product to database, adding banana as a test.');
	#You would need to code your own function that will ask user for barcode, name and price for new product
	#and remember to check those values as I check them when read from database by surrounding convertion by try except block
	#for now lets add new product hardcoded way so we can check if saveDatabase works
	database['12344321'] = {'name': 'banana', 'price': 4.25}
	
def addProductToBasket():
	barcode = raw_input('Enter barcode of product you want to add to your basket: ');
	
	try:
		barcode = int(barcode)
		
		if(database.has_key(barcode)):
			count = raw_input('Enter how many of product you want to add to your basket: ');
			
			try:
				count = int(count);
				
				if count > 0:
					if basket.has_key(barcode):
						basket[barcode] += count;
					else:
						basket[barcode] = count;
			except ValueError:
				print count, 'is not valid number';
			
		else:
			print barcode, 'doesn\'t exist in database.';
	except ValueError:
		print barcode, 'is not valid barcode.';

def listBasket():
	print 'Your basket contains:'
	for barcode, count in basket.items():
		print '{0} of {1} - ${2}'.format(count, database[barcode]['name'], (database[barcode]['price'] * count));
	
def checkout():
	print('TODO checkout');
	# You can implement checkout functiuon like listBasket function but actually summ up all (price * count)s together.
	
menu = 0;
basket = {};
database = {};

loadDatabase();

while(menu != 5):
	print('1 - Add new product to database.');
	print('2 - List database.');
	print('3 - Add new product to basket.');
	print('4 - List basket.');
	print('5 - Checkout.');
	
	
	menu  = raw_input(': ');
	try:
		menu = int(menu)
	except ValueError:
		print menu, 'is not valid number.';
		
	if(menu == 1):
		addProductToDatabase();
		saveDatabase();
	elif(menu == 2):
		listProducts();
	elif(menu == 3):
		addProductToBasket();
	elif(menu == 4):
		listBasket();
	elif(menu == 5):
		checkout();
	else:
		print menu, 'is not valid menu item.';
		
	

You still have some functions to implement.

Link to comment
https://linustechtips.com/topic/540941-able-to-save-python-335/#findComment-7217262
Share on other sites

Link to post
Share on other sites

16 hours ago, Mr_KoKa said:

So make a file where you will have barcode:price, you would need to read from it to dictionary variable at application start, then make menu where user can choose what it want to do, either it is add new product or choose product to basket. Menu can be simple, lik choose 1 to add new product, choose 2 to add product to basket or choose 3 to checkout.

 

Your code looks ok, you would need just add menu and change your if-else tree to dictionary.

 


import os.path

def loadDatabase():
	if os.path.isfile('products.txt'):
		with open('products.txt') as f:
			lines = f.readlines();
		
		for line in lines:
			params = line.split(":");
			
			if len(params) == 3:
				
				try:
					barcode = int(params[0]);
					
					try:
						price = float(params[2]);
						
						if(not database.has_key(barcode)):
							database[barcode] = {'price': price, 'name': params[1]};
						else:
							print 'Database error, barcode', barcode, 'already exists in database.';
							
					except ValueError:
						print 'Database error, price', params[2], 'is not valid float value.';
						
				except ValueError:
					print 'Database error, barcode', params[0], 'is not valid int value.';
					
			else:
				print 'Database error, entry', line, 'has not enough parameters.';
		
		print('Database loaded.');

def saveDatabase():
	with open('products.txt', 'w') as f:
		for barcode, product in database.items():
			f.write("{0}:{1}:{2}\n".format(barcode, product['name'], product['price']));
			
	print('Database saved.')

def listProducts():
	for barcode, product in database.items():
		print '{0} {1} - {2}'.format(barcode, product['name'], product['price']);
		
def addProductToDatabase():
	print('TODO add product to database, adding banana as a test.');
	#You would need to code your own function that will ask user for barcode, name and price for new product
	#and remember to check those values as I check them when read from database by surrounding convertion by try except block
	#for now lets add new product hardcoded way so we can check if saveDatabase works
	database['12344321'] = {'name': 'banana', 'price': 4.25}
	
def addProductToBasket():
	barcode = raw_input('Enter barcode of product you want to add to your basket: ');
	
	try:
		barcode = int(barcode)
		
		if(database.has_key(barcode)):
			count = raw_input('Enter how many of product you want to add to your basket: ');
			
			try:
				count = int(count);
				
				if count > 0:
					if basket.has_key(barcode):
						basket[barcode] += count;
					else:
						basket[barcode] = count;
			except ValueError:
				print count, 'is not valid number';
			
		else:
			print barcode, 'doesn\'t exist in database.';
	except ValueError:
		print barcode, 'is not valid barcode.';

def listBasket():
	print 'Your basket contains:'
	for barcode, count in basket.items():
		print '{0} of {1} - ${2}'.format(count, database[barcode]['name'], (database[barcode]['price'] * count));
	
def checkout():
	print('TODO checkout');
	# You can implement checkout functiuon like listBasket function but actually summ up all (price * count)s together.
	
menu = 0;
basket = {};
database = {};

loadDatabase();

while(menu != 5):
	print('1 - Add new product to database.');
	print('2 - List database.');
	print('3 - Add new product to basket.');
	print('4 - List basket.');
	print('5 - Checkout.');
	
	
	menu  = raw_input(': ');
	try:
		menu = int(menu)
	except ValueError:
		print menu, 'is not valid number.';
		
	if(menu == 1):
		addProductToDatabase();
		saveDatabase();
	elif(menu == 2):
		listProducts();
	elif(menu == 3):
		addProductToBasket();
	elif(menu == 4):
		listBasket();
	elif(menu == 5):
		checkout();
	else:
		print menu, 'is not valid menu item.';
		
	

You still have some functions to implement.

I get quite a few syntax errors.

Link to comment
https://linustechtips.com/topic/540941-able-to-save-python-335/#findComment-7222903
Share on other sites

Link to post
Share on other sites

4 hours ago, mattonfire said:

I get quite a few syntax errors.

It's may be because of our python versions differs. Mine is 2.7.10. You can give me yours (run python --version).

 

Edit: Dang it, I just realized it is in thread title... I will update and see what is up.

Edit2: Here is code for python3.3

 

import os.path

def loadDatabase():
	if os.path.isfile('products.txt'):
		with open('products.txt') as f:
			lines = f.readlines();
		
		for line in lines:
			params = line.split(":");
			
			if len(params) == 3:
				
				try:
					barcode = int(params[0]);
					
					try:
						price = float(params[2]);
						
						if(not barcode in database):
							database[barcode] = {'price': price, 'name': params[1]};
						else:
							print('Database error, barcode {0} already exists in database.'.format(barcode));
							
					except ValueError:
						print('Database error, price {0} is not valid float value.'.format(params[2]));
						
				except ValueError:
					print('Database error, barcode {0} is not valid int value.'.format(params[0]));
					
			else:
				print('Database error, entry {0} has not enough parameters.'.format(line));
		
		print('Database loaded.');

def saveDatabase():
	with open('products.txt', 'w') as f:
		for barcode, product in database.items():
			f.write("{0}:{1}:{2}\n".format(barcode, product['name'], product['price']));
			
	print('Database saved.')

def listProducts():
	for barcode, product in database.items():
		print('{0} {1} - {2}'.format(barcode, product['name'], product['price']));
		
def addProductToDatabase():
	print('TODO add product to database, adding banana as a test.');
	#You would need to code your own function that will ask user for barcode, name and price for new product
	#and remember to check those values as I check them when read from database by surrounding convertion by try except block
	#for now lets add new product hardcoded way so we can check if saveDatabase works
	database['12344321'] = {'name': 'banana', 'price': 4.25}
	
def addProductToBasket():
	barcode = input('Enter barcode of product you want to add to your basket: ');
	
	try:
		barcode = int(barcode)
		
		if(barcode in database):
			count = input('Enter how many of product you want to add to your basket: ');
			
			try:
				count = int(count);
				
				if count > 0:
					if(barcode in basket):
						basket[barcode] += count;
					else:
						basket[barcode] = count;
			except ValueError:
				print('{0} is not valid number'.format(count));
			
		else:
			print("{0}, doesn't exist in database.".format(barcode));
	except ValueError:
		print('{0} is not valid barcode.'.format(barcode));

def listBasket():
	print('Your basket contains:')
	for barcode, count in basket.items():
		print('{0} of {1} - ${2}'.format(count, database[barcode]['name'], (database[barcode]['price'] * count)));
	
def checkout():
	print('TODO checkout');
	# You can implement checkout functiuon like listBasket function but actually summ up all (price * count)s together.
	
menu = 0;
basket = {};
database = {};

loadDatabase();

while(menu != 5):
	print('1 - Add new product to database.');
	print('2 - List database.');
	print('3 - Add new product to basket.');
	print('4 - List basket.');
	print('5 - Checkout.');
	
	
	menu  = input(': ');
	try:
		menu = int(menu)
	except ValueError:
		print('{0} is not valid number.'.format(menu));
		
	if(menu == 1):
		addProductToDatabase();
		saveDatabase();
	elif(menu == 2):
		listProducts();
	elif(menu == 3):
		addProductToBasket();
	elif(menu == 4):
		listBasket();
	elif(menu == 5):
		checkout();
	else:
		print('{0} is not valid menu item.'.format(menu));
		
	

 

Edited by Mr_KoKa
Added Python3.3 code
Link to comment
https://linustechtips.com/topic/540941-able-to-save-python-335/#findComment-7223646
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×