Why am I getting this message invalid syntax? - python

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.

Related

Python if/elif statement not working correctly

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.

Grade calculator range and ValueError - Python

I'm new to python and have been trying to create a simple grade calculator which tells the user what grade they've achieved based on their final score they've inputted.
def grades():
try:
score = int(input("Please enter your score between 0 and 100:"))
if score >= 90:
print("Grade:A")
elif score >= 80 :
print("Grade:B")
elif score >= 70:
print("Grade:C")
elif score >= 60:
print("Grade:D")
elif score >= 50:
print("Grade:E")
elif score < 50:
print("Grade:F")
except score not in range (0,101) or ValueError:
int(input("Incorrect value. Please enter your score between 0 and 100:"))
However when I try to run the program, it disregards the range and value error and gives it a grade anyway. Is there any way to rectify this, and if possible how could I make the program more efficient. As I said, I'm new to python, so any feedback would be useful.
Just for fun, let's make it a Match Case statement:
Since you only accept integers, we can take and assign score to input with :=, then check if it's valid with str.isnumeric. If that's true then we'll make score an integer := and check if it's between 0 and 100.
We'll change the input statement if they don't put valid input the first time around.
def grades():
text = "Please enter your score between 0 and 100: "
while True:
if ((score := input(text)).isnumeric() and
(score := int(score)) in range(0, 101)):
break
else:
text = "Incorrect value. Please enter your score between 0 and 100: "
match score:
case x if x >= 90 : grade = 'A'
case x if x >= 80 : grade = 'B'
case x if x >= 70 : grade = 'C'
case x if x >= 60 : grade = 'D'
case x if x >= 50 : grade = 'E'
case _ : grade = 'F'
print(f'Grade: {grade}')
Please note that this will only work in Python 3.10 or greater.
Just do this:
def grades():
try:
score = int(input("Please enter your score between 0 and 100:"))
if score > 100:
while True:
int(input("Incorrect value. Please enter your score between 0 and 100:"))
if score <= 100:
pass
else:
break
if score >= 90:
print("Grade:A")
elif score >= 80 :
print("Grade:B")
elif score >= 70:
print("Grade:C")
elif score >= 60:
print("Grade:D")
elif score >= 50:
print("Grade:E")
elif score < 50:
print("Grade:F")
except:
print("Oops. sommthing went wrong")
grades();
I made some corrections to your code. I added some comments to help explain what is going on. Let me know if this solution works for you:
def grades():
while True:
# Start a loop to ask for user input:
score = int(input("Please enter your score between 0 and 100:"))
# If not in range 1, 100, print error message
if score in range(0, 101):
break
print('Incorrect value. Please enter your score between 0 and 100:')
# calculate grade:
if score >= 90:
print("Grade:A")
elif score >= 80:
print("Grade:B")
elif score >= 70:
print("Grade:C")
elif score >= 60:
print("Grade:D")
elif score >= 50:
print("Grade:E")
elif score < 50:
print("Grade:F")
if __name__ == '__main__':
grades()
Simply assert that the input is in the determined range before checking through score ranges. Really, there is no need for a try/except statement.
def grades():
while True:
score = int(input(...))
if 0 <= score <= 100:
break
# Invalid score
# Check score ranges
...
I have made changes to your code, please test to ensure it performs to expectations.
I have added a while True loop, which attempts to validate the score to be between 0 - 100. If a non-integer value is entered it will hit the ValueError exception. This loop will only exit when a number within the range is entered.
The if statements use interval comparators X <= score < Y. You can read more about interval comparators here.
The if statement was also removed out of the try - except to make debugging easier. The idea is to have the least code possible in try - except so that when an exception triggers, it would be caused by the intended code.
Lastly, you don't want to ask for the user input inside the exception as the user might enter something which may cause another exception which will go uncaught.
def grades():
while True:
# Perform basic input validation.
try:
# Gets the user input.
score = int(input("Please enter your score between 0 and 100: "))
# Checks if the number entered is within 0 - 100. Note that range is non-inclusive for the stop. If it is within 0 - 100 break out of the while loop.
if 0 <= score <= 100:
break
# If a non-integer is entered an exception will be thrown.
except ValueError:
print("Input entered is not a valid number")
# Checking of scores using interval comparison
if score >= 90:
print("Grade:A")
elif 80 <= score < 90:
print("Grade:B")
elif 70 <= score < 80:
print("Grade:C")
elif 60 <= score < 70:
print("Grade:D")
elif 50 <= score < 60:
print("Grade:E")
else:
print("Grade:F")

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}")```

