I keep getting None - python

My code:
def get_feedback(mark, out_of):
percentage = int((mark / out_of) * 100)
if percentage >= 80:
print("Excellent")
if 60 < percentage < 70:
print("Good")
if 50 < percentage < 59:
print("Pass")
if percentage < 50:
print("Not a pass")
I know I have to use a return statement somewhere but I'm not really sure how it works or when to use it. If anyone could help, that would be great thank you!

def get_feedback(mark, out_of):
percentage = int((mark / out_of) * 100)
remark = ''
if percentage >= 80:
remark = "Excellent"
elif 60 <= percentage <= 79:
remark = "Good"
elif 50 <= percentage <= 59:
remark = "Pass"
else percentage < 50:
remark = "Not a pass"
return remark
Some suggestions:
I believe you need inclusive range, so include <= instead of <
If one condition satisfies, no need to check the rest of the conditions. So instead of using if for every check, use if - elif- else checks.
Also your question says the range between 60 and 79 for grade 'Good'. You haven't checked it.

Use return in place of print. Example :- return "Excellent".

Another way to do it :
def get_feedback(mark, out_of):
percentage = int((mark / out_of) * 100)
if percentage >= 80:
return "Excellent"
elif 60 <= percentage <= 79:
return "Good"
elif 50 <= percentage <= 59:
return "Pass"
else:
return "Not a pass"

You can make a variable to represent the value of its condition.
def get_feedback(mark, out_of):
percentage = int((mark / out_of) * 100)
if percentage >= 80:
feedback = "Excellent"
elif 60 < percentage < 70:
feedback = "Good"
elif 50 < percentage < 59:
feedback = "Pass"
elif percentage < 50:
feedback = "Not a pass"
return print(feedback)
At the very end, we use return to give us the result of the function. Also, notice that I used elif statements, which are faster than just using if statements.

Related

Returns None instead of False

So I'm working on a question on CodingBat, a website that provides JS and Python practice problems. I've encountered a unexpected output. Btw here's the link to the question: https://codingbat.com/prob/p135815 . In theory my code should return False but it returns none when I put print(squirrel_play(50, False))
Code:
def squirrel_play(temp, is_summer):
if is_summer:
if temp <= 100:
if temp >= 60:
return True
elif temp <= 60:
return False
elif temp >= 100:
return False
if not is_summer:
if temp <= 90:
if temp >= 60:
return True
elif temp >= 90:
return False
elif temp <= 60:
return False
when I run that with print(squirrel_play(50, False)), I get None (I should get False)
Why???
With your parameter of is_summer of False, you're in the 2nd conditional block:
if not is_summer:
if temp <= 90:
if temp >= 60:
return True
elif temp >= 90:
return False
elif temp <= 60:
return False
Then follow this block:
is the temp less than 90? yes. so now we're in this block:
if temp <= 90:
if temp >= 60:
return True
What is happening here is that you never get to the elif temp <= 60 because you are in the first conditional instead. You could only ever get to the elif below if you didn't satisfy the first condition.
At the end of this if temp <= 90 block the entire conditional chain ends and your function returns the default value of None because you didn't provide another return value.
You can maybe more clearly see this by making the entire code read:
def squirrel_play(temp, is_summer):
if is_summer:
if temp <= 100:
if temp >= 60:
return True
elif temp <= 60:
return False
elif temp >= 100:
return False
if not is_summer:
if temp <= 90:
if temp >= 60:
return True
else:
return "This is where I'm returning with 50, and True as my parameters"
elif temp >= 90:
return False
elif temp <= 60:
return False
Did you try to debug it?
With squirrel_play(50, False) it will fall into:
def squirrel_play(temp, is_summer):
if is_summer:
if temp <= 100:
if temp >= 60:
return True
elif temp <= 60:
return False
elif temp >= 100:
return False
if not is_summer:
if temp <= 90:
if temp >= 60:
return True
# HERE ( 50 is less than 90 but not greater than 60 )
# and you have no return statement for this case
elif temp >= 90:
return False
elif temp <= 60:
return False
If you don't return a value from a Python function, None is returned by default. I believe that what is happening here is that because you are using elif statements, since the clause if not is_summer: if temp <= 90: is being entered, the final clause elif temp <= 60 is not being reached. Therefore the function gets passed all of the if/elif statements without returning a value, and returns None.
A simple solution is to replace all of the elifs with ifs. Then print(squirrel_play(50, False)) returns False (for me at least).
The way that you have currently coded it, in your
if temp <= 90:
if temp >= 60:
return True
elif ....
if the first if test evaluates True but the second one evaluates False, then no return statement is reached (bear in mind that the subsequent elif tests are not performed because the first if evaluated true), and the function therefore returns None.
In fact you can simplify the function making use of chained comparison operators:
def squirrel_play(temp, is_summer):
if is_summer:
return 60 <= temp <= 100
else:
return 60 <= temp <= 90

