Unexpected loop in payment calculator - python-3.x

I have run this code and changed it more times than I can count but it always results in a loop. I'm not quite sure what I've done wrong nor how to end the loop.
"""
WeeklyPay.py: generate payroll stubs for all hourly paid employees and summarizes them
"""
def main():
"""
total_gross_pay = 0
hours_worked = 0
gross_pay = 0
hourly_rate= 0
:return: None
"""
employee = input("Did the employee work this week? Y or y for yes: ")
while employee == "Y" or "y":
hours_worked = int(input("How many hours did the employee work this week? "))
hourly_rate = int(input("What is the employee's hourly rate? "))
gross_pay = hours_worked * hourly_rate
print("Your weekly pay is: "+ gross_pay)
main()

You might find the while loop shown below works more like what your program should do:
def main():
"""Help the user calculate the weekly pay of an employee."""
while input('Did the employee work this week? ') in {'Y', 'y'}:
hours_worked = int(input('How many hours? '))
hourly_rate = int(input('At what hourly rate? '))
gross_pay = hours_worked * hourly_rate
print('The weekly pay is:', gross_pay)
if __name__ == '__main__':
main()

You are using a while loop, in which the variable employee is never changed, so the condition stays True. It should work if you replace the while with an if.

Related

write your pay computation with time-and-a-half for overtime and create a function called computepay which takes two parameters (hours and rate)

For the above question i have written this code . Math formula is correct but it is not giving the correct answer where is the fault?
def computepay(hours, rate):
if hours<=40:
pay = hours * rate
else:
pay = (((hours-40)*rate)*1.5)+rate*40
return pay
x = input("Enter hours: ")
y = input("Enter rate: ")
a = float(x)
b = float(y)
pay = computepay(a, b)
print("Pay: ", pay)
When hours is less than or equal to 40, computepay() doesn't return anything. Try changing the indent of the return pay line by four spaces, so it's indented by the same amount as the else::
def computepay(hours, rate):
if hours<=40:
pay = hours * rate
else:
pay = (((hours-40)*rate)*1.5)+rate*40
return pay

"display_results undefined" error and I cannot figure out why. I'm new to programming

here is my code, I'm not sure what I can do. every time I try to run this code, no matter what I've changed I get hung up at the same spot: "builtins.NameError: name 'hourly_pay' is not defined" I've marked in the code where which line it's in; where I try to define "display_results"
def main():
display_message()
#Get name
employee_name=input("Enter employee's name: ")
#Get Sales
sales_amount = float(input("Enter the sales amount: "))
#Get Hours
hours_worked = int(input("Enter hours worked by this employee: "))
#Calculate Hourly Pay
hourly_pay = hours_worked * hourly_pay_rate
#Calculate Commission
commission = sales_amount * commission_rate
#Calculate Gross Pay
gross_pay = hourly_pay + commission_rate
#Calculate Witholding
witholding = gross_pay * witholding_rate
#Calculate Net Pay
net_pay = gross_pay -witholding
display_results = (hourly_pay, commission, gross_pay, witholding, net_pay)
def display_message():
print('This program uses functions to calculate pay, commission, gross')
print('pay, witholding, and net pay.')
def display_results():
print('Hourly pay amount is: ' (hourly_pay)) #<-- This is where it errors
print('commission amount is: ' (commission))
print('Gross pay amount is: ' (gross_pay))
print('Witholding amount is:' (witholding))
print('Net pay amount is:' (net_pay))
hourly_pay_rate = 7.5
commission_rate = 0.05
witholding_rate = 0.25
main()
display_results()
You are trying to reference global variable inside the local scope which will fail. Also you are trying to auto type cast the str to int. The correct way to do this is show below:
Solution
Use global keyword to refer to global scope variable. Also Refer to Doc on global vs local scope variables.
def main():
global hourly_pay
display_message()
#Get name
employee_name=input("Enter employee's name: ")
#Get Sales
sales_amount = float(input("Enter the sales amount: "))
#Get Hours
hours_worked = int(input("Enter hours worked by this employee: "))
#Calculate Hourly Pay
hourly_pay = hours_worked * hourly_pay_rate
#Calculate Commission
commission = sales_amount * commission_rate
#Calculate Gross Pay
gross_pay = hourly_pay + commission_rate
#Calculate Witholding
witholding = gross_pay * witholding_rate
#Calculate Net Pay
net_pay = gross_pay -witholding
display_results = (hourly_pay, commission, gross_pay, witholding, net_pay)
def display_message():
print('This program uses functions to calculate pay, commission, gross')
print('pay, witholding, and net pay.')
def display_results():
global hourly_pay
print('Hourly pay amount is: {}'.format(hourly_pay))
# print('commission amount is: ' (commission))
# print('Gross pay amount is: ' (gross_pay))
# print('Witholding amount is:' (witholding))
# print('Net pay amount is:' (net_pay))
if __name__ == "__main__":
hourly_pay = 0.00
commission = 0.00
gross_pay = 0.00
witholding = 0.00
net_pay = 0.00
hourly_pay_rate = 7.5
commission_rate = 0.05
witholding_rate = 0.25
main()
display_results()
Let us know if this solves your problem or not. I have tried it myself and returns 15.0 as output.