variables not defined in if statements for change counting program

I'm making a change counter and I'm having trouble printing the percentage for a grade, whenever I run the program I can enter as many inputs as I want, however, when I type done, which is supposed to terminate the program and leave the user with the percentage and letter grade, it just ends the program. If I could get any advice it would be greatly appreciated.
here's my code:
grade=""
total=0
count=1
scores=''
while scores != 'done':
scores=input("Enter Homework score: ")
if scores.isdigit():
numeric=int(scores)
percentage=(numeric*10/count)
elif percentage >= 92 and percentage < 100:
letter = 'A'
elif percentage >= 87 and percentage < 92:
letter = 'B+'
elif percentage >= 80 and percentage < 87:
letter = 'B'
elif percentage >=77 and percentage < 80:
letter = 'C+'
elif percentage >=70 and percentage < 77:
letter = 'C'
elif percentage >= 67 and percentage < 70:
letter = 'D+'
elif percentage >= 60 and percentage < 67:
letter = 'D'
elif percentage < 60 and percentage >= 0:
letter= 'F'
elif (numeric) < 0:
print("Score must be between 0 and 10")
elif (numeric) > 10:
print("Score must be between 0 and 10")
elif (scores)== 'done':
print(percentage,"% and you got an, ",letter)
Your conditional logic is flawed. You are never assessing the grade (letter) if the score.isdigit():
while scores != 'done':
scores=input("Enter Homework score: ")
if scores.isdigit():
numeric=int(scores)
percentage=(numeric*10/count)
if percentage >= 92 and percentage < 100:
letter = 'A'
elif percentage >= 87 and percentage < 92:
letter = 'B+'
...
It is often cleaner to jump out of the loop if the initial condition is false, e.g.:
while scores != 'done':
scores=input("Enter Homework score: ")
if not scores.isdigit():
continue
numeric=int(scores)
percentage=(numeric*10/count)
if 92 <= percentage < 100:
letter = 'A'
elif 87 <= percentage < 92:
letter = 'B+'
...
Also in python your shouldn't be afraid of exceptions. A common idiom in python is EAFP (Easier to Ask for Forgiveness than Permission):
while scores != 'done':
scores=input("Enter Homework score: ")
try:
numeric = int(scores)
except ValueError:
continue
You might also want to think about better ways of doing the large grade if elif elif ... block. E.g. an alternative approach would be define a dictionary of the grades:
grades = {'A': (92, 100), 'B+': (87, 92)} # Etc..
score = 93
_, letter = max((low <= score < high, letter) for letter, (low, high) in grades.items())
print(letter) # 'A'
Your code should look similar to the one below. Although I still cannot assess the logic behind your program (because you did not explain that in your question, e.g. percentage=(numeric*10/count) does not seem quite right to me, etc.), but the code below solves your current problem (based on your current question).
grade=""
total=0
count=1
scores=''
percentage = 0
while scores != 'done':
scores=input("Enter Homework score: ")
if scores.isdigit():
numeric=int(scores)
if numeric < 0:
print("Score must be between 0 and 10")
elif numeric > 10:
print("Score must be between 0 and 10")
percentage=(numeric*10/count)
if percentage >= 92 and percentage < 100: # I would change this to if percentage >= 92 and percentage <= 100:
letter = 'A'
elif percentage >= 87 and percentage < 92:
letter = 'B+'
elif percentage >= 80 and percentage < 87:
letter = 'B'
elif percentage >=77 and percentage < 80:
letter = 'C+'
elif percentage >=70 and percentage < 77:
letter = 'C'
elif percentage >= 67 and percentage < 70:
letter = 'D+'
elif percentage >= 60 and percentage < 67:
letter = 'D'
elif percentage < 60 and percentage >= 0: #I would change this to else:
letter= 'F'
print(percentage,"% and you got an, ",letter)

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 &.

Categories