Issues with replicating results from R to python by writing customised function

I am trying to convert the R code to python by writing customised function or without function in python based on this following lines of code
customers_df$segment = "NA"
customers_df$segment[which(customers_df$recency > 365*3)] = "inactive"
customers_df$segment[which(customers_df$recency <= 365*3 & customers_df$recency > 365*2)] = "cold"
customers_df$segment[which(customers_df$recency <= 365*2 & customers_df$recency > 365*1)] = "warm"
customers_df$segment[which(customers_df$recency <= 365)] = "active"
customers_df$segment[which(customers_df$segment == "warm" & customers_df$first_purchase <= 365*2)] = "new warm"
customers_df$segment[which(customers_df$segment == "warm" & customers_df$amount < 100)] = "warm low value"
customers_df$segment[which(customers_df$segment == "warm" & customers_df$amount >= 100)] = "warm high value"
customers_df$segment[which(customers_df$segment == "active" & customers_df$first_purchase <= 365)] = "new active"
customers_df$segment[which(customers_df$segment == "active" & customers_df$amount < 100)] = "active low value"
customers_df$segment[which(customers_df$segment == "active" & customers_df$amount >= 100)] = "active high value"
table(customers_2015$segment)
active high value active low value cold inactive
573 3313 1903 9158
new active new warm warm high value warm low value
1512 938 119 901
Python Function
I tried to replicate the same code as above in python by writing function. However, I was not able to get the same categories as R as a well number in each category also differs.
def mang_segment (s):
if (s['recency'] > 365*3):
return ("inactive")
elif (s['recency'] <= 365*3) & (s['recency'] > 365*2):
return ("cold")
elif (s['recency'] <= 365*2) & (s['recency'] > 365*1):
return ("warm")
elif (s['recency'] <= 365):
return ("active")
def mang_segment_up (s):
# if (s['recency'] > 365*3):
# return ("inactive")
# elif (s['recency'] <= 365*3 & s['recency'] > 365*2):
# return ("cold")
# elif (s['recency'] <= 365*2 & s['recency'] > 365*1):
# return ("warm")
if (s['segment'] == "warm") & (s['first_purchase'] <= 365*2):
return ("new warm")
elif (s['segment'] == "warm") & (s['amount'] < 100):
return ("warm low value")
elif (s['segment'] == "warm") & (s['amount'] >= 100):
return ("warm high value")
elif (s['segment'] == "active") & (s['first_purchase'] <= 365):
return ("new active")
elif (s['segment'] == "active") & (s['amount'] < 100):
return ("active low value")
elif (s['segment'] == "active") & (s['amount'] >= 100):
return ("active high value")
active low value 19664
warm low value 4083
active high value 3374
new active 1581
new warm 980
warm high value 561
Any pointer/suggestion would be appreciated.
Thanks in advance
I am a little confused about the purpose of the function (and if it is working as you expect). If you are seeking to mimic your R code within a function, your syntax can line up much closer with your initial code than it currently is. Assuming you are using panads/numpy:
import numpy as np
import pandas as pd
#toy example
s = pd.DataFrame({'rec' : [2000, 1500, 3000, 750]})
def mang_segment (s):
s.loc[(s['rec'] > 365*3), 'seg'] = "inactive" # creating a new column seg with our values
s.loc[(s['rec'] <= 365*3) & (s['rec'] > 365*2), 'seg'] = "cold"
#etc...
#run function
mang_segment(s)
#get value counts
s['seg'].value_counts()
Here we add a column to our dataframe to capture our values, which we can later summarize. This is different than the return function that, if it were working and call appropriately, would not assign it directly to your data frame.
There are other function and ways to get it at this, too. Check out np.where as another option.

SyntaxError for code : invalide syntax on 'def function' Grade letter

calculate and return the letter grade that would appear in the transcript
i have tried my code, in the past and it seemed to have worked without a problem, but now, i am getting a invalid syntax, and im not sure of the reason.
#python
def letter_grade(pct):
if pct <= 49:
return 'F'
elif pct <= 52:
return 'D-'
elif pct <= 56:
return 'D'
elif pct <= 59:
return 'D+'
elif pct <= 62:
return 'C-'
elif pct <= 66:
return 'C'
elif pct <= 69:
return 'C+'
elif pct <= 72:
return 'B-'
elif pct <= 76:
return 'B'
elif pct <= 79:
return 'B+'
elif pct <= 84:
return 'A-'
elif pct <= 89:
return 'A'
else:
return 'A+'
# input letter_grade(45)
expeted => # input letter_grade(45) --> F
actual result => # def letter_grade(45)
File "<ipython-input-11-06219c433935>", line 1
def letter_grade(45)
^
SyntaxError: invalid syntax
It's a little difficult to read because your formatting is off, but I think you're trying to call the function with def in front. The def only goes in front of the function definition, not when you call it.
The problem is with the return type. You need to store the value in a variable in order to get the result.
Try calling the function by using
value = letter_grade(45)
print(value)

