Ask the user to enter payroll information for the company. Set up a loop that continues to ask for information until they enter “DONE”. For each employee ask three questions:
name (first & last)
hours worked this week (only allow 1 through 60)
hourly wage (only allow 6.00 through 20.00)
VALIDATE the hours worked and the hourly wage, and make sure a name is entered.
Calculate each employee’s pay, and write it out to a sequential file. Be sure to include file I/O error handling logic.
Include only the weekly pay
Weekly pay is calculated:
For (1-40 hours) it is hourly rate * hours worked
For (41-60 hours) it is (hours worked – 40) * (hourly rate * 1.5)
+ hourly rate * 40
After all the employees are entered, read in the sequential file into a list named PAY for the weekly pay of each employee. Sort the list. Now print the lowest, highest, and average weekly pay for the week.
I am having obvious problem with this code
while len(eName)>0:
eName=raw_input("\nPlease enter the employees' first and last name. ")
hWork=raw_input("How many hours did they work this week? ")
hoursWork=int(hWork)
if hoursWork < 1 or hoursWork > 60:
print "Employees' can't work less than 1 hour or more than 60 hours!"
else:
pRate=raw_input("What is their hourly rate? ")
payRate=int(pRate)
if payRate < 6 or payRate > 20:
print "Employees' wages can't be lower than $6.00 or greater than $20.00!"
if hoursWork <=40:
grossPay=hoursWork*payRate
else:
grossPay=((hoursWork-40)*(payRate*1.5))+(40*payRate)
lsthours.append(grossPay)
print grossPay
print lsthours
ePass=raw_input("Type DONE when finished with employees' information. ")
ePass.upper() == "DONE"
if ePass == "DONE":
break
else:
continue
There's several problems with this code:
The indentation is all over the place. For example, the while loop ends at that first if statement
The test for the while loop is almost certainly false (since eName isn't initialised), so the loop never enters
the code at ePass.upper() == "DONE" is trying to set the ePass variable, which means that test won't work. You need:
if ePass.upper() == "DONE":
break
try this:
lsthours = list()
eName = "start" # initialize to something to start the loop
while eName:
eName = raw_input("\nPlease enter the employees' first and last name. ")
if not eName:
break #loop will exit also when blank name is inserted
hWork = raw_input("How many hours did they work this week? ")
hoursWork = int(hWork)
if hoursWork < 1 or hoursWork > 60:
print "Employees' can't work less than 1 hour or more than 60 hours!"
continue #skip
pRate = raw_input("What is their hourly rate? ")
payRate = int(pRate)
if payRate < 6 or payRate > 20:
print "Employees' wages can't be lower than $6.00 or greater than $20.00!"
continue #skip
if hoursWork <= 40:
grossPay = hoursWork * payRate
else:
grossPay = ((hoursWork - 40) * (payRate * 1.5)) + (40 * payRate)
lsthours.append(grossPay)
print grossPay
print lsthours
ePass = raw_input("Type DONE when finished with employees' information. ")
if ePass.upper() == "DONE":
break
It still lacks exception checking but should work.
The "data error" checks should just short-circuit the main loop, it's simpler, but you can have a more involved code and put them into their own loop.
A few errors as has been pointed out:
In python, indentation decides the code blocks
while loop:
while logic_test:
# this is inside while loop
....
# this is outside while loop
Certain functions on string does not replace the string in place, they return another string via return value
upper:
>>> a = "done"
>>> a.upper()
'DONE'
>>> a
'done'
>>>
Always initialize your variables.
If you are using sequence methods, the variable should have been defined as sequence earlier.
>>> t.append('ll')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 't' is not defined
>>> t = []
>>> t.append('ll')
>>>
Make your scope explicit
lsthours = []
while len(eName)>0:
........
lsthours.append(grossPay)
Yu can do something as this:
grossPay = 0.0
lsthours = []
eName=raw_input("\nPlease enter the employees' first and last name (type 'PASS' to exit): ")
while eName.upper() != "PASS":
hWork=raw_input("How many hours did they work this week? ")
hoursWork=int(hWork)
if hoursWork < 1 or hoursWork > 60:
print "Employees' can't work less than 1 hour or more than 60 hours!"
else:
pRate=raw_input("What is their hourly rate? ")
payRate=int(pRate)
if payRate < 6 or payRate > 20:
print "Employees' wages can't be lower than $6.00 or greater than $20.00!"
if hoursWork <=40:
grossPay=hoursWork*payRate
else:
grossPay=((hoursWork-40)*(payRate*1.5))+(40*payRate)
lsthours.append(grossPay)
print grossPay
print lsthours
eName=raw_input("\nPlease enter the employees' first and last name. (type 'PASS' to exit): ")
Related
hrs = int(input("How many hours do you want? "))
if hrs >= 24:
day = hrs/24
hrs = hrs
if day == 1:
print(hrs, "hours is equal to", day, "day")
else:
if day >= 7:
wks = day / 7
if wks == 1:
print(day, "days is equal to", wks, "week")
else:
if wks >= 4:
mon = wks / 4
if mon == 1:
print(wks, "weeks is equal to", mon, "month")
else:
if hrs == 1:
print("You have 1 hour")
else:
print("You have", hrs, "hours")
For some reason when I try and use a number greater than 24 in hrs = int(input("How many hours would you like? ")) it stops completely not giving me what the problem is.
Here is what is shown in the console
I am using VisualStudio Code to make this
try using Floor division // instaed of normal devision /
hrs = int(input("How many hours do you want? "))
if hrs >= 24:
day = hrs//24
hrs = hrs
if day == 1:
print(hrs, "hours is equal to", day, "day")
else:
if day >= 7:
wks = day // 7
if wks == 1:
print(day, "days is equal to", wks, "week")
else:
if wks >= 4:
mon = wks // 4
if mon == 1:
print(wks, "weeks is equal to", mon, "month")
else:
if hrs == 1:
print("You have 1 hour")
else:
print("You have", hrs, "hours")
There's nothing wrong with Visual Studio Code based on the information that you've provided in your post.
The first mistake that I could see was this:
day = hrs/24
#...
if day == 1:
Here, day will be exactly equal to 1 only when hrs == 24. For hrs > 24, day will always be a floating point number unless hrs is storing a multiple of 24. Hence, the condition day == 1 will never be True.
This also applies to the else block underneath, where you've written wks = day / 7 and then if wks == 1:.
To resolve this, use the floor-division operator, //, which returns an integer value if both operands are integers.
The second thing that I noticed was that in line #4, you've written hrs = hrs. I believe you wanted to write hrs = hrs % 24, which assigns the remainder of hrs and 24 to hrs itself. So for hrs = 25, number of days = hrs // 24 = 1. And, number of hours = hrs % 24 = 25 % 24 = 1 (remainder when 25 is divided by 24).
Now, on to the main question: Why did the console show no output, and why did the code terminate without doing anything?
Well, notice that all the print statements in the code are under if or else conditions. If the conditions are never true, the print statements will not be executed at all!
Consider the case where hrs = 25. The first if block becomes True (if hrs >= 24) and hence gets executed. Note that the two print statements in the corresponding else block at lines 19 and 21 will not be executed now.
Since hrs / 24 is a floating point number (not an integer, and definitely not equal to 1), the statement day == 1 is never True and hence its if statement never gets executed. So, the print statement in the if day == 1: block, printf(hrs, "hours is equal to", day, "day"), also does not get executed.
Now, the control goes to the else block below. day >= 7 evaluates to False, since hrs/24 is actually 1.08333....
Corresponding to this if (if day >= 7:), there is no else! So, when this if condition turns out to be False, the program terminates without doing anything!
for i in range (0, 3):
print() # When iterates creates a space from last section
raw_mark = int(input("What was student: " + str(student_id[i]) + "'s raw mark (0 - 100)?: "))
days_late = int(input("How many days late was that student (0 - 5)?: "))
penalty = (days_late * 5)
final_mark = (raw_mark - penalty)
# Selection for validation
if 0 <= raw_mark <= 100 and 0 <= days_late <= 5 and final_mark >= 40:
print("Student ID:", str(student_id[i]))
print() # Spacing for user readability
print("Raw mark was:", str(raw_mark),"but due to the assignment being handed in",
str(days_late),"days late, there is a penalty of:", str(penalty),"marks.")
print()
print("This means that the result is now:", final_mark,"(this was not a capped mark)")
elif 0 <= raw_mark <= 100 and 0 <= days_late <= 5 and final_mark < 40: # Final mark was below 40 so mark must be capped
print("Student ID:", str(student_id[i]))
print()
print("Raw mark was:", str(raw_mark),"but due to the assignment being handed in",
str(days_late),"days late, there is a penalty of:", str(penalty),"marks.")
print()
print("Therefore, as your final mark has dipped below 40, we have capped your grade at 40 marks.")
else:
print("Error, please try again with applicable values")
At the else i would like the loop to loop back through but not having iterated i to the next value, so that it can be infinite until all 3 valid inputs are entered... cannot use a while loop nor can i put the if - elif- else outside the loop. Nor can i use a function :(
You can have your for loop behave like a while loop and have it run forever and implement your i as a counter. Then the loop can be terminated only if it ever hits 3 (or 2 so that you indices dont change), while otherwise it is set back to 0:
cnt_i = -1
for _ in iter(int, 1):
cnt_i += 1
if ...
else:
cnt_i = 0
if cnt_i == 2:
break
But seriously, whatever the reason for not using a while loop, you should use it anyhow..
Try something like this. You can keep track of the number of valid inputs, and only stop your loop (the while) once you hit your target number.
valid_inputs = 0
while valid_inputs <= 3:
...
if ...:
...
elif ...:
...
else:
# Immediately reset to the top of the while loop
# Does not increment valid_inputs
continue
valid_inputs += 1
If you really cannot use a while loop...
def get_valid_input():
user_input = input(...)
valid = True
if (...): # Do your validation here
valid = False
if valid:
return user_input
else:
return get_valid_input()
for i in range (0, 3):
input = get_valid_input()
# Do what you need to do, basically your program from the question
...
...
There are some additional gotchas here, as in you need to worry about the possibility of hitting the maximum recursion limit if you keep getting bad input values, but get_valid_input should ideally only return when you are sure you have something that is valid.
You can put the input statement inside while loop containing try block.
for j in range(3): # or any other range
try:
raw_mark = int(input("What was student: " + str(student_id[i]) + "'s raw mark (0 - 100)?: "))
days_late = int(input("How many days late was that student (0 - 5)?: "))
break
except:
pass
I am using Python 3. This is for a homework project for a class, but I'm not looking for something to do the problem for me! I was just wondering if someone could help point out exactly where I've gone wrong, or what I need to look into to make my code work.
def main():
taxPayersList = []
incomesList = []
taxesList = []
taxPayersList, incomesList = inputNamesAndIncomes(taxPayersList, incomesList)
taxesList = calculateTaxes(incomesList)
displayTaxReport(taxesList, incomesList, taxPayersList)
def inputNamesAndIncomes(taxPayersList, incomesList):
print('Welcome to Xanadu Tax Computation Program')
print('')
confirmation = input('Do you have income amounts? y/n ')
index = 0
try:
while confirmation == 'y' or confirmation == 'Y':
taxPayersList[index] = input('Enter a tax payer name: ')
incomesList[index] = float(input('Enter income amount: '))
confirmation = input('Are there more income amounts? ')
index += 1
except:
print('An error occurred. Please only enter numbers for income amount.')
return taxPayersList, incomesList
def calculateTaxes(incomesList):
index = len(incomesList)
while index < len(incomesList):
if incomesList[index] >= 0 and incomesList[index] <= 50000:
taxesList[index] = incomesList[index] * .05
elif incomesList[index] >= 50000 and incomesList[index] <= 100000:
taxesList[index] = 2500 + ((incomesList[index] - 50000) * .07)
elif incomesList[index] >= 100000:
taxesList[index] = 6000 + ((incomesList[index] - 100000) * .09)
index += 1
return incomesList
def displayTaxReport(taxesList, incomesList, taxPayersList):
print('2018 TAX DUES FOR XANADU STATE')
print('')
print('Name\t\tANNUAL INCOME\tTAXDUE')
for n in incomesList:
print(taxPayersList,'\t\t',incomesList,'\t',taxesList)
main()
Right now, I can enter a name into the first input, but as soon as I hit enter it just prints out my error code and then print out the final function like below.
Welcome to Xanadu Tax Computation Program
Do you have income amounts? y/n y
Enter a taxpayer name: Susan
An error occurred. Please only enter numbers for income amount.
2018 TAX DUES FOR XANADU STATE
Name ANNUAL INCOME TAXDUE
I know this is a total mess but any help at all would be so appreciated!
There is an IndexError: list assignment index out of range for the line
taxPayersList[index] = input('Enter a tax payer name: ')
You didn't see it because you excepted all errors and didn't print them. I suggest using
name = input('Enter a tax payer name:')
taxPayersList.append(name)
etc. Note that I append it to the list. I also suggest a different strategy of handling errors.
Alternatively, you might wish to use a dictionary instead of using two lists, since you want to associate an income with a name,
name = input('Enter a tax payer name:')
income = float(input('Enter income amount:'))
incomes[name] = income
You can't just assign into a non-existant index for a list to add items to it:
>>> a = []
>>> a[0] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
Instead you should look at using the .append() method for lists.
(The reason you aren't seeing the IndexError debugging details is because your except clause prevents it from being displayed. Bare except clauses are often considered an antipattern because they mask unexpected errors like this and make it harder to tell what went wrong - they catch any exception, not just ones due to bad user input.)
I'm not sure what I did wrong in this code, but for some reason, Eclipse keeps on telling me that the if statement is just bad. I'm not sure why, when I look at the examples, it looked fine to me.
penny = .01
nickel = .05
dime = .1
quarter = .25
print("Enter how many coins you want to use to make a dollar.")
e_pen = int(input("Enter the amount of pennies you want: "))
e_nic = int(input("Enter the amount of nickels you want: "))
e_dim = int(input("Enter the amount of dimes you want: "))
e_qua = int(input("Enter the amount of quarters you want: "))
doll = float((e_pen * penny) + (e_nic * nickel) + (e_dim *dime) + (e_qua * quarter))
if doll > 1 # every conditional needs a : per the answer below
print("The total value is greater than 1 dollar.") # notice the indentation
else # same here
print("Try again.")
If statements require a colon and proper indentation, see:
if doll > 1:
print("blah")
else:
Print ("Try again")
Note, the indentation is 4 spaces.
I'm working on this simple task where I need to use 2 while loops. The first while loop checks if the number of hours is less than 0 if it is then loop should keep asking the user.
Here's my code:
hours = float(input('Enter the hours worked this week: '))
count = 0
while (0 > hours):
print ('Enter the hours worked this week: ')
count = count + 1
pay = float(input('Enter the hourly pay rate: '))
while (0 > pay):
print ('Enter the hourly pay rate: ')
count = count + 1
total_pay = hours * pay
print('Total pay: $', format(total_pay, ',.2f'))
break is what you're looking for.
x = 100
while(True):
if x <= 0:
break
x -= 1
print x # => 0
As for your example, there is nothing that would seem to cause a break to occur. For example:
hours = float(input('Enter the hours worked this week: '))
count = 0
while (0 > hours):
print ('Enter the hours worked this week: ')
count = count + 1
You are not editing the hours variable at all. This would merely continue to print out "Enter the hours worked this week: " and increment count ad infinitum. We would need to know what the goal is to provide any more help.
You exit a loop by either using break or making the condition false.
In your case, you take input from the user, and if hours < 0, you print the prompt and update the count, but you don't update hours.
while (0 > hours):
print ('Enter the hours worked this week: ')
count = count + 1
should be:
while (0 > hours):
hours = float(input('Enter the hours worked this week: '))
count = count + 1
Similarly for pay:
while (0 > pay):
pay = float(input('Enter the hourly pay rate: '))
count = count + 1
Well, the other answer shows you how to break out of a while loop, but you're also not assigning to the pay and hours variables. You can use the built-in input function to get what the user supplied into into your program
hours = float(input('Enter the hours worked this week: '))
count = 0
while (0 > hours):
hours = input('Enter the hours worked this week: ')
count = count + 1
pay = float(input('Enter the hourly pay rate: '))
while (0 > pay):
pay = input('Enter the hourly pay rate: ')
count = count + 1
total_pay = hours * pay
print('Total pay: $', format(total_pay, ',.2f'))