Python code not printing the desired result - python

I'm very new to Python, Just as a way of learning i tasked myself with this problem but no matter what i do the result still comes up to 100000 even when the value is less than the (first condition or second condition) and should print 200000. Please, help.
price = 1000000
credit_score = 300
income = 70000
if credit_score and income:
credit_score > 700 and income > 80000
downpayment = price * 0.10
print(f"Downpayment: {downpayment}")
elif credit_score or income:
credit_score < 700 or income < 80000
downpayment = price * 0.20
print(f"Downpayment: {downpayment}")
else:
downpayment = price * 0.30
print(f"Downpayment: {downpayment}")

You're putting the conditions that you want to test after the if statements, not in them where they belong.
if credit_score > 700 and income > 80000:
downpayment = price * 0.10
print(f"Downpayment: {downpayment}")
elif credit_score < 700 or income < 80000:
downpayment = price * 0.20
print(f"Downpayment: {downpayment}")
else:
downpayment = price * 0.30
print(f"Downpayment: {downpayment}")

Instead of
if credit_score and income:
credit_score > 700 and income > 80000
Do
if credit_score > 700 and income > 80000:
Putting a variable directly as the clause in an if statement (i.e. if credit_score) tries to coerce that variable into a boolean. Any nonzero number or any non-empty string registers as true, which means your code is always taking the first branch.
Instead, what you should be doing is checking the condition credit_score > 700 and the condition income > 80000.

I hope you're already clear about how it works now. I'll just provide another way of doing this:
downpayment = price * 0.10 if (credit_score > 700 and income > 80000) else (price * 0.20 if credit_score < 700 or income < 80000 else price * 0.30)
print(f"Downpayment: {downpayment}")

Related

Pandas: Find ratio of values for a column and then groupby on another column

I am working with the Census Income dataset. You can find the dataset file adult.data in the "Data Folder".
To quickly reproduce the problem, here is how to load it:
training_df = pd.read_csv('adult.data', header = None, skipinitialspace = True)
columns = ['age','workclass','fnlwgt','education','education-num','marital-status',
'occupation','relationship','race','sex','capital-gain','capital-loss',
'hours-per-week','native-country','income']
training_df.columns = columns
I am trying to find out income imbalance for each native_country using a simple ratio:
income imbalance = population with <=50K income / population with >50K income
Here is my most naive and non-Pythonic and non-Pandas way to do it:
def native_country_income_imbalance():
income_dict = {}
for index, data in training_df.iterrows():
native_country = data['native-country']
income = data['income']
# 1st number will store count of >50K and second <=50K
income_count = [0,0]
if not income_dict.get(native_country, False):
if income == '>50K':
income_count[0] += 1
income_dict[native_country] = income_count
else:
income_count[1] += 1
income_dict[native_country] = income_count
else:
if income == '>50K':
income_dict[native_country][0] += 1
else:
income_dict[native_country][1] += 1
for country, incomes in income_dict.items():
# For a native_country where there is no one with >50K
# income, we'll make proportion 0 as a special case
if incomes[0] != 0:
proportion = round(incomes[1] / incomes[0], 2)
else:
proportion = 0
income_dict[country] = proportion
income_dict = dict(sorted(income_dict.items(), key=lambda item: item[1],reverse=True))
return income_dict
call the function
native_country_income_imbalance()
returns the output correctly as
{'Dominican-Republic': 34.0,
'Columbia': 28.5,
'Guatemala': 20.33,
'Mexico': 18.48,
'Honduras': 12.0,
.
.
'Taiwan': 1.55,
'India': 1.5,
'France': 1.42,
'Iran': 1.39,
'Outlying-US(Guam-USVI-etc)': 0,
'Holand-Netherlands': 0}
This is clearly verbose and not something which is utilising Pandas' true power (vectorization + groupby + transform). How do I improve this?
Note: Please feel free to improve the question title.
Pandas solution
Create a frequency table with crosstab, then mask the values where count is zero, then use eval to divide <=50K by >50K column to calculate ratio
s = pd.crosstab(df['native-country'], df['income'])
result = s[s != 0].eval('`<=50K` / `>50K`').fillna(0)
result = result.round(decimals = 2)
result = result.sort_values(ascending=False)
result
native-country
Dominican-Republic 34.00
Columbia 28.50
Guatemala 20.33
Mexico 18.48
Nicaragua 16.00
.
.
India 1.50
France 1.42
Iran 1.39
Outlying-US(Guam-USVI-etc) 0.00
Holand-Netherlands 0.00
dtype: float64

