Returns None instead of False - python

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

Related

Passing data between a series of related functions

I am attempting to create an exam grading program. I successfully wrote each function to do what I need it to, but when I attempt to execute the entire program, I am running into issues with my return variables not being referenced.
Here is my code for context:
def userinput():
allinputs = []
while True:
try:
results = list(map(int, input('Exam points and exercises completed: ').split(' ')))
allinputs.append(results)
except:
ValueError
break
return allinputs
def points(allinputs):
exampoints = []
exercises = []
exercises_converted = []
gradepoints = []
counter = 0
for i in allinputs:
exampoints.append(i[0])
exercises.append(i[1])
for e in exercises:
exercises_converted.append(e//10)
for p in exampoints:
p2 = exercises_converted[counter]
gradepoints.append(p + p2)
counter += 1
return (gradepoints, exampoints, exercises_converted)
def average(gradepoints):
avg_float = sum(gradepoints) / len(gradepoints)
points_avg = round(avg_float, 1)
return points_avg
def pass_percentage(exercises_converted, exampoints):
failexam = []
passexam = []
passorfail = []
i = 0
while i < len(exampoints):
if exampoints[i] < 10 or exercises_converted[i] + exampoints[i] < 15:
failexam.append("fail")
passorfail.append(0)
else:
passexam.append("pass")
passorfail.append(1)
i += 1
percentage_float = len(passexam)/len(failexam)
percentage = round(percentage_float, 1)
return (percentage, passorfail)
def grades_distribution(passorfail, gradepoints):
grades = []
i = 0
l = 5
while i < len(gradepoints):
if passorfail[i] == 0:
grades.append(0)
elif passorfail[i] != 0 and gradepoints[i] >= 15 and gradepoints[i] <= 17:
grades.append(1)
elif passorfail[i] != 0 and gradepoints[i] >= 18 and gradepoints[i] <= 20:
grades.append(2)
elif passorfail[i] != 0 and gradepoints[i] >= 21 and gradepoints[i] <= 23:
grades.append(3)
elif passorfail[i] != 0 and gradepoints[i] >= 24 and gradepoints[i] <= 27:
grades.append(4)
elif passorfail[i] != 0 and gradepoints[i] >= 28 and gradepoints[i] <= 30:
grades.append(5)
i += 1
while l >= 0:
print(l, ": ", "*" * grades.count(l))
return
userinput()
print("Statistics:")
points(allinputs)
print(f"Points average: {average(gradepoints)}")
print(f"Pass percentage: {pass_percentage(exercises_converted, exampoints)}")
print("Grade distribution")
grades_distribution(passorfail, gradepoints)
I have no problems with the mechanics within each function; rather, my error lies where I try calling each of them from the main function.
The user input() function runs fine, and returns allinputs. However, when the second function points(allinputs) is called, the program states that the argument is undefined.
You should store the return value of a function before passing it as argument.
This should solve your problem
allinputs = userinput()
points(allinputs)

I keep getting None

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.

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

Solution to cigars and squirrels puzzle on CodingBat throws syntax error

I am trying to solve this CodingBat problem:
Squirrels who like to party get together and smoke cigars. Such a party is only deemed successful when the number of cigars is between 40 and 60, on a weekday. On weekends, however, there is no upper bound on number of cigars. Write a function that returns True if the party with the given values was successful.
Unfortunately, although I have used Python occasionally, I am not good enough at it to understand why my code fails with a syntax error on line 5:
def cigar_party(cigars, is_weekend):
if is_weekend:
if cigars >= 40:
return True
else if:
cigars >= 40 and cigars =< 60:
return True
else:
return False
In Python you need to use elif instead of else if.
More information:
http://docs.python.org/2/tutorial/controlflow.html
Also change the following line:
else if:
cigars >= 40 and cigars =< 60:
To this:
elif cigars >= 40 and cigars <= 60:
return True
The less than or equal to sign needs to be <= and there should not be a colon between the keyword elif and the rest of the expression.
First of all, as tcdowney pointed out, the syntax is elif, not else if, secondly, you need to have the logical assessent in the elif statement, not as some sort of operation. Lastly, have the greaterthan/smallerthan sign before the equals sign.
elif cigars >= 40 and cigars <= 60:
return True
That should do the trick ;)
def cigar_party(cigars, is_weekend):
a = range(61)
if is_weekend and cigars not in a:
return True
elif cigars in range(40,61):
return True
else:
return False
def cigar_party(cigars, is_weekend):
if is_weekend and cigars>=40:
return True
elif not is_weekend and cigars in range(40,61):
return True
return False
def cigar_party(cigars, is_weekend):
if is_weekend:
return cigars >= 40
return 40 <= cigars <= 60 // Python supports this type of Boolean evaluation
or using the ternary form:
def cigar_party(cigars, is_weekend):
return cigars >= 40 if is_weekend else 40 <= cigars <= 60
def cigar_party(cigars, is_weekend):
if is_weekend:
if cigars>=40:
return is_weekend
else:
if cigars in range(40,61):
return True
return False
def cigar_party(cigars, is_weekend):
if is_weekend == True:
if cigars >= 40:
return True
else:
return False
if is_weekend == False:
if cigars >= 40 and cigars <= 60:
return True
else:
return False
#got 9/12 not bad!
is_weekday = True
is_weekend = True
def cigar_party(cigars, is_weekend):
if is_weekend and cigars >= 0:
return True
elif is_weekday and cigars >= 40:
return True
else:
return False
def cigar_party(cigars, is_weekend):
if is_weekend and cigars >= 40:
return True
elif cigars >= 40 and cigars <= 60:
return True
else:
return False

question about else statement...blackjack in python

Python newbie here. I'm trying to create a black jack game in which the user plays against the computer. I think where I'm having trouble is with the if, elif statements here. What I want to know is, what happens when none of the criteria of any of the if and elif statements are met when I don't have an else statement? Is it problematic here not to have an else statement?
def game_winner(n):
p_wins = 0
d_wins = 0
for i in range(n):
player_sum = player_game()
dealer_sum = dealer_game()
if player_sum > dealer_sum and player_sum <= 21:
p_wins = p_wins + 1
elif dealer_sum > 21 and player_sum <= 21:
p_wins = p_wins + 1
elif player_sum > 21 and dealer_sum <= 21:
d_wins = d_wins + 1
elif dealer_sum > player_sum and dealer_sum <= 21:
d_wins = d_wins + 1
return p_wins, d_wins
If none of the conditions are met then none of the conditionals in any of the if or elif blocks are executed. If it is ok that neither the computer or the player wins in a round, then it's fine. Otherwise you should include an else statement to cover that case.
If you don't have an else, the code will simply "fall through"; i.e. none of the conditional code will be executed, so the win counts will not be changed.
Looking at the specifics of your example, the only potential problem I see is that there will be some games that aren't counted. Your requirements or design will determine if this is really a problem or not.
This is perfectly valid. Having no else statement isn't a problem.
try:
rng = xrange # Python 2.x
except NameError:
rng = range # Python 3.x
def game_winner(n):
p_wins, d_wins = 0, 0
for i in rng(n):
player = player_game()
if player > 21:
d_wins += 1
else:
dealer = dealer_game()
if player <= dealer <= 21:
d_wins += 1
else:
p_wins += 1
return p_wins, d_wins

Categories

Resources