Learning Python using a textbook and codecademy.
This code is returning a SyntaxError. Can I not use two greater/less than symbols in the same elif statement? Or is the problem my '<='?
def movie_rating(rating):
if rating <= 5:
return "Avoid"
elif rating > 5 and <= 9:
return "I recommend!"
else:
return "Amazing"
The problem is because of your and in line 4, this error happening because when you use and you need to define a new condition in other word you should change your code to one of this codes:
def movie_rating(rating):
if rating <= 5:
return "Avoid"
elif rating > 5 and rating <= 9:
return "I recommend!"
else:
return "Amazing"
or change your code to this:
def movie_rating(rating):
if rating <= 5:
return "Avoid"
elif 5> rating <= 9:
return "I recommend!"
else:
return "Amazing"
if you want to know how you can use and in python, follow this link:
How to use boolean 'and' in Python
and
how use if and else elif or
Related
Please help understand what is wrong with the code below. The code works fine if I pass values up to 34. Once I pass 35 or higher, the output is incorrect.
tuk=0
if tuk <= 24:
print ('The text is very easy to read.')
elif tuk >= 25 & tuk <= 34:
print('The text is easy to read.')
elif tuk >= 35 & tuk <= 44:
print('The text is moderately difficult to read.')
elif tuk >= 45 & tuk <= 54:
print('The text is difficult to read')
elif tuk >= 55:
print('The text is very difficult to read')
else:
print('This is beyond')
Your code is correct, but changing the "&" to "and" because "&" is a bitwise logical operator, not a logical one.
For example:
z = 0 := 0b000
a = 1 := 0b001
b = 2 := 0b010
c = 3 := 0b011
d = 4 := 0b100
now the result of the expression (a & c) is 0b001 or 1
but in logical expression (a and c) the result will be true, which I suppose you are interested in.
Given a positive integer change, a set of coins makes change for change if the sum of the values of the coins is change. We will use standard US Coin values: 1, 5, 10, 25.
I was asked to solve this coin change question with recursion function only(while and for loop are not allowed), and I am very struggling with it. Please help!
def next_smaller_coin(coin):
"""Returns the next smaller coin in order."""
if coin = 25:
return 10
elif coin = 10:
return 5
elif coin = 5:
return 1
def count_coins(change):
if change == 0:
return 1
elif change < 0:
return 0
else:
with_coin = count_coins(change - next_smaller_coin(coins))
wo_coin = count_coins(change)
return with_coin + wo_coin
I'm reading the book "Automate the boring stuff" by Al Sweigart to start learning Python (it is free online, so you can check it if you're interested, or you think that it would help solve my problem). And by the end of Chapter 3, you are given an exercise, creating a program that can execute the Collatz Conjecture. I've successfully created a function that takes an input integer and divides it by 2 or multiplies it by 3 and adds 1 for even and odd numbers, respectively.
The issue comes, when I try to take the value returned by the function, and assign it to a variable(so I can make a loop that will stop when the number gets to one), it instead calls the function, and when I try to use the function inside a while loop it returns a None value.
I tried comparing it to other program that simulates a magic 8-ball, because the way I made the way I made the Collatz program is very similar to the 8-ball, but somehow the 8-ball does work, and the Collatz doesn't, and since I'm currently out of ideas, I ask you if you can notice any typos in my code that may indicate why this is happening.
I thank you in advance for your time and effort.
PS: don't forget to drink some water, it is good for you <3
THE CODES:
1.-Collatz(no while loop included)
import random
even = range(0, 1001, 2)
def collatz(number):
if number in even:
print(number // 2)
return
else:
print(3 * number + 1)
return
startNumber = int(input())
newNumber = collatz(startNumber)
2.- 8-ball
import random
def getAnswer(x):
if x == 1:
return 'It is certain'
elif x == 2:
return 'It is decidedly so'
elif x == 3:
return 'Yes'
elif x == 4:
return 'Reply hazy try again'
elif x == 5:
return 'Ask again later'
elif x == 6:
return 'Concentrate and ask again'
elif x == 7:
return 'My reply is no'
elif x == 8:
return 'Outlook not so good'
elif x == 9:
return 'Very doubtful'
r = random.randint(1, 9)
fortune = getAnswer(r)
print(fortune)
3.- Collatz made with the hints from the book(includes while loop)
def collatz(number):
if number % 2 == 0:
print(number // 2)
return
elif number % 2 == 1:
print(3 * number + 1)
return
startNumber = int(input())
while startNumber != 1:
collatz(startNumber)
newNumber = collatz(startNumber)
collatz(newNumber)
Also, here's an SS of the book, just in case
enter image description here
You have unused variables, and you need to define a return value for collatz().
Right now, you define a variable newNumber, but never use it anywhere in your code. You should be updating startNumber instead (renamed to num below for readability). You also need to define a return value for collatz(); otherwise, it will return None, which isn’t what the question asks for.
Here’s a solution which resolves these issues.
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
print(3 * number + 1)
return 3 * number + 1
num = int(input())
while num != 1:
num = collatz(num)
def greater_less_equal_5(answer):
if answer > 5:
return 1
elif answer < 5:
return -1
else:
return 0
print greater_less_equal_5(4)
print greater_less_equal_5(5)
print greater_less_equal_5(6)
What these number: 4,5,6 mean and do in the ending of print?
They are arguments/parameters being passed to the function greater_less_equal_5 as the value of answer to be used inside the body of that function. For example, greater_less_equal_5(4) effectively runs this code:
if 4 > 5:
return 1
elif 4 < 5:
return -1
else:
return 0
This has nothing to do with the print.
How are the two options different? I'm using some arbitrary code as an example but the question is general.
Using 'or'
if (passenger['Sex'] == 'female') or (passenger['Pclass'] == 1):
predictions[passenger_id] = 1
else:
predictions[passenger_id] = 0
Using 'elif'
if (passenger['Sex'] == 'female'):
predictions[passenger_id] = 1
elif (predictions[passenger_id] = 1):
predictions[passenger_id] = 1
else:
predictions[passenger_id] = 0
The first reduces code duplication. For example
s = 'd'
if s == 'a' or s == 'b' or s == 'c'... etc:
print('Is alpha')
else:
print('Not alpha')
As opposed to
s = 'd'
if s == 'a':
print('Is alpha') # repetition of same code
elif s == 'b':
print('Is alpha') # repetition of same code
elif s == 'c':
print('Is alpha') # repetition of same code
elif... etc:
print('Is alpha') # repetition of same code
else:
print('Not alpha')
Note that the above is simply an example to get the point across, you could more pythonically do
if s.isalpha():
or
if s in string.ascii_lowercase:
In your code snippet, there is no functional difference (at the end of your if-suite, you'll have the same result). However, or allows you to only write the code in the branch one time which is more DRY (Don't Repeat Yourself) -- And that's pretty much always a good thing.
In the general case, elif allows you to take different actions in different branches:
if (passenger['Sex'] == 'female'):
do_thing_1()
elif (predictions['Pclass'] = 1):
do_thing_2()
This can't be accomplished using or.
You use elif when you want certain code to run under the condition that an earlier clause was False and this one is True, without re-evaluating or respecifying that earlier clause. Say that we want to give someone a grade based on their score. We could write it like this:
if score >= 90:
grade = 'A'
if score < 90 and score >= 80: # not using: 80 <= score < 90, to make AND explicit
grade = 'B'
if score < 80 and score >= 70:
grade = 'C'
if score < 70 and score >= 60:
grade = 'D'
else:
grade = 'E'
As you can see, we're repeating the same information. If we want to make it so that to get an A, you need at least 95 points, we have to remember to change 90 into 95 twice, or face interesting bugs.
With elif you could rewrite it like this:
if score >= 90:
grade = 'A'
elif score >= 80: # implicit condition: score < 90
grade = 'B'
elif score >= 70: # implicit conditions: score < 90 and score < 80
grade = 'C'
elif score >= 60: # implicit conditions: score < 90 and score < 80 and score < 70
grade = 'D'
else:
grade = 'E'
If you'd use if here instead of elif, everyone with at least 60 points would get a D. Just using or wouldn't work either:
if score >= 90 or score >= 80 or score >= 70 or score >= 60:
grade = '?'
Hence, whether to use elif greatly depends on the similarities between the conditions and between the code that needs to be run if True.
In your case, the first option is better because you don't really care which of the two conditions was True; the very same needs to happen in both cases.
Building on mgilson's question, elif uses multiple branches, while the or statement evaluates everythin (seemingly) at once. In the case of
if a or b:
If 'b' takes significantly longer to evaluate than 'a', then using 'elif' is preferable.
if a:
{code}
elif b:
{code}
else:
{other code}
Here 'b' is only evaluated if 'a' is found to be false, and therefore processing time is saved.
Note: I'm going off of my experience in C, C++, and basic. If python deals differently with 'or' statements, please let me know.