working on a payroll calculation program - loops

I'm working on a payroll calculation and I have to get it to loop
while name= karen:
name = (input("enter employees name"))
if karen>0:
hours=float(input("enter hours worked"))
rate=float(input('enter hourly rate'))
total= (hours)*(rate)+(overtimetotal)
print (total)
# when over time
if hours>40:
overtimerate=1.50
overtimetotal= (total)* (overtimerate)
print (overtimetotal)
my instructor said "There should not be an input for overtimehours. You are calculating it by taking the hours-40
You need to calculate the total as total=hours*rate+overtimetotal
You need to have a while loop to checking the name !="0"
everything in the loop block will be indented."
Im lost at what to write to start the loop.

Related

having issues adding an input to an array

I have a problem that I think is asking me to have a user enter a input into a array. I am having difficulties understanding this and any help would be appreciated.
The problem is as follows:
Design a program that lets the user enter the total rainfall for each of 12 months into an array. The program should calculate and display the total rainfall for the year, the average monthly rainfall, and the months with the highest and lowest amounts.
Here is what I have wrote so far:
def get_rainfall(a, b)
rain_array = []
rain_array.push(a => b)
puts rain_array
end
get_rainfall('january', 300)
Thanks for updating the question C_B.
I think the slight issue you're having here is between hashes and arrays.
Your current method results in the following:
#=> [{"january"=>300}, {"february"=>...}]
This happens because when you call rain_array.push(a => b), you're pushing a hash to the array each time in a => b.
It seems to me you'd be better suited storing the whole things as a hash, perhaps:
hash = {}
def get_rainfall(hash, key, value)
hash[key] = value
puts hash
end
get_rainfall(hash, 'january', 300)
# {"january"=>300}
get_rainfall(hash, 'february', 200)
#{"january"=>300, "february"=>200}
Hash you add more entries, they will be stored under the month as the key, with the rainfall as the value.
Alternatively, you could also push an array of arrays - to tweak your current method:
rain_array = []
def get_rainfall(array, a, b)
array.push([a, b])
puts array
end
get_rainfall(rain_array, 'january', 300)
# january
# 300
get_rainfall(rain_array, 'february', 200)
# january
# 300
# february
# 200
You'll notice I'm pulling the declaration of the array or hash to store the values outside of the method; without this, you'll lose access to it as soon as the method has run.
Hope that helps - happy to expand if you've any questions or queries. Let me know how you get on.
One more update based on a further comment about getting user input. Try the following to get you started:
hash = {}
def get_rainfall(hash, month)
puts "Please enter value for #{month}"
hash[month] = gets.chomp
puts hash
end
get_rainfall(hash, 'january')
I'll write my answer in simple script form to not over complicate what is being asked here.
The minimal approach is to not worry about month names for now and simply collect a list (array) of 12 values to do the calculations with.
rainfall = 1.upto(12).map do |month_nr|
# `print` and `puts` are practically the same with the only difference being
# that `puts` adds a newline character to the string if it doesn't have one
# output the question to the user
print "enter the rainfall for month #{month_nr}: "
# get the input from the user and convert it into an integer
gets.to_i # output the rainfall
end
puts "the total rainfall is: #{rainfall.sum}"
puts "the average rainfall is: #{rainfall.sum / rainfall.size}"
puts "the highest rainfall is: #{rainfall.max}"
puts "the lowest rainfall is: #{rainfall.min}"
If you care about month names you can do the following:
# create an array of all months
months = %w[January February March April May June July August September October November December]
# ask the user for each moth the amount of rainfall
rainfall = months.map do |month_name|
print "enter the rainfall for month #{month_name}: "
[month_name, gets.to_i] # output both the month name and the rainfall provided
end
# convert [['January', 123], ['February', 456], ...]
# to { 'January' => 123, 'February' => 456, ... }
rainfall = rainfall.to_h
puts "the total rainfall is: #{rainfall.values.sum}"
puts "the average rainfall is: #{rainfall.values.sum / rainfall.size}"
# search the key with the highest value
puts "the month with the highest rainfall is: #{rainfall.key(rainfall.values.max)}"
# search the key with the lowest value
puts "the month with the lowest rainfall is: #{rainfall.key(rainfall.values.min)}"
If anything is unclear have a look at the reference of the thing it is you have difficulty with. If it's still unclear ask away in the comments.
references:
String interpolation ("1 + 1 = #{1 + 1}")
Integer#upto
Enumerable#map
Kernel#print output to standard output without appending newline
Kernel#gets read from standard input
String#to_i
Kernel#puts output to standard output while appending a newline character (unless already present)
Array#sum
Array#size
Array#max
Array#min
%w array of strings
Array#to_h convert array to a hash
Hash#values
Hash#key

