Python loop statements - python-3.x

I have been working on a program for my homework:
Write a program for a car salesperson who works a five day week. The program should prompt for how many cars were sold on each day and then prompt for the selling price of each car (if any) on that day. After the data for all five days have been entered, the program should report the total number of cars sold and the total sales for the period. See example output. NOTE: duplicate the currency format shown for the total sales,
Example Output
How many cars were sold on day 1? 1
Selling price of car 1? 30000
How many cars were sold on day 2? 2
Selling price of car 1? 35000
Selling price of car 2? 45000
How many cars were sold on day 3? 0
How many cars were sold on day 4? 1
Selling price of car 1? 30000
How many cars were sold on day 5? 0
You sold 4 cars for total sales of $140,000.00
I do have some code that I have worked on but I am stuck. I can figure out how to get the program to prompt the user for how many cars were sold on day 2 and so on. Any help would be appreciated!
Here is my code, I am also taking a basic python course so I am new to this!!
def main () :
cars_sold = []
num_days = int(input('How many days do you have sales?'))
for count in range(1, num_days + 1):
cars = int(input('How many cars were sold on day?' + \
str(count) + ' '))
while (cars != cars_sold):
for count in range(1, cars + 1):
cars_sold = int(input('Selling price of car' ' ' + \
str(count) + ' '))
main ()

For this you would want to use nested for loop to prompt for each car entered.
def main():
cars_sold = 0
total = 0
num_days = int(input('How many days do you have sales? '))
# for each day
for i in range(1, num_days + 1):
num_cars = int(input('How many cars were sold on day {0}? '.format(i)))
cars_sold += num_cars
# for each car of each day
for j in range(1, num_cars + 1):
price = int(input('Selling price of car {0}? '.format(j)))
total += price
# Output number of cars and total sales with $ and comma format to 2 decimal places
print('You sold {0} cars for total sales of ${1:,.2f}'.format(cars_sold, total))
# Output
>>> main()
How many days do you have sales? 5
How many cars were sold on day 1? 1
Selling price of car 1? 30000
How many cars were sold on day 2? 2
Selling price of car 1? 35000
Selling price of car 2? 45000
How many cars were sold on day 3? 0
How many cars were sold on day 4? 1
Selling price of car 1? 30000
How many cars were sold on day 5? 0
You sold 4 cars for total sales of $140,000.00

Related

How do I assign a value to a word?

I'm creating a calculating list for the user to select from such as: pepsi, sprite, coke
and after user selects their fav drink, it will calculate: the calories(they all have diff. calories) + plus how many they drink per week + per year and then Print how many total calories they consume per year.
I got the math part down but I can't figure out how to add the "drink" they select into the final output.
EXAMPLE:
pepsi 100
sprite 200
coke 300
So, if they select pepsi, it should then take variable pepsi, then add how many per day + week + year then print total calories for year. Make sense?
right now it just prints the same number for any selection. when clearly the calories will vary.
Here is how I tried coding it:
cans_per_day = int(input("\nHow many cans per day?\n"))
sodas_per_week = int(input("How many cans do you drink per week?\n"))
drink_of_choice = input("What's your drink of choice?\n\n" + "Pepsi\nWild Cherry Coke\nOrange Fanta\nMountain Dew\nMello Yello\nSprite\n\n")
drink_of_choice = input + 41 * cans_per_day * sodas_per_week * 4 * 12 / (453.592)
print(drink_of_choice)
You can just check which drink is selected with something like this (if you use python):
if drink == "pepsi":
calories = 100
elif drink == "sprite":
calories = 200
elif drink == "coke":
calories = 300
then you can just multiply with calories in your calculation

How to map sales against purchases sequentially using python?

I have a transaction dataframe as under:
Item Date Code Qty Price Value
0 A 01-01-01 Buy 10 100.5 1005.0
1 A 02-01-01 Buy 5 120.0 600.0
2 A 03-01-01 Sell 12 125.0 1500.0
3 A 04-01-01 Buy 9 110.0 990.0
4 A 04-01-01 Sell 1 100.0 100.0
#and so on... there are a million rows with about thousand items (here just one item A)
What I want is to map each selling transaction against purchase transaction in a sequential manner of FIRST IN FIRST OUT. So, the purchase that was made first will be sold out first.
For this, I have added a new column bQty with opening balance same as purchase quantity. Then I iterate through the dataframe for each sell transaction to set the sold quantity off against purchase transaction before that date.
df['bQty'] = df[df['Code']=='Buy']['Quantity']
for each in df[df['Code']=='Sell']:
for each in df[(df['Code']=='Buy') & (df['Date'] <= sellDate)]:
#code#
Now this requires me to go through the whole dataframe again and again for each sell transaction.
For 1000 records it takes about 10 seconds to complete. So, we can assume that for a million records, this approach will take a lot time.
Is there any faster way to do this?
If you are only interested in the resulting final balance values per item, here is a fast way to calculate them:
Add two additional columns that contain the same absolute values as Qty and Value, but with a negative sign in those rows where the Code value is Sell. Then you can group by item and sum these values for each item, to get the remaining number of items and the money spent for them on balance.
sale = df.Code == 'Sell'
df['Qty_signed'] = df.Qty.copy()
df.loc[sale, 'Qty_signed'] *= -1
df['Value_signed'] = df.Value.copy()
df.loc[sale, 'Value_signed'] *= -1
qty_remaining = df.groupby('Item')['Qty_signed'].sum()
print(qty_remaining)
money_spent = df.groupby('Item')['Value_signed'].sum()
print(money_spent)
Output:
Item
A 11
Name: Qty_signed, dtype: int64
Item
A 995.0
Name: Value_signed, dtype: float64

