Python Salary Program Using Conditionals - python-2.7

I get an error # line 19, the Bonus function and I can't figure out why. I'll probably get an error for the other functions too. I've checked my spaces, my numbers vs. my strings, and my DOM. My first problem were about my globals and I fixed it from global comrate to `comrate = 0; . I've got debugging blindness. Thank you guys in advance!
def main():
#Welcome user and get sales number
print("Welcome to the Bonus Qualification Calculator! Please honestly answer the following questions:")
name = str(input("What is your name? "))
sales = float(input("What is your sales total? "))
jobtime = float(input("How many months have you been with the company? "))
vacationtime = float(input("How many vacation days have you taken? "))
#Define Global Vars
comrate = 0;
compedsalary = 0;
bonussalary = 0;
finalsalary = 0;
#Begin calculations
Bonus(sales, jobtime)
vacation(vacationtime)
print(str(name) + ", your salary based on the information you provided is " + str(format(finalsalary,'.2f'))
def Bonus(sales,jobtime):
#Calcultate commission
if sales < 10000:
comrate = 0
elif sales > 10000 and sales <= 1000000:
comrate = .02
elif sales >= 100001 and sales <= 500000:
comrate = .15
compedsalary = float(comrate * 2000)
if jobtime > 3:
bonussalary = float(compedsalary + 1000)
else:
print("You don't qualify for a bonus due to your limited time at the company.")
elif sales >= 500001 and sales <= 1000000:
comrate = .28
compedsalary = float(comrate * 2000)
if jobtime > 3:
bonussalary = float(compedsalary + 5000)
else:
print("You don't qualify for a bonus due to your limited time at the company.")
elif sales > 1000000:
comrate = .35
compedsalary = float(comrate * 2000)
if jobtime > 3:
bonussalary = float(compedsalary + 100000)
elif jobtime > 60:
bonussalary = float(compedsalary + 101000)
else:
print("You don't qualify for a bonus due to your limited time at the company.")
def vacation(finalsalary):
if vacation > 3:
finalsalary = float(bonussalary - 200)
else:
finalsalary = bonussalary
main()

You're using full quotes where you should be using apostrophes. You're using contractions in your print statements, which confuses Python. Just put "do not" instead of "don't" in your print statements.

Related

Why is the average not calculating correctly, and why does the average letter grade remain F no matter the number?

This is my code for the program that calculates 5 user inputs of test scores, displays the letter grade, and then calculates the average score and letter grade. However, the grade comes back as the wrong average, and the letter grade stays F no matter the number.
import os
#constants
PROG_ID = "\nFilename: Average_Grade.py\n"\
"Homework: 09\n"\
"Source Code Author: \n"\
"Reference: Chapter 5\n"\
"Date: 9 April 2022\n"
USER_PROMPT = "Please enter a test score. "
GRADE_TAG = "The letter grade is "
OUTPUT_TAG = "The average grade is "
#display program id
def progId ():
print(PROG_ID)
print()
#prompt user
def getInput(testScore, gradeList):
for item in range (5):
testScore = int(input(USER_PROMPT))
gradeList.append(testScore)
determineGrade(testScore)
print()
#letter grade
def determineGrade(testScore):
if testScore >= 90: print (GRADE_TAG, "A")
elif testScore >= 80: print (GRADE_TAG, "B")
elif testScore >= 70: print (GRADE_TAG, "C")
elif testScore >= 60: print (GRADE_TAG, "D")
else: print (GRADE_TAG, "F")
#show average
def calculateAverage(testScore, gradeList):
avg = sum(gradeList)/len(gradeList)
print(OUTPUT_TAG, format(avg, ".0f"))
avg = testScore
determineGrade(testScore)
def housekeeping():
input ("Press enter to exit.")
os._exit(1)
#control
def main():
#variables
testScore = avg = 0
gradeList = [testScore]
#calls
progId()
getInput(testScore, gradeList)
calculateAverage(testScore, gradeList)
main()
housekeeping()
If for some reason your main does not get called before the rest your gradeList is never initialised and calling methods on it would do nothing? I would initialise the array at the beginning of the file. You should test if at any point your array does not only contain 0, or nothing at all with a console.log().

How do I get my code to repeat itself if the desired input is not entered?

I just started python 2 weeks ago and I don't know how to make my code repeat itself when the input is something like "fox" when that is not one of the three options I'm accepting (horse, oxen, mule). Also if I want to total up the cost of 2 horse and say 3 mules by having it ask "do you want to buy any more animals", how would i do that? Any help would be very appreciated.
zoo = {}
def main():
print ("Animals available to purchase: " + "horse: 50, oxen: 35, mule: 20")
total_money = 1000
print ("You have " + str(total_money) + " to spend")
cost(total_money)
def animal_cost(total_money):
animal_type = raw_input("Please enter an animal:")
print ("Animal Type Entered: " + str(animal_type))
global animal_quantity
animal_quantity = int(raw_input("Please enter quantity of animals:"))
print ("Animal Quantity Entered: " + str(animal_quantity))
if animal_type in zoo:
zoo[animal_type] += animal_quantity
else: zoo[animal_type] = animal_quantity
while True:
if animal_type == 'horse':
return 50 * animal_quantity
if animal_type == 'oxen':
return 35 * animal_quantity
if animal_type == 'mule':
return 20 * animal_quantity
else:
cost(total_money)
def cost(total_money):
costing = animal_cost(total_money)
total_money -= costing
if total_money <= 0:
print ("No money left, resetting money to 1000.")
total_money = 1000
zoo.clear()
print ("Cost of Animals: " + str(costing))
print ("Remaining Balance:" + str(total_money))
choice = raw_input("Do you want to buy any more animals?(Y/N):")
if choice in('Y','y'):
cost(total_money)
elif choice in ('N','n'):
choice_2 = raw_input("Enter 'zoo' to see the animals you have purchased:")
if choice_2 in('zoo','Zoo'):
print zoo
choice_3 = raw_input("is everything correct?(Y/N):")
if choice_3 in ('Y','y'):
print ("Thank you for shopping!")
elif choice in ('N','n'):
print ("Restarting Transaction")
zoo.clear()
cost(total_money)
if __name__ == '__main__':
main()
You may try this enhanced version of your code:
zoo = {} # creating global dictionary for adding all animals into it.
# function to get animal cost
def animal_cost(total_money):
animal_type = raw_input("Please enter an animal:")
print ("Animal Type Entered: " + str(animal_type))
animal_quantity = int(raw_input("Please enter quantity of animals:"))
print ("Animal Quantity Entered: " + str(animal_quantity))
if animal_type in zoo:
zoo[animal_type] += animal_quantity
else: zoo[animal_type] = animal_quantity
if animal_type == 'horse':
return 50 * animal_quantity
if animal_type == 'oxen':
return 35 * animal_quantity
if animal_type == 'mule':
return 20 * animal_quantity
# getting total_money after animal purchase
def cost(total_money):
costing = animal_cost(total_money)
total_money = total_money - costing
if total_money <=0: # condition when money is less than or equal to 0.
print("No Money left, resetting money to 1000.")
total_money = 1000
print ("Cost of Animals:" + str(costing))
print ("Total Money Left:" + str(total_money))
# Recursion for buying more animals:
choice = raw_input("Do you want to buy any more animals?:")
if choice in ('Yes','y','Y','yes','YES'):
cost(total_money)
# you can use this commented elif condition if you want.
else: # elif choice in('no','No','n','N','NO'):
print("thankyou!!")
print("You have total animals: "+str(zoo))
# main function to initiate program
def main():
print ("Animals available to purchase: " + "horse, oxen, mule")
total_money = 1000
print ("You have " + str(total_money) + " to spend")
cost(total_money)
if __name__ == '__main__':
main()
This might help you out.
Have a look into this for last two lines

maximum recursion depth error?

So I'm really new to this (3 days) and I'm on code academy, I've written this code for one of the activities but when I run it it displays maximum recursion depth error, I'm running it in the python console of code academy and simultaneously on my own ipython console. The hint on the page is not helpful, can anybody explain how to fix this?
Thanks
def hotel_cost(nights):
return (nights * 140)
def plane_ride_cost(city):
if plane_ride_cost("Charlotte"):
return (183)
if plane_ride_cost("Tampa"):
return (220)
if plane_ride_cost("Pittsburgh"):
return (222)
if plane_ride_cost("Loas Angeles"):
return (475)
def rental_car_cost(days):
cost = days * 40
if days >= 7:
cost -= 50
elif days >= 3:
cost -= 20
return cost
def trip_cost(city, days):
return hotel_cost(nights) + plane_ride_cost(city) + rental_car_cost(days)
Maybe:
def plane_ride_cost(city):
if city == "Charlotte":
return (183)
if city == "Tampa":
return (220)
if city == "Pittsburgh":
return (222)
if city == "Los Angeles":
return (475)
The error was:
The plane_ride_cost(city) called plane_ride_cost("Charlotte") in every recursion step.
Not the best, but a better approach:
def hotel_cost(nights):
return nights * 140
plane_cost = {
'Charlotte' : 183,
'Tampa' : 220,
'Pittsburgh' : 222,
'Los Angeles' : 475,
}
def plane_ride_cost(city):
if city not in plane_cost:
raise Exception('City "%s" not registered.' % city)
else:
return plane_cost[city]
def rental_car_cost(days):
cost = days * 40
if days >= 7:
cost -= 50
elif days >= 3:
cost -= 20
return cost
def trip_cost(city, days):
return hotel_cost(nights) + plane_ride_cost(city) + rental_car_cost(days)

I would like to add an hours and minute format to my list and list each item with the hour next to it starting at 0:00 and going to 23:00

This is for PYthon 3.5. I am looking to add hours and minutes format to the list and get it to print out currently it will not do either.
I am looking to get a list of what is input as:
0:00 The temperature is ##
1:00 The temperature is ##
up to 23:00.
Thanks for the help.
HourlyTemperatures = []
def main():
def GetTemperatures(HourlyTemperatures):
for hours in range(0,24):
HourlyTemperatures.append(int(input("Please input a temperature for the hour: " % hours)))
while HourlyTemperatures[hours] <= -50 or HourlyTemperatures[hours] >= 130:
print("Please enter a valid Temperature between -50 or 130")
HourlyTemperatures[hours] = (int(input("Please input a temperature for the hour: ")))
return HourlyTemperatures
def ComputeAverageTemp(HourlyThemperatures):
AverageTemperature = sum(HourlyTemperatures) / len(HourlyTemperatures)
return AverageTemperature
def ComputeMaxTemp(HourlyTemperatures):
MaxTemp = max(HourlyTemperatures)
return MaxTemp
def ComputeMinTemp(HourlyTemperatures):
MinTemp = min(HourlyTemperatures)
return MinTemp
CalcTemperature = GetTemperatures(HourlyTemperatures)
AverageTemperature = ComputeAverageTemp(CalcTemperature)
MaxTemp = ComputeMaxTemp(CalcTemperature)
MinTemp = ComputeMinTemp(CalcTemperature)
CalcDisplayTemperature = DisplayTemperatures(HourlyTemperatures, AverageTemperature)
print(CalcTemperature)
print(HourlyTemperatures)
print(AverageTemperature)
print(MaxTemp)
print(MinTemp)
The following code will repeatedly ask for temperatures and then show the minimum, maximum and average values.
The new thing in this code is the use of the datetime module and the datetime.time(hours + 1, 0).strftime('%H:%M') to format a value as 01:00, 02:00 and so on. This is using the strftime method on a time (which is what datetime.time() creates) and it formats the value as HH:MM (two digits for the hour, two digits for the minutes).
It also uses enumerate which is a built-in function that Python provides for going over a list of values while also providing a counter variable. So you'll get both the position in the list as well as the value at that position. This is useful in our case because we want to display both the hour and the temperate value of that hour.
import datetime
HourlyTemperatures = []
def GetTemperatures(HourlyTemperatures):
for hours in range(0,24):
message = "Please input a temperature for the hour: %s " % datetime.time(hours + 1, 0).strftime('%H:%M')
HourlyTemperatures.append(int(input(message)))
while HourlyTemperatures[hours] <= -50 or HourlyTemperatures[hours] >= 130:
print("Please enter a valid Temperature between -50 or 130")
HourlyTemperatures[hours] = int(input(message))
return HourlyTemperatures
def ComputeAverageTemp(HourlyThemperatures):
AverageTemperature = sum(HourlyTemperatures) / len(HourlyTemperatures)
return AverageTemperature
def ComputeMaxTemp(HourlyTemperatures):
MaxTemp = max(HourlyTemperatures)
return MaxTemp
def ComputeMinTemp(HourlyTemperatures):
MinTemp = min(HourlyTemperatures)
return MinTemp
CalcTemperature = GetTemperatures(HourlyTemperatures)
AverageTemperature = ComputeAverageTemp(CalcTemperature)
MaxTemp = ComputeMaxTemp(CalcTemperature)
MinTemp = ComputeMinTemp(CalcTemperature)
print(CalcTemperature)
print(HourlyTemperatures)
print(AverageTemperature)
print(MaxTemp)
print(MinTemp)
for hour, temperature in enumerate(HourlyTemperatures):
print("The temperature for " + datetime.time(hour + 1, 0).strftime('%H:%M') + " is " + str(temperature))

day of the week issue always prompts monday no matter the entry

The outcome of this is when you enter any number 1-7 you will get the day of that number. for some reason it will always prompt Monday. How can I fix this?
'#Enter a number range 1-7 for the day of the week Example 1=Monday
#variables to represent the days of the week
num = float(input ("Enter the number for the day of week"))
Monday_number = 1
Tuesday_number = 2
Wednesday_number = 3
Thursday_number = 4
Friday_number = 5
Saturday_number = 6
Sunday_number = 7
Other_number = 8
#the day of the week
if Monday_number == 1:
print('Monday')
elif Tuesday_number == 2:
print('Tuesday')
elif Wednesday_number == 3:
print('Wednesday')
elif Thursday_number == 4:
print('Thursday')
elif Friday_number == 5:
print('Friday')
elif Saturday_number == 6:
print('Saturday')
elif Sunday_number == 7:
print('Sunday')
else:
if Other_number > 7:
print('Invalid number entered')'
You're not comparing num, the user input, to anything. In your if statements, you should be sequentially comparing num to each of the day of week constants. Better yet, you could be using a lookup table:
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
user_input = input('Enter the day of the week: ')
print(days[int(user_input)])
Step through your algorithm mentally, line-by-line. What happens when you get to the first if statement?