greater than but less than function in python usage - python

while I was studding python I run into this problem that I'm trying to filter if a number is bigger than n and smaller than x
in other thread I read that you could just do this:
if 10 < a < 20:
whatever
but when I run the code Im getting invalid syntax
while guess != rightnum:
guess=int(input('your guess: '))
diff= abs(guess - rightnum)
if guess > rightnum and diff >= 1000 :
print(random.choice(muchless))
elif guess > rightnum and 1000 > diff >= 100
print(random.choice(less))
elif guess > rightnum and diff < 100
print(random.choice(fewless))

your elif statements don't end with :!

You missed 2 colons
while guess != rightnum:
guess=int(input('your guess: '))
diff= abs(guess - rightnum)
if guess > rightnum and diff >= 1000 :
print(random.choice(muchless))
elif guess > rightnum and 1000 > diff >= 100 :
print(random.choice(less))
elif guess > rightnum and diff < 100 :
print(random.choice(fewless))

Related

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

i have thes exam and i dont know what is the problem in my answer

Write a Python code snippet use 'if-elif' flow control along with a 'while' loop that will:
Instruct a user to input a number that is greater than 0 and less than or equal to 10 and store the input as a floating-point value in a variable
If the input number is greater than 0 and less than or equal to 10,
use a 'while' loop in order to add the number to itself until the sum exceeds a value of 100.
After the sum has exceeded a value of 100, use the print statement to output the sum
Otherwise, output the message 'You did not enter a value between 0 and 10'
My Answer :
inval = float(input('Input a number greater than zero and less than or equal to 10: '))
if inval > 0 and inval <= 10:
while inval < 100:
inval += inval
continue
else:
print(inval)
elif inval <= 0 or inval > 10:
print('You did not enter a value between 0 and 10')
The reason your answer is not acceptable is because the code should return 100.0 for input like 6.25. But, your code returns 200.0 because of your while condition. You can just add an equal sign(=) to solve this problem. And also, I removed unnecessary parts from your code.
inval = float(input('Input a number greater than zero and less than or equal to 10: '))
if inval > 0 and inval <= 10:
while inval <= 100:
inval += inval
print(inval)
else:
print('You did not enter a value between 0 and 10')
I think that the only thing that may be wrong is the condition of the While loop (u should put it inval <= 100).
However, the problem could be on the else inside the loop; because, its not "efficient", after the inval value is greater than 100 it will print the value even if the else is not there.
See:
inval = float(input('Input a number greater than zero and less than or equal to 10: '))
if inval > 0 and inval <= 10:
while inval <= 100:
inval += inval
print(inval)
elif inval <= 0 or inval > 10:
print('You did not enter a value between 0 and 10')
I don't see other problem in your code :)

Python : Exit while loop when condition is met

Im trying to iterate over my list and calculate the diff between each element and the element following it. If the difference is greater than 0 ( or positive ) then increment up and decrease down by 1 ( if it is greater than 0 ). Similarly if difference is less than 0 then increment down and decrease up by 1 ( if greater than 0 ) . I want to exit out of the loop if either the up or down exceeds limit which is set to 3.
My code:
my_list = [13.04, 12.46, 13.1, 13.43, 13.76, 13.23, 12.15, 12.0, 11.55, 14.63]
up = 0
down = 0
limit = 3
while (up < limit) or (down < limit) :
for i in range(len(my_list)-1):
diff = my_list[i] - my_list[i+1]
print (diff)
if diff > 0:
up +=1
if down > 0:
down -=1
elif diff < 0:
down +=1
if up > 0:
up -=1
Obviously this is not working since I keep getting caught up in an infinite loop and cant figure out what I am doing wrong.
The while condition is wrong. The loop keeps going while either up or down is below limit, so it will not stop even when up=1000, as long as down<3.
What you want is while (up < limit) and (down < limit) instead.
do not use while , you can use if condition in last of for loop for break it :
for i in range(len(my_list)-1):
diff = my_list[i] - my_list[i+1]
#print (diff)
if diff > 0:
up +=1
if down > 0:
down -=1
elif diff < 0:
down +=1
if up > 0:
up -=1
if (up > limit)or (down > limit) :print(up);print(down);break
The problem is with your condition. You said you want to exit the program if either the up or down exceeds the limit which is set to 3. So the condition on the while loop needs to be set as while up is less than limit AND down is also less than limit, only then execute the body of the loop. Something like this.
while up < limit and down < limit:
or you can also use brackets (doesn't matter in this case)
while (up < limit) and (down < limit):
So the full program will be
my_list = [13.04, 12.46, 13.1, 13.43, 13.76, 13.23, 12.15, 12.0, 11.55, 14.63]
up = 0
down = 0
limit = 3
while up < limit and down < limit:
for i in range(len(my_list)-1):
diff = my_list[i] - my_list[i+1]
print (diff)
if diff > 0:
up +=1
if down > 0:
down -=1
elif diff < 0:
down +=1
if up > 0:
up -=1

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

Using “and” operator to compare two values

Very new to python and trying to figure out how to use the and operator to check if a number is between 50 and 100. Tried using and, && and || , but just getting invalid syntax python parser-16 error. If I take the and or alternative out of the code, then it partly works and dosn't give me a error message, though it dosn't check if the value is below 100, so presumly it must the and part that I'm doing wrong?
x = int(input("Enter a number between 0 and 100"))
if x < 50:
print("That is below 50!")
elif x > 50 and < 100:
print("That is above 50!")
else:
print("That number is too high!")
close!
x = int(input("Enter a number between 0 and 100"))
if x < 50:
print("That is below 50!")
elif x > 50 and x < 100:
print("That is above 50!")
else:
print("That number is too high!")
if x > 50 and x < 100 you have to reference it each time you check if its true
Alternative solution:
x = int(input("Enter a number between 0 and 100: "))# for a better look
if x < 50:
print("That is below 50!")
elif 100 >= x >= 50:# the numbers 50 and 100 shall be inclusive in one of the three params
print("That is between 50 and 100!")
else:
print("That number is too high!")
To simplify it more, you can write as below.
x = int(input("Enter a number between 0 and 100"))
if x < 50:
print("That is below 50!")
elif 50 < x < 100:
print("That is above 50!")
else:
print("That number is too high!")
If x<50:
print('Below 50')
elif x>50 and x<100:
print('Between 50 and 100');
else:
print('Above 100');
Try this

Categories