Python Optimization Package

I'm new to the python and analytics world, and I know there are lots of packages out there to solve specific problems. My problem is like follows:
I have some independent variables with a value for each row.
I can calculate some ratios (like payed amount, payed count, bill not payed amount and bill not payed count, in relation to the totals of the dataset).
I have to find the value for each independent variable maximizing the ratios of payed amount and counts and minimizing the ratios for not payed ones.
For example:
amount payed var1 var2 var3
10 1 25 5 10
25 0 21 8 15
30 1 35 3 8
As you can see in this data set the payed and not payed ratios would be:
For the totals.
Payed count: 2/3 ~ 0.67
Payed amount: 40/65 ~ 0.62
Not payed count: 1/3 ~ 0.33
Not payed amount: 25/65 ~ 0.38
I was thinking to compare each split of the independent variables, against the ones in the total and see If there is a gain on the calculations, if so, I can take it as a possible solution, for var1 >= 25
Payed count: 2/2 ~ 1
Payed amount: 40/40 ~ 1
Not payed count: 0/2 ~ 0
Not payed amount: 0/40 ~ 0
This numbers are better that the original ones if we calculate the gain:
Payed count: 1 - 0.67 = 0.33
payed amount: 1 - 0.62 = 0.38
Not payed count: 0.33 - 0 = 0.33
Not payed amount: 0.38 - 0 = 0.38
Total Gain: = 1.42
An so on for each independent variable. Until we get the best splits with the maximum gain.
So seems like the best solution would be:
Var1: >= 25
Var2: <= 5
Var3: <= 10
Is there any tool to solve this? I was thinking of an optimization package but any other approach is welcome.

about half of my if statements not working properly

