10

I'm relatively new to Python Programming, using Python 3.x, and am working on a Barbershop P.O.S system where the admin will have the privilege to add Services and their corresponding Prices. I'm using the Pretty Table library to achieve printing out a table with serviceID, service and price.

Here's my code:

from prettytable import PrettyTable
import random

serviceID = []
services = []
price = []
x = PrettyTable()

x.add_column("ServiceID",[serviceID])
x.add_column("Service", [services])
x.add_column("Price", [price])

while True:
try:

     ID = random.randint(1,90000) #range high to lower probability of non-uniqueness
     serviceID.append(ID) #Generates unique ID for each service
     prompt1 = input("Please add a service name to the list\n")
     services.append(prompt1)

     prompt2 = input("Please enter a price for the service\n")
     prompt2 == int(prompt2)
     price.append(prompt2)

     print(x)


except ValueError:
    print("Please enter valid type")
    continue

When I enter the first service and Price, the output is:

+-----------+---------+--------+
| ServiceID | Service | Price  |
+-----------+---------+--------+
|   [9880]  | ['box'] | ['90'] |
+-----------+---------+--------+

When I enter the 2nd service and price, the output is this:

+---------------+-----------------+--------------+
|   ServiceID   |     Service     |    Price     |
+---------------+-----------------+--------------+
| [9880, 47612] | ['box', 'trim'] | ['90', '80'] |
+---------------+-----------------+--------------+

I'd like the output to be this:

+---------------+-----------------+--------------+
|   ServiceID   |     Service     |    Price     |
+---------------+-----------------+--------------+
|  9880         |      box        |       90     |
|  47612        |     trim        |       80     |
+---------------+-----------------+--------------+

Does anyone know how to achieve this? Any help would be appreciated.

mabishi
  • 115
  • 1
  • 1
  • 8

2 Answers2

4

We can do by adding row into PrettyTable object by add_row method.

Demo:

>>> from prettytable import PrettyTable
>>> import random
>>> 
>>> x = PrettyTable(["ServiceID", "Service", "Price"])
>>> 
>>> while True:
...     #- Get value
...     ID = random.randint(1,90000) #range high to lower probability of non-uniqueness
...     prompt1 = raw_input("Please add a service name to the list\n")
...     try:
...         #- Type Casting.
...         prompt2 = int(raw_input("Please enter a price for the service\n"))
...     except ValueError:
...         print("Please enter valid type")
...         continue
...     #- Add row
...     x.add_row([ID, prompt1, prompt2])
...     #- Ask user to Continue or not.
...     choice = raw_input("Continue yes/ no:").lower()
...     if not(choice=="yes" or choice=="y"):
...         break
... 
Please add a service name to the list
2
Please enter a price for the service
3
Continue yes/ no:y
Please add a service name to the list
4
Please enter a price for the service
6
Continue yes/ no:y
Please add a service name to the list
5
Please enter a price for the service
7
Continue yes/ no:n
>>> print x
+-----------+---------+-------+
| ServiceID | Service | Price |
+-----------+---------+-------+
|   38515   |    2    |   3   |
|    8680   |    4    |   6   |
|   51188   |    5    |   7   |
+-----------+---------+-------+
>>> 

Delete Row:

Use del_row() method. We need to pass index of row which we want to remove.

>>> print x
+-----------+---------+-------+
| ServiceID | Service | Price |
+-----------+---------+-------+
|   38515   |    2    |   3   |
|    8680   |    4    |   6   |
|   51188   |    5    |   7   |
+-----------+---------+-------+
>>> x.del_row(1)
>>> print x
+-----------+---------+-------+
| ServiceID | Service | Price |
+-----------+---------+-------+
|   38515   |    2    |   3   |
|   51188   |    5    |   7   |
+-----------+---------+-------+

Need to handle exception if we provide index value greater then total rows in exception will raise, that need to handle in ur code.

Exception is:

>>> x.del_row(10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/prettytable.py", line 832, in del_row
    raise Exception("Cant delete row at index %d, table only has %d rows!" % (row_index, len(self._rows)))
Exception: Cant delete row at index 10, table only has 2 rows!

Note:

  1. Use raw_input() for Python 2.x

  2. Use input() for Python 3.x

Vivek Sable
  • 9,938
  • 3
  • 40
  • 56
  • Thanks Vivek and Padraic. How do I delete a row from the table? I've tried indexing the table like this del[2] but it doesn't work. – mabishi Apr 05 '16 at 12:15
  • @ElizabethMabishi: Use `del_row` method. pass index of row which we want to remove. I am adding in answer. – Vivek Sable Apr 05 '16 at 12:29
  • @janus-py, Vivek For my previous question, I found a way around accessing individual elements. This is what I did: def log_service(): while True: try: response3 = input("Please choose service from list using the ServiceID.\n") response3 = int(response3) y = (x[response3:(response3 + 1)]) #write into the report table. Works but doesn't store previous value logged. ie. starts over every time Is there a method like append list,or another I can use to add the row into the new table every time the fx is called? Apologies,it's not creating a code block – mabishi Apr 05 '16 at 21:46
0

I've accomplished that by always creating a new instance of the class prettytable.PrettyTable inside the while loop.

from prettytable import PrettyTable
import random

serviceID = []
services = []
price = []

while True:
    try:
        x = PrettyTable()

        ID = random.randint(1,90000) #range high to lower probability of non-uniqueness
        serviceID.append(ID) #Generates unique ID for each service

        prompt1 = input("Please add a service name to the list\n")
        services.append(prompt1)

        prompt2 = input("Please enter a price for the service\n")
        prompt2 == int(prompt2)
        price.append(prompt2)

        x.add_column("ServiceID", serviceID)
        x.add_column("Service", services)
        x.add_column("Price", price)

        print(x)


    except ValueError:
        print("Please enter valid type")
        continue

Here is my version of code using methods field_names() and add_row().

from prettytable import PrettyTable
import random

serviceID = []
services = []
price = []

x = PrettyTable()

x.field_names = ["ServiceID", "Service", "Price"]

while True:
    try:
         ID = random.randint(1,90000) #range high to lower probability of non-uniqueness
         serviceID.append(ID) # in order to store new value if you will need it later

         prompt1 = input("Please add a service name to the list\n")
         services.append(prompt1) # in order to store new value if you will need it later

         prompt2 = input("Please enter a price for the service\n")
         prompt2 == int(prompt2)
         services.append(prompt2) # in order to store new value if you will need it later

         x.add_row([ID, prompt1, prompt2])
         print(x)

    except ValueError:
        print("Please enter valid type")
        continue
UserAG
  • 142
  • 7
janus-py
  • 17
  • 3
  • Thanks! Let me test it out. – mabishi Apr 05 '16 at 12:56
  • Is there a way to access individual elements in a row, to achieve the same results as you would with a list? For example, in this case, a normal user would have the ability to enter a ServiceID and the program would print the Service and Price data of that row and ask for a confirmation of the entry. If confirmed, the program would then log the entry into (ServiceID, Service and Price) a report that the admin could view. I really appreciate your help guys! – mabishi Apr 05 '16 at 14:15