I honestly have no idea what I'm doing but, I know as soon as I get a bit of help, it'll come to me. So, here's the code and I know I've done something wrong? Won't let me complete the input?
"""
WeeklyPay.py: generate payroll stubs for all hourly paid employees and summarizes them
"""
def main():
"""
WeeklyPay.py generates and prints and employee pay stubs based off hours_worked, hourly_rate, and gross_pay
:return: None
"""
total_gross_pay = 0
hours_worked = 0
more_employee = input()
more_employee = input("Did the employee work this week? Y or y for yes: ")
while more_employee == "Y" or "y":
hours_worked = input("How many hours did the employee work? ")
hourly_rate = input("Please enter the employee's hourly rate: ")
Related
I have created a simple python program that lets users drive different cars. The user will enter their full name, address, and phone number. The user will then be asked which car they wish to drive, with a maximum of five selected cars. The cars have set prices and a total bill will be added up at the end of the program, however, I am currently unable to find a solution to work out the total cost for the user. The program also asks the user how many laps of the race they wish to perform in the car, I have already worked out how to display the total cost of the laps, but need it added to the total cost somehow. Thanks!
Code
cars_list = ["Lamborghini", "Ferrari", "Porsche", "Audi", "BMW"]
cars_prices = {"Lamborghini":50, "Ferrari":45, "Porsche":45, "Audi":30, "BMW":30}
laps_cost = 30
final_cost = []
final_order = {}
cust_num_cars = int(input("Please enter the number of cars you want to drive in this session: "))
while cust_num_cars > 5:
cust_num_cars = int(input("You can only drive a maximum of five cars! Please try again.\n Enter cars: "))
for index in range(cust_num_cars):
print("\nChoose a car type from the following list", cars_list)
select_cars = input("Select a car type: ")
if select_cars in cars_list:
print("\nYou have selected to drive the", {select_cars})
final_cost.append(cars_prices[select_cars])
if select_cars not in cars_list:
print("\n",{select_cars}, "is not in the available list of cars to drive!")
cust_name = input("\nPlease enter your full name: ")
cust_address = input("Please enter your full address: ")
cust_phone_num = int(input("Please enter your mobile phone number: "))
add_laps = input("\nWould you like to drive additional laps? (Yes/No): ")
if add_laps == "Yes":
print("\nYou have selected an additional lap!")
num_of_laps = int(input("Number of additional laps: "))
print("\nYou have selected", num_of_laps, "additional laps!")
final_cost.append(cars_prices[add_laps])
sum = num_of_laps * laps_cost
else:
print("\nYou have selected no additional extra laps.")
print("Total laps cost: £",final_cost)
print("\n----Order & Billing summary----")
print("Customer Full Name:", cust_name)
print("Customer Address:", cust_address)
print("Customer Phone Number", cust_phone_num)
print("Total cost", final_cost.append(cars_prices))
I have tried everything I know in my little experience with Python to work out a final cost. I have worked out the total cost for the number of laps, but can't work out how to add that to the cost of the selected cars and then display a total cost.
First, you can't use a for-loop because when you select a car that isn't in the possibilities you have lost an iteration, use a while loop
# final_cost renamed to car_cost
while len(car_cost) != cust_num_cars:
print("\nChoose a car type from the following list", cars_list)
select_cars = input("Select a car type: ")
if select_cars in cars_list:
print("\nYou have selected to drive the", select_cars)
car_cost.append(cars_prices[select_cars])
else:
print("\n", select_cars, "is not in the available list of cars to drive!")
Then use sum() for the cars cost and add to the laps cost
num_of_laps = 0
add_laps = input("\nWould you like to drive additional laps? (Yes/No): ")
if add_laps == "Yes":
print("\nYou have selected an additional lap!")
num_of_laps = int(input("Number of additional laps: "))
print("\nYou have selected", num_of_laps, "additional laps!")
else:
print("\nYou have selected no additional extra laps.")
total = num_of_laps * laps_cost + sum(car_cost)
print("Total price:", total)
To calculate the total cost, you can use the built-in sum() function, which takes an iterable (like a list) and returns the sum of all its elements. In your case, you can use it to add up all the prices of the cars that the user selected:
total_cost = sum(final_cost)
Then you can add the cost of the laps to the total cost. In your code, the variable sum holds the total cost of the laps. You can add that to the total_cost variable:
total_cost += sum
Hi friend in this program its better to add all of your costs in one variable.
in a list your list's elements are not adding together,
but with variables you can add your cost every time you get a cost like this:
cost_sum = 0
cost = input("Enter a cost: ")
cost_sum += cost
I am brand new to coding so I hope this is a small mistake. Below is the code for an assignment on a paper carrier's salary. I get no error codes but no output, even the print functions do not show. Please help
# This program will calculate the weekly pay of a paper carrier.
# Developer: Hannah Ploeger Date: 08/30/2022
def main():
# initialize variables
paperCost = 4
commission = 0.05
# prompt user for number of papers
numPaper = eval(input("How many papers are delivered on your route?"))
# prompt user for days of delivery
numDays = eval(input("How many days was the paper delivered this week"))
# prompt user for tips recieved
numTips = input("How much did you recieve in tips this week?")
# calculate salary
weekPay = ((numPaper * numDays) * paperCost) * commission
totalPay = weekPay + numTips
# display output
print("This week you delivered", numPaper, "papers")
print("Your salary this week is $", weekPay)
print("Your total tips were $", numTips)
print("Your total pay is $", totalPay)
enter image description here
add this:
if __name__ == "__main__":
main()
just call the main function
def main():
# initialize variables
paperCost = 4
commission = 0.05
# prompt user for number of papers
numPaper = eval(input("How many papers are delivered on your route?"))
# prompt user for days of delivery
numDays = eval(input("How many days was the paper delivered this week"))
# prompt user for tips recieved
numTips = input("How much did you recieve in tips this week?")
# calculate salary
weekPay = ((numPaper * numDays) * paperCost) * commission
totalPay = weekPay + numTips
# display output
print("This week you delivered", numPaper, "papers")
print("Your salary this week is $", weekPay)
print("Your total tips were $", numTips)
print("Your total pay is $", totalPay)
main() # calling main function
I am doing a project for class and can't figure out where I am going wrong. The code works in sections, but when I run it all together it shuts down right after the first input.
I think I need to call functions somewhere - but how and where?
Below is all my code so far, with comments.
import sys
#account balance
account_balance = float(500.25)
##prints current account balance
def printbalance():
print('Your current balance: %2g'% account_balance)
#for deposits
def deposit():
#user inputs amount to deposit
deposit_amount = float(input())
#sum of current balance plus deposit
balance = account_balance + deposit_amount
# prints customer deposit amount and balance afterwards
print('Deposit was $%.2f, current balance is $%2g' %(deposit_amount,
balance))
#for withdrawals
def withdraw():
#user inputs amount to withdraw
withdraw_amount = float(input())
#message to display if user attempts to withdraw more than they have
if(withdraw_amount > account_balance):
print('$%.2f is greater than your account balance of $%.2f\n' %
(withdraw_amount, account_balance))
else:
#current balance minus withdrawal amount
balance = account_balance - withdraw_amount
# prints customer withdrawal amount and balance afterwards
print('Withdrawal amount was $%.2f, current balance is $%.2f' %
(withdraw_amount, balance))
#system prompt asking the user what they would like to do
userchoice = input ('What would you like to do? D for Deposit, W for
Withdraw, B for Balance\n')
if (userchoice == 'D'): #deposit
print('How much would you like to deposit today?')
deposit()
elif userchoice == 'W': #withdraw
print ('How much would you like to withdraw today?')
elif userchoice == 'B': #balance
printbalance()
else:
print('Thank you for banking with us.')
sys.exit()
This part should be as one userchoice = input ('What would you like to do? D for Deposit, W for Withdraw, B for Balance\n')
Not sure if you indented by accident, but python does not like that.
Also, advice for your code. Make it so user can either do uppercase or lowercase letters for input, also make sure it still grab input even if user put empty spaces after input string.
Your withdraw exit the program after entering the string character W.
Balance is not grabbing the correct Deposit.
Use for loops and condition to keep it looping and ask user when to exit.
Hi ive looked at other threads like this but cant find a fix...
Im only including the code where the problem occurs, there is more code but the rest is irreverent.
def transferMoney(self, sender_account, receiver_name, receiver_account_no, amount):
self.sender_account = found_customer
self.reciver_name = customer_name = input("\nPlease input customer name \n")
customer = self.search_customers_by_name(customer_name)
def run_admin_options(self, admin):
loop = 1
while loop == 1:
choice = self.admin_menu(admin.get_name())
if choice == 1:
customer_name= input("Please Enter The Name Of The Customer Sending Money: ")
sender_account_no= int(input("Please Enter the Account Number Of The Person Sending Money: "))
recipient_name= input("Please Enter the name of the person reciving money: ")
recipient_account_no= int(input("Please Enter the recipient account number: "))
found_recipient= self.search_customers_by_name(recipient_name)
found_customer= self.search_customers_by_name(customer_name)
if found_recipient ==None:
return ("Customer Not Found")
else:
if found_customer != None:
my_account= found_customer.get_account()
receiver_account= found_recipient.get_account()
amount_transfer= float(input("Please Enter Amount You Would Like To Send: "))
transferMoney= self.transferMoney(my_account, receiver_account, amount_transfer)
Please give receiver_name parameter value to your function.
In the last line of code you provided you do not have receiver_account_no being passed in. As of now your program thinks the receiver_account_no is actually the amount to be transferred. This leaves the expected amount argument not being passed in.
I have been trying to get this program to work, and it runs but once I got it to run I uncovered this problem. Right now it asks for gradePoint and credit hours and prints out a GPA like it is supposed to, but I can type anything in gradePoint and it will spit out a value. What I want is gradePoint to only work if the user types in a number between 0.0-4.0.
I was thinking of a loop of some sort, like an if loop but is there an easier way (or a preferred way) to do this?
Here's the code:
def stu():
stu = Student
class Student:
def __init__(self, name, hours, qpoints):
self.name = name
self.hours = float(hours)
self.qpoints = float(qpoints)
def getName(self):
return self.name
def getHours(self):
return self.hours
def getQpoints(self):
return self.qpoints
def getStudent(infoStr):
name, hours, qpoints = infoStr.split("\t")
return Student(name, hours, qpoints)
def addGrade(self, gradePoint, credits):
self.qpoints = gradePoint * credits
self.hours = credits
self.gradePoint = float(gradePoint)
self.credits = float(credits)
def gpa(self):
return self.qpoints/self.hours
def main():
stu = Student(" ", 0.0, 0.0)
credits = int(input("Enter Credit Hours "))
gradePoint = float(input("Enter Grade Point"))
if gradePoint > 4.0:
print("Please enter a Grade Point that is less then 4.")
stu.addGrade(gradePoint,credits)
output = stu.gpa()
print("\nStudent GPA is: ", output)
main()
This is the shell printout(I know the grade point is repeated in the GPA, this is for a class and we were supposed to use a skeleton program and change some things):
Enter Credit Hours 4
Enter Grade Point 3.5
Student GPA is: 3.5
Enter Credit Hours 12
Enter Grade Point 3.2
Student GPA is: 3.2
Thanks!
EDIT: I just did an if loop as suggested in the comments and it worked somewhat in that it printed out what I wanted but didn't make it stop and wait for the correct input. I'm not exactly sure how to get it to do that.
Here is the new print from the shell:
Enter Credit Hours 4
Enter Grade Point 3.5
Student GPA is: 3.5
Enter Credit Hours 4
Enter Grade Point 4.5
Please enter a Grade Point that is less then 4.
Student GPA is: 4.5
You can check if user input meet your requirements and throw an exception if not. This will make the program log an error message and stop on invalid user input.
The most basic way to do this is to use an assert statement:
def main():
stu = Student(" ", 0.0, 0.0)
credits = int(input("Enter Credit Hours "))
assert credits > 0 and credits < 4, "Please enter a number of Credit Hours between 0 and 4."
If you wish the application to keep prompting the user until a valid input is entered, you will need at least one while loop.
For exemple:
def main():
stu = Student(" ", 0.0, 0.0)
while True:
credits = int(input("Enter Credit Hours "))
if credits > 0 and credits < 4:
break
else:
print("Please enter a number of Credit Hours between 0 and 4")
while True:
gradePoint = float(input("Enter Grade Point"))
if gradePoint <= 4.0:
break
else:
print("Please enter a Grade Point that is less then 4.")
stu.addGrade(gradePoint,credits)
output = stu.gpa()
print("\nStudent GPA is: ", output)
Create a function that gathers a valid float from the user within a range:
def getValidFloat(prompt, error_prompt, minVal, maxVal):
while True:
userInput = raw_input(prompt)
try:
userInput = float(userInput)
if minVal <= userInput <= maxVal:
return userInput
else: raise ValueError
except ValueError:
print error_prompt
And then use like this:
gpa = getValidFloat(
"Enter Grade Point ",
"You must enter a valid number between 1.0 and 4.0",
1,
4)
The output would look something like this:
Enter Grade Point 6.3
You must enter a valid number between 1.0 and 4.0
Enter Grade Point 3.8