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'))
Related
so im getting a list index out of range here:
for i in range(len(empNr)):
print(empNr[i], rate[i], hrs[i], wkPay[i])
and I haven't really figured lists out, so I may just be confused and am unable to understand why i would be out of range. here the rest of the code below. thanks!
SENTINEL = 0
wkTotal = payHigh = wkPay = empHigh = 0
empNr = []
rate = []
hrs = []
wkPay = []
i = 0
empNr.append(input("Input first employee number: "))
#iteration if 0 is entered it should stop
while (empNr[i] != str(SENTINEL)):
rate.append(int(input("Input rate: ")))
hrs.append(int(input("Input hours: ")))
wkPay.append(rate[i] * hrs[i])
i = i + 1
empNr.append(input("Input employee number or '0' to stop: "))
#calculations using list functions
wkTotal = sum(wkPay)
payHigh = max(wkPay)
wkAvg = float(wkTotal) / len(empNr)
#output summary for pay calculator
print("\n\n Data entry complete " +" \n --------------------------------------")
print("\n Employee Number Pay Rate Hours worked Pay ")
print("--------------------------------------------------------")
for i in range(len(empNr)):
print(empNr[i], rate[i], hrs[i], wkPay[i])
print("Summary: ")
print("WEEK TOTAL: ", str(wkTotal))
print("EMPLOYEE HIGH: ", str(empHigh))
print("PAY HIGH: ", str(payHigh))
print("WEEK AVERAGE: ", str(wkAvg))
empNr.append(input("Input employee number or '0' to stop: ")) this line appends '0' to empNr. But it has no corresponding values for rate, hrs or wkPay. Meaning rate, hrs or wkPay these have one element less than that of empNr. A quick fix (but not recommended) would be to loop for rate or hrs instead of empNr. So your code would be:
for i in range(len(rate)):
print(empNr[i], rate[i], hrs[i], wkPay[i])
A better fix would be:
i = 0
inp = input("Do you want to add anew record? Y/n: ")
while (inp == "Y"):
empNr.append(input("Input first employee number: "))
rate.append(int(input("Input rate: ")))
hrs.append(int(input("Input hours: ")))
wkPay.append(rate[i] * hrs[i])
i = i + 1
inp = input("Do you want to add anew record? Y/n: ")
So while I enter 'Y' I can add new entries and length of each empNr, rate, hrs, wkPay would match. If I enter anything other than Y, the loop will terminate and the lengths will still remain the same...
SENTINEL = 0
wkTotal = payHigh = wkPay = empHigh = 0
empNr = []
rate = []
hrs = []
wkPay = []
i = 0
empNr.append(input("Input first employee number: "))
#iteration if 0 is entered it should stop
while (empNr[i] != str(SENTINEL)):
rate.append(int(input("Input rate: ")))
hrs.append(int(input("Input hours: ")))
wkPay.append(rate[i] * hrs[i])
i = i + 1
empNr.append(input("Input employee number or '0' to stop: "))
#calculations using list functions
wkTotal = sum(wkPay)
payHigh = max(wkPay)
wkAvg = float(wkTotal) / len(empNr)
#output summary for pay calculator
print("\n\n Data entry complete " +" \n --------------------------------------")
print("\n Employee Number Pay Rate Hours worked Pay ")
print("--------------------------------------------------------")
for i in range(len(empNr)-1):
print(empNr[i], rate[i], hrs[i], wkPay[i])
print("Summary: ")
print("WEEK TOTAL: ", str(wkTotal))
print("EMPLOYEE HIGH: ", str(empHigh))
print("PAY HIGH: ", str(payHigh))
print("WEEK AVERAGE: ", str(wkAvg))
Please use the above.
Lets say the list had 2 employee details. According to your solution len(empNr) gives 3. The range function will make the for loop iterate for 0,1 and 2. Also one mistake you did was even for the exiting condition when u r accepting the value for 0 you had used the same list which increases the count of the list by 1 to the no. of employees. Hence do a -1 so that it iterates only for the employee count
I have a question where im asked to calculate interest rate of an account after asking user for:
P is the present value of the account.
i is the monthly interest rate.
t is the number of months.
The current code I have is this:
def get_value(p, i , t):
return p * (1 + i) ** t
def main():
p = float(input("Please enter the current amount of money in your account: "))
i = float(input("Please enter the monthly interest rate: "))
t = float(input("Please enter the number of months: "))
#the while loop would probably go here, but I just dont know how to do it#
future_total = get_value(p, i, t)
print ("\nAfter", t, "months, you will have $", format(future_total, ".2f"), "in your account.")
main()
But the output is only giving me the final amount after 10 months, how do I implement a loop in order to see how much money would be in the account since month 1?
I would first make a variable called month and set it equal to 1. Then I would use the while loop so that when the month is less than the inputted month, the present value will be updated based on the inputted information. This will print out the money in the account for each month and not just the final value.
def get_value(p, i , t):
month = 1
while month <= t:
p = p * (1 + i)
print(month, p)
month += 1
def main():
p = float(input("Please enter the current amount of money in your account: "))
i = float(input("Please enter the monthly interest rate: "))
t = float(input("Please enter the number of months: "))
print(get_value(p,i,t))
# future_total = get_value(p, i, t)
# print ("\nAfter", t, "months, you will have $", format(future_total, ".2f"), "in your account.")
# print(f'After {t} months, you will have ${future_total} in your account.')
main()
I keep getting the following error and my program will not run. I need to make sure my program is modular and have the if-then statements to figure out what gross pay equation to use.
BASE_HOURS = 40
OT_MULTIPLIER = 1.5
def main():
hours = input("Enter the number of hours worked: ")
payRate = input("Enter the hourly pay rate: ")
calcPayWithOT(hours,payRate)
def calcPayWithOT(hours,payRate):
if hours <= BASE_HOURS:
theGrossPayNoOT = hours * payRate
print("The gross pay is $ ", theGrossPayNoOT)
if hours > BASE_HOURS:
theGrossPayOT = (hours - BASE_HOURS) * OT_MULTIPLIER + (hours * payRate)
print("The gross pay is $ ", theGrossPayOT)
main()
You should convert the hours and payRate into integers or floats like so:
hours = int(input("Enter the number of hours worked: "))
payRate = int(input("Enter the hourly pay rate: "))
or
hours = float(input("Enter the number of hours worked: "))
payRate = float(input("Enter the hourly pay rate: "))
Depending if you want to include only natural numbers or ones with figures after the decimal .
I am trying to use Python coding to create a paycheck when a user enters a said amount of hours. For under 40 hours a week of work, the standard pay is $9.25 an hour. Anything over 40 hours is rewarded a 150% of bonus(150% of 9.25 that is). I should also be able to take in hours entered in fractions and be able to print the paycheck as the output(which states the number of hours worked, pay per hour, bonus received, if any and the total salary)
So far, I have been able to successfully use the if else statement to get the final result but I do not know how to take in fractions and print the entire paycheck in the output. I am fairly new to Python and really like it a lot. Can someone please help me improvise my code and help me with fractions and printing the entire paycheck?
Here is my code so far.
hours = int(input('Please enter the number of hours...'))
if hours <= 40:
hourlyWage = hours*(9.25)
elif hours > 40:
hourlyWage = hours*(9.25*1.5)
print('Your salary is ${0}'.format(hourlyWage))
Thank you and help is much appreciated!
hours = int(input('Please enter the number of hours...'))
hourlyWage = 9.25
bonus = 0.5
bonusThreshold = 40
bonusHours = max(0, hours - bonusThreshold)
regularSalary = hourlyWage * hours
bonusSalary = bonusHours * hourlyWage * bonus
totalSalary = regularSalary + bonusSalary
print('Worked: {0} hours.'.format(hours))
print('Pay per hour: ${0}.'.format(hourlyWage))
print('Bonus received: ${0}'.format(bonusSalary))
print('Total salary: ${0}'.format(totalSalary))
hours = float(input('Please enter the number of hours...'))
hourlyWage = hours*(9.25)
hours = hours - 40
if hours > 0:
hourlyWage = hourlyWage + (hours*(9.25*1.5))
print('Your salary is ${0}'.format(hourlyWage))
hours = float(input('Please enter the number of hours...'))
pay = hours * 9.25 + max(hours-40,0)* (9.25*1.5-9.25)
print('Your salary is ${0}'.format(pay))
Your need to format your print statement. Here are some examples.
hours = 50
hourly_wage = 9.25
>>> print('Your salary is ${0:,.2f}'.format(hourly_wage * hours
+ max(0, hours - 40) * hourly_wage * 1.5))
Your salary is $601.25
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): ")