SAS code is giving error for Do-While loop

I need to print the fuel consumption and mileage of the car in SAS code. if given that mileage is 20 miles per gallon.
It should stop generating output if fuel reaches to 10 gallon OR car travel 250 miles.
My code:
data milage;
fuel=1;
do while (fuel<11);
miles = fuel*20;
fuel+1;
output;
end;
run;
My output:
Code Output
The output for fuel needs to be started from 1 for first 20 miles which incorrect in my code. Any suggestion on what I am missing here.
Thanks!!
Add an explicit OUTPUT for the first line or start at 0 instead. If
you start at 0, make sure the order of the fuel and miles
calculation are correct.
Change your loop condition to be <10 and add in the MILES criteria
as well. In this case you're only looping if fuel<10 AND the miles
lt 250. Make sure the boundaries are what you want.
data milage;
fuel=0; miles=0;
do while (fuel<10 and miles lt 250);
fuel+1;
miles = fuel*20;
output;
end;
run;

Python loop to print salaries within range of the average

I'm an absolute beginner to Python and am tasked with creating a program that does a few things:
Inputs employee names into a list.
Inputs that employee's salary after inputting their name.
Totals the salaries in a list, (2 lists: names[] and salaries[]).
Finds the average salary after totaling.
Prints employees that earn within $5,000 of the average salary (Where I'm stuck).
Please see my code below:
# function to total the salaries entered into the "newSalary" variable and "salaries[]".
def totalSalaries(salaries):
total = 0
for i in salaries:
total += i
return total
# Finds the average salary after adding and dividing salaries in "salaries[]".
def averageSalaries(salaries):
l = len(salaries)
t = totalSalaries(salaries)
ave = t / l
return ave
# Start main
def main():
# Empty names list for "name" variable.
names = []
# Empty salaries list for "salary" and "newSalary" variables.
salaries = []
# Starts the loop to input names and salaries.
done = False
while not done:
name = input("Please enter the employee name or * to finish: ")
salary = float(input("Please enter the salary in thousands for " + name + ": "))
# Try/except to catch exceptions if a float isn't entered.
# The float entered then gets converted to thousands if it is a float.
try:
s = float(salary)
# Message to user if a float isn't entered.
except:
print("Please enter a valid float number.")
done = False
newSalary = salary * 1000
# Break in the loop, use * to finish inputting Names and Salaries.
if name == "*":
done = True
# Appends the names into name[] and salaries into salaries[] if * isn't entered.
# Restarts loop afterwards if * is not entered.
else:
names.append(name)
salaries.append(newSalary)
# STUCK HERE. Need to output Names + their salaries if it's $5,000 +- the total average salary.
for i in range(len(salaries)):
if newSalary is 5000 > ave < 5000:
print(name + ", " + str(newSalary))
# Quick prints just to check my numbers after finishing with *.
print(totalSalaries(salaries))
print(averageSalaries(salaries))
main()
Any info is greatly appreciated. I hope the rest of the functions and logic in this program makes sense.
Your haven't written your iterator correctly. With an array, you can just use for element in array: and the loop will iterate over array by putting each element in element. So your for loop becomes for salary in salaries.
Also, You need to split your condition in two and use additions and substractions. Your code should check if the salary is higher or equal to the average minus 5000 and if it is lower or equal to the average plus 5000. If you want to formalize this mathematically it would be:
Salary >= Average - 5000
and
Salary <= Average + 5000
So the condition at line becomes if salary >= (average - 5000) and salary <= (average + 5000)
Finally, you do not call averageSalaries before entering the loop, so the average salary haven't been computed yet. You should call the function and put the result in a variable before your for loop.

about check the number from string

This is my plan. {i using linux(mac(xcode&terminal))}
Name of program is Tour Company.
Ask for the user's first name and the discount code (3 letters plus 1 digit, e.g. "AGF2",or 0 if no discount code available).
---so i will use fgets to get string , How check last number , [guide #1]---
When the user enters a name equal to "END", you have reached the end of the day.
---how check input string = 'end' [guide #2]---
For each customer, repeatedly ask date of the tour (dd/mm/yyyy), which tour, and the number of people going on the tour.
Available tours are "London" (800/person), "Paris" (1000/person),*"Rome" (1400 baht/person)* and "Moscow" (2500 baht/person).
If the user has a discount code, take 15% off the total price if there are 1-4 people on a tour, 20% for 5 or more people. ---check from #1 so i will use 2 function---
When the customer enters a date beginning with "00", print an invoice showing the customer name plus information about each booked tour: date, tour name, number of people, total price before discount, discount amount, total price after discount.
The invoice should also show the total price for this customer.
---how to check have 00 before date? [guide#3]---
[from #2]At the end of the day, print a summary showing the number of customers who had discount codes, number of customers without discount codes, the total money received for each of the four tour types before discounts, the total discounts for each tour type, and the
overall total money received.---I not have problem about this ---
I'm newbie of C programing
---I want to make this programs without using pointers---
Thanks for help.
Ps.I'm weak about using english, sorry about grammar & meaning.
You can use strcmp() or strncmp() ,to compare input with "end"
fgets(input,MAX_SIZE,stdin);
if(strncmp(input,"end",3)==0)
{
//you have reached the end of the day
}

MATLAB receipt print random values issue

I have a project where I must make the following;
You have a small business and you sell 6 different products. Choose your products
and their prices within the range of 20p to £25.00 (these could be completely fictitious). Your
shop has 4 employees, one of whom will be at the till at the time of purchase.
Your task is to write MATLAB code to prepare a receipt for a fictitious transaction as explained
below.
There is a customer at the till. They want to purchase 3 random products with specific
quantities for each. For example, the customer wants 2 cappuccinos, 1 croissant and 6 raspberry
muffins.
(1) Select randomly 3 products from your list. For each product choose a random quantity
between 1 and 9.
(2) Calculate the total cost.
(3) Choose randomly the staff member to complete the transaction.
(4) Suppose that the price includes 20% VAT. Calculate the amount of VAT included in the price.
(6) Prepare the receipt as text in the MATLAB command window. Use the current date and time
(check datestr(now,0)).
Your code should output the receipt in the format shown in the picture. There should be
60 symbols across. Choose our own shop name.
My code so far is the following:
clear all
clc
close all
items = {'apples ','carrots ','tomatoes','lemons ','potatoes','kiwis '};% products
price = {3.10, 1.70, 4.00, 1.65, 9.32, 5.28};% item prices. I set spaces for each entry in order to maintain the border format.
employee = {'James','Karina','George','Stacey'};%the employees array
disp(sprintf('+-----------------------------------------------+'));
disp(sprintf('|\t%s \t\t\tAlex''s Shop |\n|\t\t\t\t\t\t\t\t\t\t\t\t|', datestr(now,0)));
totalPrice = 0;
for i = 1:3
randItems = items {ceil(rand*6)};
randprice = price {ceil(rand*6)};
randQuantity = ceil(rand*9);% random quantity from 1 to 9 pieces
randEmployee = employee{ceil(rand*4)};
itemTotal = randprice * randQuantity;%total price of individual item
totalPrice = totalPrice + itemTotal;
disp(sprintf('|\t%s\t (%d) x %.2f = £ %.2f \t\t\t|', randItems, randQuantity, randprice, itemTotal))
end
disp(sprintf('|\t\t\t\t-----------------------------\t|'));
disp(sprintf('|\t\t\t\t\t\t\t\t\t\t\t\t|\n|\t Total to pay \t £ %.2f\t\t\t\t|',totalPrice));
disp(sprintf('|\t VAT \t\t\t\t £ %.2f\t\t\t\t| \n|\t\t\t\t\t\t\t\t\t\t\t\t|', totalPrice*0.2));
disp(sprintf('|\tThank you! You have been served by %s\t|\t', randEmployee));
disp(sprintf('+-----------------------------------------------+'));
My issue of course is the following. Upon choosing a random item from the items list, I then choose a random price to assign as well. I don't want this though. I would like to find a way to assign a preset price to each item to be printed automatically when generating a random item to be added to the basket. I hope this explanation is sufficient for you, if you have any questions feel free to ask. Thank you in advance.
When you write
randItems = items {ceil(rand*6)};
randprice = price {ceil(rand*6)};
you calculate a random index into the array items, and then you calculate a random index into the array price. If you instead assign the index you calculate via ceil(rand*6) to a separate variable, called e.g. index, you can re-use it to pick, say, item #3 from both items and price. Thus, the ith item will always show up with the ith price.

Resources