Python if/elif statement not working correctly - python

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.

Related

Beginner in Python: if statement is not returning print function

I recently tried to make a love calculator with this code. However, when faced with a name that has over 11 characters in common for either 'love' or 'true' it does not return the proper statement. For example, if I get 711 returned because the 'love' statement is over 9, it just gives me the 'else' option instead of the => 90 statement. I'm not sure what I did wrong. Thank you for any help in advance!
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
combined_names = str(name1.lower()) + str(name2.lower())
t = combined_names.count('t')
r = combined_names.count('r')
u = combined_names.count('u')
e = combined_names.count('e')
l = combined_names.count('l')
o = combined_names.count('o')
v = combined_names.count('v')
e = combined_names.count('e')
Love = l + o + v + e
true = t + r + u + e
truelove = int(str(true) + str(Love))
if truelove <= 10 and truelove >= 90:
print(f"Your score is {truelove}, you go together like coke and mentos")
elif truelove >= 40 and truelove <= 50:
print(f"Your score is {truelove}, you are alright together")
else:
print(f"Your score is {truelove}")
truelove <= 10 and truelove >= 90
Will always give false and not pass this if statement.
To be able to run it you can try.
truelove >= 10 and truelove <= 90
EDIT: I saw that your elif statement will never work because first if statement is wider range. So flipping the if statements will fix it.
if truelove >= 40 and truelove <= 50:
print(f"Your score is {truelove}, you are alright together")
elif truelove >= 10 and truelove >= 90:
print(f"Your score is {truelove}, you go together like coke and mentos")
else:
print(f"Your score is {truelove}")```

Why am I getting this message invalid syntax?

i write code if statement but there is a wrong in it .
this is the code
mark = float(input('enter your mark : '))
if mark < 50:
result = 'failed'
elif mark >= 50 and < 75:
result = 'accepted'
elif mark >= 75 and < 85:
result = 'good'
elif mark >= 85 and < 90:
result = 'very good'
else:
result = 'excellent'
print(result)
the message appear is invalid syntax in line 4 about < assignment
any help here guys?
The proper syntax is either elif mark >= 50 and mark < 75: or elif 50 <= mark < 75:
mark >= 50 and < 75 is not a valid expression, you must write mark >= 50 and mark < 75 instead. Alternatively, you can use a chained comparison: 50 <= mark < 75.
This would be your code that actually runs:
mark = float(input('enter your mark : '))
if mark < 50:
result = 'failed'
elif mark >= 50 and mark < 75:
result = 'accepted'
elif mark >= 75 and mark < 85:
result = 'good'
elif mark >= 85 and mark < 90:
result = 'very good'
else:
result = 'excellent'
print(result)
As others stated mark >= 50 and < 85 is not valid in Python.

Having trouble using <= with "elif" and "and"

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

Complete beginner with Elif [Python]

I tried to do the first assignment from http://www.cplusplus.com/forum/articles/12974/
g = int(raw_input('Enter the grade you scored: '))
if g >= 90 & g <= 100:
print 'Your grade is: A'
elif g >= 80 & g < 90:
print 'Your grade is: B'
elif g >= 70 & g < 80:
print 'Your grade is: C'
elif g >= 60 & g < 70:
print 'Your grade is: D'
elif g >= 50 & g < 60:
print 'Your grade is: E'
elif g >= 0 & g <= 49:
print 'Your grade is: F'
else:
print 'You can only enter an integer within the range of 0-100.'
The problem is that whenever I run this program, any number I input that is greater than 0 will get:
Your grade is: A
Any help greatly appreciated. Thanks!
Bi Rico's answer is simple and correct. To explain the situation further:
The & operator computes the bitwise AND of two integers. For example, 5 & 3 == 1.
The precedence of & is above the comparison operators (such as < and >=). So a < b & c < d actually means a < (b & c) < d.
Python allows chained comparisons. For example, a < b == c >= d translates into a < b and b == c and c >= d.
Putting these facts together, this is what happens when you run your program:
Assume that g is assigned an integer value between 0 and 100, inclusive.
So the if-test g >= 90 & g <= 100 means (g >= (90 & g)) and ((90 & g) <= 100).
Bitwise AND is always smaller than or equal to both arguments (i.e. (a & b <= a) and (a & b <= b)).
Thus 90 & g <= g is always true. Likewise, 90 & g <= 100 is always true, because 90 <= 100.
Therefore the first if-test is always true, so the body will execute and the elif/else clauses will never execute.
The problem in your code is that you're using & when you want to use and, try this:
if g >= 90 and g <= 100:
print 'Your grade is: A'
...
The code you had their was spot on but syntax is very important in Python. You want to use and where you have & like this:
g = int(raw_input('Enter the grade you scored: '))
if g >= 90 and g <= 100:
print 'Your grade is: A'
elif g >= 80 and g < 90:
print 'Your grade is: B'
elif g >= 70 and g < 80:
print 'Your grade is: C'
elif g >= 60 and g < 70:
print 'Your grade is: D'
elif g >= 50 and g < 60:
print 'Your grade is: E'
elif g >= 0 and g <= 49:
print 'Your grade is: F'
else:
print 'You can only enter an integer within the range of 0-100.'
This will display what you need the correct way.
Using the correct keyword is always important as certain things can cause errors. Use and, not &.

In Python what's the difference between using 'elif' statements vs. 'or' statements?

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.

Categories