Calculate phone bill(python)

Trying to return to data question is user enters incorrect number.
I need need to know how to return to the question again if incorrect number is entered
import math
p=float(input('Please enter the price of the phone: '))
print('')
data=int(input('Enter the amount of the data you will use, 1 gig, 3 gigs, 6 gigs: '))
tax=p*.0925
Total=p+tax
print('')
print ('If your phone cost',p,',the after tax total in Tennessee is',round(Total,2))
print('')
if data==1:
datap=30
print('The price of one gig is $30.')
elif data==3:
datap=45
print('The price of three gig is $45.')
elif data==6:
datap=60
print('The price of six gigs is $60.')
else:
print(data, 'Is not an option.')
#I need need to know how to return to the question again if incorrect number is entered
pmt=Total/24
bill=(datap+20)*1.13
total_bill=bill+pmt
print('')
print('With the phone payments over 24 months of $',round(pmt,2),'and data at $',datap,
'a month and line access of $20. Your total cost after tax is $',round(total_bill,2))
You should enter an infinite loop and only break out of it when the user has entered a valid input.
import math
costmap = {1: 30, 3: 45, 6: 60}
price = float(input('Please enter the price of the phone: '))
datamsg = 'Enter the amount of the data you will use, 1 gig, 3 gigs, 6 gigs: '
while True:
try:
data = int(input(datamsg))
except ValueError:
print('must input a number')
continue
tax = price * .0925
total = price + tax
print('If your phone cost {}, the after tax total in Tennessee is {}'
.format(price, round(total, 2)))
try:
datap = costmap[data]
print('The price of one gig is ${}.'.format(datap))
break
except KeyError:
print('{} is not an option try again.'.format(data))
pmt = total / 24
bill = (datap + 20) * 1.13
total_bill = bill + pmt
print('With the phone payments over 24 months of ${}'.format(round(pmt, 2)))
print('and data at ${} a month and line access of $20.'.format(datap))
print('Your total cost after tax is ${}'.format(round(total_bill, 2)))
You can also simplify your if/else clause by defining a dict to map inputs to cost values. If the value does not exist it throws an exception which you can catch, issue an error and go around the loop again.
Finally I'd recommend you try running your code through a pep-8 checker such as http://pep8online.com/. It will teach you how to format your code to make it easier to read. At present your code is more difficult to read than it could be.

How to validate inputs with 2 messages?python3

I have the example for gross pay but I want don't accept any string value . I tried to solve it with while true statement but executed with the first question of code.
I want these outputs :
Enter the hours worked this week:asd
please integer number
Enter the hours worked this week:10
Enter the hourly pay rate :asd
please float number
Enter the hourly pay rate :20.01
anyone help
my code
while True:
try:
hours = int(input('Enter the hours worked this week: '))
pay_rate = float(input('Enter the hourly pay rate: '))
gross_pay = hours * pay_rate
print('Gross pay: $', format(gross_pay, ',.2f'))
except ValueError:
print('please integer number)
This is a function I generally use when I need to validate multiple user input and request different types.
def get_input(typ, msg, err):
while True:
try:
return typ(input(msg))
except ValueError:
print("Please enter {0}".format(err))
hours = get_input(int, 'Enter the hours worked this week: ', 'an intger number')
pay_rate = get_input(float, 'Enter the hourly pay rate: ', 'a float number')
gross_pay = hours * pay_rate
print('Gross pay: $', format(gross_pay, ',.2f'))
Try this:
def hoursGet():
hours = input("Enter the hours worked this week: ")
try:
hours = int(hours)
return hours
except ValueError:
print ("please integer number")
hoursGet()
and simply write other functions for the other questions, substituting the printed statements and the data types.

What is the best possible way to loop this program

count = 0
while (count >4):
fixedcosts = float(input("Enter fixed costs: "))
salesprice = float(input("Enter the price for one unit: "))
variablecosts = float(input("Enter the variable costs for one unit: "))
contribution = float(salesprice)-float(variablecosts)
breakevenpoint = float(fixedcosts)/float(contribution)
roundedbreakevenpoint = round(breakevenpoint)
#Finds break even point
if int(roundedbreakevenpoint) < float(breakevenpoint):
breakevenpoint2 = int(roundedbreakevenpoint) + 1
print("Your break even point is ",int(breakevenpoint2),"units")
else:
print("Your break even point is ",int(roundedbreakevenpoint),"units")
#Finds number of units needed to make a profit
if int(roundedbreakevenpoint) < float(breakevenpoint):
breakevenpoint3 = int(roundedbreakevenpoint) + 2
print("To make a profit you need to sell ",int(breakevenpoint3),"units")
else:
int(roundedbreakevenpoint) >= float(breakevenpoint)
breakevenpoint4 = int(roundedbreakevenpoint) + 1
print("To make a profit you need to sell ",int(breakevenpoint4),"units")
decision = input("Would you like to restart the program?")
if decision == 'yes' or 'Yes':
count = count + 1
print("This program will now restart")
else:
print("This program will now be terminated")
print("Press enter to stop the program")
quit()
What is the best way to loop this code? I have tried while loop but I can't seem to be able to get it to work with a yes no answer.

Resources