I am to make a python program using basic operators to ask for an income from the user, in order to calculate the 2017 progressive tax along with 2018. The output should look like this:
Income: 15000
2017 tax: (tax amount here) #will skip the math for samples
2018 tax: (tax amount here)
My program as of now produces both prints for 2017 / 2018 but will stop at the 2018 nested if bracket of 82501 to 157500 (which is nested in the 4th elif)... Here's my program as of now, since its long I'll mark out where it stops working.
income = float(input("Enter your income to calculate tax: "))
#Loop input/calculations
while income > 0:
print("----------------------------------------------")
if income >= 0 and income <= 9325:
bracket1 = income * 0.10
tax2017 = bracket1
print("Income: ",income)
print("2017 tax: ",format(tax2017,'.2f'))
if income >= 0 and income <= 9525:
newbracket1 = income * 0.10
tax2018 = newbracket1
print("2018 tax: ",format(tax2018,'.2f'))
income = float(input("\nEnter your income as and integer with no commas: "))
elif income >= 9326 and income <= 37950:
bracket1 = 9325 * 0.10
bracket2 = (income - 9326) * 0.15
tax2017 = bracket1 + bracket2
print("Income: ",income)
print("2017 tax: ",format(tax2017,'.2f'))
if income >= 9526 and income <=38700:
newbracket1 = 9526 * 0.10
newbracket2 = (income - 9525) * 0.12
tax2018 = newbracket1 + newbracket2
print("2018 tax: ",format(tax2018,'.2f'))
income = float(input("\nEnter your income as and integer with no commas: "))
elif income >= 37951 and income <= 91900:
bracket1 = 9325 * 0.10
bracket2 = (37950 - 9325) * 0.15
bracket3 = (income - 37951) * 0.25
tax2017 = bracket1 + bracket2 + bracket3
print("Income: ",income)
print("2017 tax: ",format(tax2017,'.2f'))
if income >= 38701 and income <= 82500:
newbracket1 = 9526 * 0.10
newbracket2 = (38700 - 9526) * 0.12
newbracket3 = (income - 38700) * 0.22
tax2018 = newbracket1 + newbracket2 + newbracket3
print("2018 tax: ",format(tax2018,'.2f'))
income = float(input("\nEnter your income as and integer with no commas: "))
elif income >= 91901 and income <= 191650:
bracket1 = 9325 * 0.10
bracket2 = (37950 - 9325) * 0.15
bracket3 = (91901 - 37950) * 0.25
bracket4 = (income - 91901) * 0.28
tax2017 = bracket1 + bracket2 + bracket3 + bracket4
print("Income: ",income)
print("2017 tax: ",format(tax2017,'.2f'))
if income >= 82501 and income <= 157500: #HERE STOPS WORKING, the 2018 from here on doesn't print
newbracket1 = 9526 * 0.10
newbracket2 = (38700 - 9526) * 0.12
newbracket3 = (82500 - 38701) * 0.22
newbracket4 = (income - 82500) * 0.24
tax2018 = newbracket1 + newbracket2 + newbracket3 + newbracket4
print("2018 tax: ",format(tax2018,'.2f'))
income = float(input("\nEnter your income as and integer with no commas: "))
elif income >= 191651 and income <= 416700:
bracket1 = 9325 * 0.10
bracket2 = (37950 - 9325) * 0.15
bracket3 = (91901 - 37950) * 0.25
bracket4 = (191650 - 91901) * 0.28
bracket5 = (income - 191651) * 0.33
tax2017 = bracket1 + bracket2 + bracket3 + bracket4 + bracket5
print("Income: ",income)
print("2017 tax: ",format(tax2017,'.2f'))
if income >= 157501 and income <= 200000:
newbracket1 = 9526 * 0.10
newbracket2 = (38700 - 9526) * 0.12
newbracket3 = (82500 - 38701) * 0.22
newbracket4 = (157500 - 82501) * 0.24
newbracket5 = (income - 157500) * 0.32
tax2018 = newbracket1 + newbracket2 + newbracket3 + newbracket4 + newbracket5
print("2018 tax: ",format(tax2018,'.2f'))
income = float(input("\nEnter your income as and integer with no commas: "))
elif income >= 416701 and income <= 418400:
bracket1 = 9325 * 0.10
bracket2 = (37950 - 9325) * 0.15
bracket3 = (91901 - 37950) * 0.25
bracket4 = (191650 - 91901) * 0.28
bracket5 = (416700 - 191650) * 0.33
bracket6 = (income - 416701) * 0.35
tax2017 = bracket1 + bracket2 + bracket3 + bracket4 + bracket5 + bracket6
print("Income: ",income)
print("2017 tax: ",format(tax2017,'.2f'))
if income >= 200001 and income <= 500000:
newbracket1 = 9526 * 0.10
newbracket2 = (38700 - 9526) * 0.12
newbracket3 = (82500 - 38701) * 0.22
newbracket4 = (157500 - 82501) * 0.24
newbracket5 = (200000 - 157501) * 0.32
newbracket6 = (income - 200001) * 0.35
tax2018 = newbracket1 + newbracket2 + newbracket3 + newbracket4 + newbracket5 + newbracket6
print("2018 tax: ",tax2018)
income = float(input("\nEnter your income as and integer with no commas: "))
elif income >= 418401:
bracket1 = 9325 * 0.10
bracket2 = (37950 - 9325) * 0.15
bracket3 = (91901 - 37950) * 0.25
bracket4 = (191650 - 91901) * 0.28
bracket5 = (416700 - 191650) * 0.33
bracket6 = (418400 - 416700) * 0.35
bracket7 = (income - 418401) * 0.396
tax2017 = bracket1 + bracket2 + bracket3 + bracket4 + bracket5 + bracket6 + bracket7
print("Income: ",income)
print("2017 tax: ",tax2017)
income = float(input("\nEnter your income as and integer with no commas: "))
else:
print("invalid")
I've marked the line that wont work. just to clarify, the nested if's and prints before that output both 2017 and 2018 results, but when the income is in the marked range and greater, only 2017's tax will print.
My outcome at income 82502 and above is something like:
Enter your income to calculate tax: 82502
----------------------------------------------
Income: 82502.0
2017 tax: 16364.00
Enter your income as and integer with no commas:
SOLVED:
thanks for all the comments and answers, they cleared some things up for me!
here is what I've reworked, seems to work so I'm satisfied. I'll be adding a few more calculations so hopefully that goes well too :)
income = float(input("Enter your income to calculate tax: "))
#Loop input/calculations
while income > 0:
if income >= 0 and income <= 9325:
bracket1 = income * 0.10
tax2017 = bracket1
print("Income: ",income)
print("2017 tax: ",format(tax2017,'.2f'))
if income >= 0 and income <= 9525:
newbracket1 = income * 0.10
tax2018 = newbracket1
print("2018 tax: ",format(tax2018,'.2f'))
income = float(input("\nEnter your income as and integer with no commas: "))
if income >= 9326 and income <= 37950:
bracket1 = 9325 * 0.10
bracket2 = (income - 9326) * 0.15
tax2017 = bracket1 + bracket2
print("Income: ",income)
print("2017 tax: ",format(tax2017,'.2f'))
if income >= 9526 and income <=38700:
newbracket1 = 9526 * 0.10
newbracket2 = (income - 9525) * 0.12
tax2018 = newbracket1 + newbracket2
print("2018 tax: ",format(tax2018,'.2f'))
income = float(input("\nEnter your income as and integer with no commas: "))
if income >= 37951 and income <= 91900:
bracket1 = 9325 * 0.10
bracket2 = (37950 - 9325) * 0.15
bracket3 = (income - 37951) * 0.25
tax2017 = bracket1 + bracket2 + bracket3
print("Income: ",income)
print("2017 tax: ",format(tax2017,'.2f'))
if income >= 38701 and income <= 82500:
newbracket1 = 9526 * 0.10
newbracket2 = (38700 - 9526) * 0.12
newbracket3 = (income - 38700) * 0.22
tax2018 = newbracket1 + newbracket2 + newbracket3
print("2018 tax: ",format(tax2018,'.2f'))
income = float(input("\nEnter your income as and integer with no commas: "))
if income >= 91901 and income <= 191650:
bracket1 = 9325 * 0.10
bracket2 = (37950 - 9325) * 0.15
bracket3 = (91901 - 37950) * 0.25
bracket4 = (income - 91901) * 0.28
tax2017 = bracket1 + bracket2 + bracket3 + bracket4
print("Income: ",income)
print("2017 tax: ",format(tax2017,'.2f'))
if income >= 82501 and income <= 157500:
newbracket1 = 9526 * 0.10
newbracket2 = (38700 - 9526) * 0.12
newbracket3 = (82500 - 38701) * 0.22
newbracket4 = (income - 82500) * 0.24
tax2018 = newbracket1 + newbracket2 + newbracket3 + newbracket4
print("2018 tax: ",format(tax2018,'.2f'))
income = float(input("\nEnter your income as and integer with no commas: "))
if income >= 191651 and income <= 416700:
bracket1 = 9325 * 0.10
bracket2 = (37950 - 9325) * 0.15
bracket3 = (91901 - 37950) * 0.25
bracket4 = (191650 - 91901) * 0.28
bracket5 = (income - 191651) * 0.33
tax2017 = bracket1 + bracket2 + bracket3 + bracket4 + bracket5
print("Income: ",income)
print("2017 tax: ",format(tax2017,'.2f'))
if income >= 157501 and income <= 200000:
newbracket1 = 9526 * 0.10
newbracket2 = (38700 - 9526) * 0.12
newbracket3 = (82500 - 38701) * 0.22
newbracket4 = (157500 - 82501) * 0.24
newbracket5 = (income - 157500) * 0.32
tax2018 = newbracket1 + newbracket2 + newbracket3 + newbracket4 + newbracket5
print("2018 tax: ",format(tax2018,'.2f'))
income = float(input("\nEnter your income as and integer with no commas: "))
if income >= 416701 and income <= 418400:
bracket1 = 9325 * 0.10
bracket2 = (37950 - 9325) * 0.15
bracket3 = (91901 - 37950) * 0.25
bracket4 = (191650 - 91901) * 0.28
bracket5 = (416700 - 191650) * 0.33
bracket6 = (income - 416701) * 0.35
tax2017 = bracket1 + bracket2 + bracket3 + bracket4 + bracket5 + bracket6
print("Income: ",income)
print("2017 tax: ",format(tax2017,'.2f'))
if income >= 200001 and income < 500000:
newbracket1 = 9526 * 0.10
newbracket2 = (38700 - 9526) * 0.12
newbracket3 = (82500 - 38701) * 0.22
newbracket4 = (157500 - 82501) * 0.24
newbracket5 = (200000 - 157501) * 0.32
newbracket6 = (income - 200001) * 0.35
tax2018 = newbracket1 + newbracket2 + newbracket3 + newbracket4 + newbracket5 + newbracket6
print("2018 tax: ",format(tax2018,'.2f'))
income = float(input("\nEnter your income as and integer with no commas: "))
if income >= 418401:
bracket1 = 9325 * 0.10
bracket2 = (37950 - 9325) * 0.15
bracket3 = (91901 - 37950) * 0.25
bracket4 = (191650 - 91901) * 0.28
bracket5 = (416700 - 191650) * 0.33
bracket6 = (418400 - 416700) * 0.35
bracket7 = (income - 418401) * 0.396
tax2017 = bracket1 + bracket2 + bracket3 + bracket4 + bracket5 + bracket6 + bracket7
print("Income: ",income)
print("2017 tax: ",format(tax2017,'.2f'))
if income >= 500000:
newbracket1 = 9526 * 0.10
newbracket2 = (38700 - 9526) * 0.12
newbracket3 = (82500 - 38701) * 0.22
newbracket4 = (157500 - 82501) * 0.24
newbracket5 = (200000 - 157501) * 0.32
newbracket6 = (500000 - 200001) * 0.35
newbracket7 = (income - 500000) * 0.37
tax2018 = newbracket1 + newbracket2 + newbracket3 + newbracket4 + newbracket5 + newbracket6 + newbracket7
print("2018 tax: ",format(tax2018,'.2f'))
income = float(input("\nEnter your income as and integer with no commas: "))
else:
print("-------------------")
Just work through what statements the program will go through for
income = 82502.0
will enter
elif income >= 37951 and income <= 91900:
but for 2018 calculation, it won't satisfy the conditional inside it
if income >= 38701 and income <= 82500:
So it has no way to calculate 2018. It will not get to the point where you marked it.
2017 calculation should be independent of 2018 calculations. There are lots of cases where your calculation will not print 2018 tax.
But you did have good testing to see that your program is not working. Edge cases generally give problems.

