10
\$\begingroup\$

I've done tutorials as well as searches. I need assistance in simplifying this code. Please don't do it for me- instead inform me of what, where and why you are trying to simplify or write less code. I'm already working on an if loop to exit on enter. This is just version 3 for me.

## Program gets the date, Employee ID, and amounts.  
## It then places them into a text file which can be ported to excel.

## Get Date
import datetime
date = str(datetime.date.today())

## Get Employee I.D.
empnum = raw_input('Please enter Employee Number\n')

## Lists for the Users input.
amnt = []
amntt =[]

## Get Users Input and add to the appropriate list
num1 = raw_input('Please enter Ticket amount.\n')
amnt.append(num1)
numt1 = raw_input('Please enter tip amount.\n')
amntt.append(numt1)

num2 = raw_input('Please enter Ticket amount.\n')
amnt.append(num2)
numt2 = raw_input('Please enter tip amount.\n')
amntt.append(numt2)

num3 = raw_input('Please enter Ticket amount.\n')
amnt.append(num3)
numt3 = raw_input('Please enter tip amount.\n')
amntt.append(numt3)

num4 = raw_input('Please enter Ticket amount.\n')
amnt.append(num4)
numt4 = raw_input('Please enter tip amount.\n')
amntt.append(numt4)
\$\endgroup\$
0

4 Answers 4

8
\$\begingroup\$

To expand on TheAtomicOption's answer, we should first try and perform some validation so that the values in your program are as expected.

Starting with this section:

## Get Employee I.D.
empnum = raw_input('Please enter Employee Number\n')

raw_input will accept basically anything and return a string value. Assuming that an employee ID is a number, for example, we can try to convert it to int and continue asking until a valid value is received.

## Get Employee I.D.
employee_id = None
while employee_id is None:
    try:
        employee_id = int(raw_input('Please enter Employee Number\n'))
    except ValueError:
        print "Invalid entry; please enter a valid employee ID."

So now this is what we see at the console:

Please enter Employee Number
 hello
Invalid entry; please enter a valid employee number.
Please enter Employee Number
 12345

We can apply the exact same kind of validation for ticket and tip amounts.


Some of your names could be made more clear. For instance:

## Lists for the Users input.
amnt = []
amntt =[]

Would be more clear like this:

## Lists for the Users input.
user_tickets = []
user_tips =[]

You have hard-coded 4 tickets and tips. I would recommend instead to ask the user how many tickets they want to enter

# Get number of tickets to enter.
num_tickets = 0
while num_tickets <= 0:
    try:
        num_tickets = int(raw_input('How many tickets do you want to enter?\n'))
    except:
        print "Invalid entry for number of tickets."

Then, you can just loop over the number of tickets, applying similar validation along the way. Note that, since those are presumably monetary amounts, we will convert it to float instead of int.

## Get Users Input and add to the appropriate list
for ticket in range(0, num_tickets):
    ticket_amt = None
    tip_amt = None
    while ticket_amt is None:
        try:
            ticket_amt = float(raw_input("Enter ticket {0} amount:\n".format(ticket+1)))
        except ValueError:
            print "Invalid entry for ticket amount."
    while tip_amt is None:
        try:
            tip_amt = float(raw_input("Enter tip amount:\n"))
        except ValueError:
            print "Invalid entry for tip amount."
    # add to lists once we know we have valid inputs
    user_tickets.append(ticket_amt)
    user_tips.append(tip_amt)
    print "Ticket {0} added with amount {1} and tip {2}".format(ticket+1, ticket_amt, tip_amt)

All that put together, it looks like this in the console:

How many tickets do you want to enter?
 2
Enter ticket 1 amount:
 20.50
Enter tip amount:
 2.25
Ticket 1 added with amount 20.5 and tip 2.25
Enter ticket 2 amount:
 15.75
Enter tip amount:
 1.50
Ticket 2 added with amount 15.75 and tip 1.5

I would suggest to start making functions to handle things like getting the employee ID, getting tickets, displaying tickets, etc. so you don't have to keep repeating code over and over, you can just call the function instead.

An example:

def get_employee_id():
    """Request employee ID from user"""
    employee_id = None
    while employee_id is None:
        try:
            employee_id = int(raw_input('Please enter Employee Number\n'))
        except ValueError:
            print "Invalid entry; please enter a valid employee ID."
    return employee_id

# Do this to get an employee's ID by calling your function:
employeeid = get_employee_id()

Here is a working demo on repl.it.

\$\endgroup\$
2
  • \$\begingroup\$ Would you recommend that the OP avoid using floats to represent monetary values? As in, should they use the Decimal class? Or is that just overkill? \$\endgroup\$
    – tonysdg
    Commented Oct 27, 2017 at 14:34
  • \$\begingroup\$ It may be overkill for this tiny use case, but for a more serious us case I would definitely use Decimal class instead of float. \$\endgroup\$
    – Phrancis
    Commented Oct 27, 2017 at 16:57
8
\$\begingroup\$

There's no such thing as an "If" loop, but perhaps you meant a While loop? That is exactly what you need. Otherwise this looks like a pretty good start.

Next you might consider:

  • adding some error checking:
    • is the value entered a number?
    • What happens if the user includes currency signs?
    • what happens if the user enters nothing?
    • Is the employee number a real employee number?
    • what happens if the user enters a sentence instead of a number?
  • Are there always exactly 4 tickets or can there be more/less?
\$\endgroup\$
8
\$\begingroup\$

Others already provided great answers, but I'd like to add something about portability. I see you used the tag, but I feel like (at least for this snippet of code) there shouldn't be a reason to limit it to Python 2. If you're learning Python from scratch, I strongly recommend learning Python 3. Support for Python 2.7 will be dropped soon and version 3 is the future of Python.


Learning Python 3 is not hard if you already know Python 2. Some things have changed only a little, like print being a function in Python 3, while other things have been rehauled entirely, like how strings are handled. These differences are easy to pick up on, however. If you don't know where to start, this Python Wiki article is a good read.


Regarding your actual code, the incompatibility is a result of your use of raw_input, which doesn't exist in Python 3. The Python 3 release renamed raw_input to input and provided eval as a way to simulate Python 2's input behavior. To fix this:

try:
    input = raw_input
except NameError:
    # Python 3; raw_input doesn't exist
    pass
\$\endgroup\$
1
  • \$\begingroup\$ Thanks for the info. I am learning from scratch. Me and a laptop. I will def switch to 3. I thought they just built on each other and expanded. Now that I know I will do better Huge THANK YOU!!!!! \$\endgroup\$
    – Toby
    Commented Oct 26, 2017 at 23:00
7
\$\begingroup\$

Instead of calling str(datetime...), use the isoformat() method available to the object.

Understanding the difference between amnt and amntt variables is not so straighforward. Both could mean amount of tickets or amount of tips. Use better named variables.

You can merge asking for 4 inputs into a single loop (and optionally, ask for number of tickets):

## Lists for the Users input.
amount_tickets = []
amount_tips = []

## Get Users Input and add to the appropriate list
for _ in range(4):
    num1 = raw_input('Please enter Ticket #{} amount.\n'.format(_ + 1))
    amount_tickets.append(num1)
    numt1 = raw_input('Please enter tip amount.\n')
    amount_tips.append(numt1)
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.