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
Related
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
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.
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
I am quite new to django/python.
I am trying to create a field that outputs a value depending on the value of another field. I have looked all over the internet but can't find anything to help me.
I have a python condition:
def _final(obj):
if obj.final > '40,000':
return obj.match_score == 1
elif obj.final >= '35,000' and obj.final <= '40,000':
return obj.match_score == 2
elif obj.final >= '30,000' and obj.final <= '35,000':
return obj.match_score == 3
else:
return None
This is how I've defined the 2 fields in django models:
match_score = Derived(NumberField(null=True, default=None), _final)
final = NumberField(blank=True, null=True, default=None)
It runs but when I enter a number for "final", it doesn't output anything in "match_score"
Thanks for your help.
Editing the formatting of code and indentation
You need to set the values, not return booleans
def _final(obj):
if obj.final > '40,000':
obj.match_score = 1
elif obj.final >= '35,000' and obj.final <= '40,000':
obj.match_score = 2
elif obj.final >= '30,000' and obj.final <= '35,000':
obj.match_score = 3
Also, it looks fishy to me that you compare with strings ('40,000') instead of numbers (40000 - no quotes, no comma)
Being that match_score is computed would this be better suited as a method on the model instead of a field?
models.py
from django.db import models
class MyModel(models.Model):
final = models.IntegerField(blank=True, null=True)
def match_score(self):
if self.final > 40000:
return 1
elif self.final >= 35000 and self.final <= 40000:
return 2
elif self.final >= 30000 and self.final <= 35000:
return 3
template
{{ obj.match_score }}
This is how I solved the problem:
def _final(obj):
if obj.final > 40000:
return 1
elif obj.final >= 35000 and obj.final <= 40000:
return 2
elif obj.final >= 30000 and obj.final <= 35000:
return 3
else:
return 0
The two fields remained defined in the same way. Thanks for your contribution guys!
I am practicing my python coding on this website. This is the problem
Return True if the string "cat" and "dog" appear
the same number of times in the given string.
cat_dog('catdog') → True
cat_dog('catcat') → False
cat_dog('1cat1cadodog') → True
This is my code , for some unknown reason , i dont pass all the testcases. I have problems debugging it
def cat_dog(str):
length=len(str)-2
i=0
catcount=0
dogcount=0
for i in range (0,length):
animal=str[i:i+2]
if ("cat" in animal):
catcount=catcount+1
if ("dog" in animal):
dogcount=dogcount+1
if (dogcount==catcount):
return True
else:
return False
You don't need to creat a function,just a line is enough.like:
return s.count('cat') == s.count('dog')
An alternative without loop:
> def cat_dog(str):
> total_len = len(str)
> cat = str.replace("cat", "")
> dog = str.replace("dog", "")
> if len(cat) == len(dog):
> if len(cat) < len(str):
> if len(dog) < len(str):
> return True
> if len(cat) == len(str) and len(dog) == len(str):
> return True
>
> else: return False
def cat_dog(str):
count_cat = str.count('cat')
count_dog = str.count('dog')
if count_cat == count_dog:
return True
else:
return False