Beginner Python Code Issue: Accumulator Loop

I am a beginner programmer and I am working on an assignment that requires me to do nested loops as part of a finance operation. I have written most of the code and the numbers work according (such as interest and such), however the issue arises when I try print out the savings summary for the years given.
import math
def main():
#This will be hardcoded values for the years running, savings amount and annual interest and calculate the monthly interest rate
savingsAmount = 500
annualInterest = 0.12
yearsRunning = 2
monthlyInterest = annualInterest / 12
#This will state the accumulator variables for totals of investment balance (month), savings (YTD), and interest earned (YTD)
totalInvestBal = 0
totalSavings = 500
totalInterest = 0
#This will begin the accumulator loop process
for i in range (1, yearsRunning + 1):
print "Savings Schedule for Year", i,":"
print "Month Interest Amount Balance"
for i in range (1, 13):
totalInterest = monthlyInterest * totalInvestBal
totalInvestBal = totalSavings + totalInterest + totalInvestBal
totalSavings = totalSavings
print i, round(totalInterest,2), round(totalSavings,2), round(totalInvestBal,2)
print
#i becomes 12 here so we need another answer.
print "Savings summary for year", (need a new way of saying the year here),":"
print "Total amount saved:", totalSavings
print "Total interest earned:", totalInterest
print "End of year balance:", totalInvestBal
main()
Since the "i" loop index variable is updated to 12, I can place that as the year. I am working from year 1 up and I need the savings summary to be from year 1 and up as well. How would that be fixed?
Simply change the second loop variable form i to anything else (e.g. k):
for i in range (1, yearsRunning + 1):
print
print "Savings Schedule for Year", i,":"
print "Month Interest Amount Balance"
for k in range (1, 13):
totalInterest = monthlyInterest * totalInvestBal
totalInvestBal = totalSavings + totalInterest + totalInvestBal
totalSavings = totalSavings
print k, round(totalInterest,2), round(totalSavings,2), round(totalInvestBal,2)
print
#IF WE KEEP ONLY i IT becomes 12 here so we need another -> VARIABLE!!!!! for example K!!.
print "Savings summary for year %s:" %(i) #use this " words words %s words" %(variable name)
print "Total amount saved:", totalSavings
print "Total interest earned:", totalInterest
print "End of year balance:", totalInvestBal
For starters, I added some \t 's to your code- they denote printing a tab for your output so that the output lines up better.
def main():
#This will be hardcoded values for the years running, savings amount and annual interest and calculate the monthly interest rate
savingsAmount = 500
annualInterest = 0.12
yearsRunning = 2
monthlyInterest = annualInterest / 12
#This will state the accumulator variables for totals of investment balance (month), savings (YTD), and interest earned (YTD)
totalInvestBal = 0
totalSavings = 500
totalInterest = 0
#This will begin the accumulator loop process
for i in range (1, yearsRunning + 1):
print
print "Savings Schedule for Year", i,":"
print "Month \tInterest \tAmount \tBalance"
for i in range (1, 13):
totalInterest = monthlyInterest * totalInvestBal
totalInvestBal = totalSavings + totalInterest + totalInvestBal
totalSavings = totalSavings
print i, "\t", round(totalInterest,2), "\t\t", round(totalSavings,2), "\t", round(totalInvestBal,2)
print
#i becomes 12 here so we need another answer.
print "Savings summary for year" #, (need a new way of saying the year here),":"
print "Total amount saved:", totalSavings
print "Total interest earned:", totalInterest
print "End of year balance:", totalInvestBal
main()
Since this is an assignment, I'll point out some errors I see and let you try to fix them. If you look at the output:
Savings Schedule for Year 1 :
Month Interest Amount Balance
1 0.0 500.0 500.0
2 5.0 500.0 1005.0
3 10.05 500.0 1515.05
4 15.15 500.0 2030.2
5 20.3 500.0 2550.5
6 25.51 500.0 3076.01
7 30.76 500.0 3606.77
8 36.07 500.0 4142.84
9 41.43 500.0 4684.26
10 46.84 500.0 5231.11
11 52.31 500.0 5783.42
12 57.83 500.0 6341.25
Savings summary for year
Total amount saved: 500
Total interest earned: 57.8341733327
End of year balance: 6341.2515066
your balance isn't correct, look at this line of code for a solution:
totalInvestBal = totalSavings + totalInterest + totalInvestBal
For your question, the way I'm interpreting it is that you want to have a separate interest-earned value in just the timeframe of a year, after the first year. So the output that I think you want for year 2 is (assuming you fix the end of year balances):
Savings Schedule for Year 2 :
Month Interest Amount Balance
1 63.41 500.0 6904.66
2 69.05 500.0 7473.71
3 74.74 500.0 8048.45
4 80.48 500.0 8628.93
5 86.29 500.0 9215.22
6 92.15 500.0 9807.37
7 98.07 500.0 10405.45
8 104.05 500.0 11009.5
9 110.1 500.0 11619.6
10 116.2 500.0 12235.79
11 122.36 500.0 12858.15
12 128.58 500.0 13486.73
Savings summary for year
Total amount saved: 500
Total interest earned: 70.74733
End of year balance: 13486.7324266
Is that correct?

payroll program, need help simply a patterned event, new to python

so i'm learning python and decided to program a payroll for my company as practice.
for the usa bi-weekly tax, there is pattern to the amount you need to pay, here is a short code for example
if n >= 760 and n < 780:
gt = 45
if n >= 780 and n < 800:
gt = 47
if n >= 800 and n < 820:
gt = 49
if n >= 820 and n < 840:
gt = 51
here n is the salary, and gt is the tax to be paid.
as you can see, the range of n is a constant 20, and tax increase by a constant 2
this is true from 720 - 1000, starting from 1000 however, the rate of the tax increases by constant 3
i want to to be able to include a salary range from 720 to 2000, is there a way to do this, or do i have to do it the hard way and write them all out?
I'd branch on your two ranges and then use some math to get the tax amount:
if n >= 720 and n < 1000:
gt = 2*(( n - 720 ) / 20) + 41
elif n >= 1000 and n < 2000:
gt = 3*(( n - 1000 ) / 20) + 67

Categories

Resources