Python Ranking Program Using Numbers

The promoter wants to be able to classify donors based on how much they have contributed to the overall goal of the campaign.
Write a function easy_donor_rank(percent_donated) that takes a number indicating percent donated and returns a string containing the rank attained by giving such a donation.
For example, the function call easy_donor_rank(1.0) should return the string 'Bronze'.
See the table below to see the list of donor ranks.
Donor Classification
Donation Percentage Donor Rank
0% or less
Error Less than 2% Bronze
2% to 15% inclusive Silver more than 15% Gold
The code I have right now works but I always get a "None" in the end of every output
def easy_donor_rank(percent_donated):
if percent_donated <= 0:
print("Error")
if percent_donated < 2:
print("Bronze")
elif percent_donated >= 2 and percent_donated <= 15:
print("Silver")
else:
print("Gold")
Basically, your code works for me. I made a small modification only for your if condition. I change the second if to elif.
def easy_donor_rank(percent_donated):
if percent_donated <= 0:
print("Error")
elif percent_donated < 2:
print("Bronze")
elif percent_donated <= 15:
print("Silver")
else:
print("Gold")
it's work in python 3.6
def easy_donor_rank(percent_donated):
if percent_donated <= 0:
return "Error"
elif percent_donated < 2:
return ("Bronze")
elif percent_donated >= 2 and percent_donated <= 15:
return ("Silver")
else:
return ("Gold")
The code I have right now works but I always get a "None" in the end
of every output.
I'm going to assume that you are trying to print the return of easy_donor_rank.
$ cat test.py
def easy_donor_rank(percent_donated):
if percent_donated <= 0:
print("Error")
if percent_donated < 2:
print("Bronze")
elif percent_donated >= 2 and percent_donated <= 15:
print("Silver")
else:
print("Gold")
print(easy_donor_rank(1.2))
But because you don't return anything, it will return None, so None gets printed.
$ python3 test.py
Bronze
None
You just need to return the result instead of printing it inside the function.
See What is the purpose of the return statement?
$ cat test.py
def easy_donor_rank(percent_donated):
if percent_donated <= 0:
return "Error"
if percent_donated < 2:
return "Bronze"
elif percent_donated >= 2 and percent_donated <= 15:
return ("Silver")
else:
return "Gold"
print(easy_donor_rank(1.2))
$ python3 test.py
Bronze

Forwarding variables between functions

I'm trying to do a calculation in the following code:
def traffic_intensity(count):
"""Number of cars passing by"""
int(count)
if count < 5000:
level = "Very Low"
elif 5000 <= count < 10000:
level = "Low"
elif 10000 <= count < 18000:
level = "Moderate"
elif count >= 18000:
level = "High"
return level
def number_of_busy_days(counts):
"""Busy days based on traffic flow"""
daily_counts = 0
for count in counts:
if traffic_intensity(level) == "Moderate" or "High":
daily_counts = daily_counts + 1
return daily_counts
counts = [18000, 10000, 500, 9999, 12000]
print(number_of_busy_days(counts))
What I'm trying to achieve is to use the traffic_intensity function to calculate the number of busy days - a busy day is defined as having more than the "Moderate" amount of traffic given in the traffic_intensity function. I've tried a lot of different ways but I'm running out of ideas at this point.
The problem I'm encountering is that it doesn't find the level variable form the first function. I get the following error:
if traffic_intensity(level) == "Moderate" or "High":
NameError: name 'level' is not defined
Is anyone able to help me? Thanks! ^_^
You were passing in a variable level that doesn't exist into the function traffic_intensity. I presume you meant to pass in the variable count.
Likewise, having or "High" as a condition will always result in true since non-empty strings are convertible true in python
def traffic_intensity(count):
"""Number of cars passing by"""
int(count)
if count < 5000:
level = "Very Low"
elif 5000 <= count < 10000:
level = "Low"
elif 10000 <= count < 18000:
level = "Moderate"
elif count >= 18000:
level = "High"
return level
def number_of_busy_days(counts):
"""Busy days based on traffic flow"""
daily_counts = 0
for count in counts:
state = traffic_intensity(count)
if state == "Moderate" or state == "High":
daily_counts = daily_counts + 1
return daily_counts
counts = [18000, 10000, 500, 9999, 12000]
print(number_of_busy_days(counts))

Categories

Resources