Why I am getting StatisticsError: no unique mode; found 2 equally common values while creating a pivot table?

Suppose I have this (randomic) df_bnb:
neighbourhood room_type price minimum_nights
0 Allen Pvt room 38 5
1 Arder Entire home/apt 90 2
2 Arrochar Entire home/apt 90 2
3 Belmont Shared Room 15 1
4 City Island Entire home/apt 100 3
Every row represents an Airbnb's booking.
I hope to generate a pivot_table in which Index is the column neighbourhood and columns are others data frame columns ['room_type', 'price', 'minimun_nights'].
I want entries of the abovementioned columns as mean, expect for room_type where I wish to have the mode. Like the following dataframe's example:
room_type price minimum_nights
Allen room type mode for Allen price mean for Allen mean min nights for Allen
Arder room type mode for Arder price mean for Arder mean min nights for Arder
Arrochar room type mode for Arrochar price mean for Arrochar mean of min nights for Arrochar
Belmont room type mode for Belmont price mean for Belmont mean of min nights for Belmont
City Island room type mode for City Island price mean fot City Is. mean of min nights for City Island
This is the code I try so far:
bnb_pivot = pd.pivot_table(bnb,
index = ['neighborhood'],
values = ['room_type', 'price',
'minimum_nights','number_of_reviews'],
aggfunc = {'room_type': statistics.mode,
'price' : np.mean,
'minimum_nights': np.mean,
'number_of_reviews': np.mean})
This is the error that I am getting:
StatisticsError: no unique mode; found 2 equally common values
I try to search for other sources, but I don't how to treat statistic.mode() while creating a pivot_table.
Many thanks in advance for any helpful indication!

Python Incorrect Values

I'm working on an assignment that implements while and for loops to calculate the cost of tuition each year for the next 5 years, when the initial amount is 8000 and increases 3% each year.
My program works, but I'm getting the wrong values when I actually calculate the projected tuition.
In
-------------------
tuition = 8000
increase = 0.03
tuition_total = 0
for year in range(0, 6):
tuition += ((tuition * increase) * year)
print(tuition, '\t', year)
Out
-------------------
8000.00 0
8240.00 1
8734.40 2
9520.49 3
10662.95 4
12262.39 5
According to the assignment written by my teacher, here are what the values are supposed to be:
In 1 year, the tuition will be 8240.00.
In 2 years, the tuition will be 8487.20.
In 3 years, the tuition will be 8741.82.
In 4 years, the tuition will be 9004.07.
In 5 years, the tuition will be 9274.19.
Are my operations off? Would appreciate any suggestions for what I should change. Thanks!
You are super close. Ask yourself, why you are multiplying (tuition * increase) by year?
The year that the tuition increase happens should be independent of the increase itself. Thus your for loop should be of the form:
for year in range(0, 6):
tuition += (tuition * increase)
print(tuition, '\t', year)
This should give you the same answers that your teacher provided as well.

Determining Profit Python

I am writing a program to determine a car salesman profit for a new or pre-owned vehicle.
I need to express all three outputs in currency format with the $ sign right up against the first digit and two decimal places.
I need to add commas for any profit earned over $1000.
The salesman gets 25% profit from a pre-owned sale and 35% profit from new sales.
Pseudocode
Start Program
The salesperson gets 25% dealer profit on pre-owned vehicles.
The salesperson gets 35% dealer profit
Enter the total dealer profit on pre-owned vehicles sold.
Enter total dealer profit on new vehicles sold.
The input type should float.
Compute and display commission amounts
Compute and display the total commission.
Print out the sum.
End Program
Code so far
def main():
pre-owned_vehicles = float(input("Enter total profit on pre-owned vehicles sold * 0.25: "))
new_vehicles = float(input("Enter total profit on new vehicles sold * 0.35: "))
commission pre-owned sales = float(input("Enter commission pre_owned: "))
commission new sales = float(input("Enter commission new: "))
total = profit + commission
print('Pre-owned sales profit is $')
format(new sale profit, ',.2f)
main()
You are getting a SyntaxError because you cannot have variable names with hyphens (or spaces) in between, it thinks you are trying to subtract. Thus, change your code to:
pre-owned_vehicles = float(input("Enter total profit on pre-owned vehicles sold * 0.25: "))
And carry on.
>>> foo-bar = 'foo-bar'
File "<stdin>", line 1
SyntaxError: can't assign to operator
>>> foo_bar = 'foo-bar'
>>>

Resources