Using “and” operator to compare two values - python

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

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

How do I make it to where the range is ONLY 3-20

What they want us to do is create a code where I am able to give them the option of only scoring up to 20 grades. They also want me to add an error message if they mess up and go either above or below the numbers asked. This is what I have so far.
n=int(input("Enter an integer between 3-20: "))
a=[]
for i in range(0,n):
grade=int(input("Enter Grade: "))
a.append(grade)
avg=sum(a)/n
print("Average Score",round(avg,2))
if(avg >= 90):
print("Final Grade A")
elif(avg >= 80 and avg < 90):
print("Final Grade B")
elif(avg >= 70 and avg < 80):
print("Final Grade C")
elif(avg >= 60 and avg < 70):
print("Final Grade D")
else:
print("Sorry, Failed Grade")
If your python version is 3.8+, you can replace the first line with
while not 3 <= (n := int(input('Enter an integer between 3-20: '))) <= 20:
print('Input must be between 3-20, inclusive.')
The "assignment expression" := sets n as the input. Then (3 <= ... <= 20) checks whether n is between 3 and 20. Input is requested over and over again until this check returns True.
This should work and is pretty simple to understand.
while True:
n = int(input("Enter an integer between 3-20: "))
if not (3 <= n <= 20):
print("Number not in range 3-20, try again!")
continue
a = []
for i in range(0, n):
grade = int(input("Enter Grade: "))
a.append(grade)
avg = sum(a)/n
print("Average Score", round(avg, 2))
if(avg >= 90):
print("Final Grade A")
elif(avg >= 80 and avg < 90):
print("Final Grade B")
elif(avg >= 70 and avg < 80):
print("Final Grade C")
elif(avg >= 60 and avg < 70):
print("Final Grade D")
else:
print("Sorry, Failed Grade")
break

How can I check if a number is negative?

I tried to check if the number is negative or not:
x = int(input('Enter any number:'))
bumble = x+1
shumble = x-1
if shumble>x:
print('Your number is a negative number')
elif bumble>x:
print('Your number is a positive number')
elif x == 0:
print('Your number is 0')
but the problem is python won't consider a negative number its mathematical value
and I checked that by running this block of code
x = -2
y = 1
if x>y:
print('-2 is greater that 1')
elif y>x::
print('1 is greater than -2')
and the output says:
-2 is greater than 1
so can someone pls help me find a solution?
I would really appreciate it!
I'm not sure whether or not you're not allowed to use zero with you inequality operator. But surely the following should work pretty well. You can omit the exception handling if not needed.
try:
x = int(input('Enter any number:'))
if x < 0: print('Your number is a negative number')
elif x > 0: print('Your number is a positive number')
elif x == 0: print('Your number is 0')
except ValueError:
print("That was not a valid number...")
You're overcomplicating this so much. To check if its a negative number check if its less than, equal to, or greater than zero
try:
x = int(input("Enter a number"))
except:
print("invalid number")
if x > 0:
print("Positive")
elif x < 0:
print("Negative")
else:
print("Equal to 0")
num = float(input("Enter a number: "))
if num > 0:
print("{0} is a positive number".format(num))
elif num == 0:
print("{0} is zero".format(num))
else:
print("{0} is negative number".format(num))

Traceback error: TypeError float object cannot be interpreted as an integer

Could someone help me figure out the problem I have with this?
def marbles():
marbles = 0
while True:
try:
x = eval(input("How many marbles? "))
except ValueError:
print("You can't enter", x , "marbles! How many marbles do you have?")
continue
else:
break
for i in range(x):
x = eval(input("Please enter how many marbles between 0 and 100: "))
if 0 <= x and x <= 100:
marble = marble + x
else:
print("Your number is out of range!")
y = int(input("Please enter how many marbles between 0 and 100: "))
main()
I can't seem to figure out why it won't give out the warning that You are not in range when I code 5.4 marbles. Between 0 and 100, I should be allowed to give decimals, but for "How many marbles" I would like to receive that warning to try again.
Use is_integer() method. It returns boolean if parameter is whole number or not.
For example
>>> (5.4).is_integer()
False
>>> (1).is_integer()
True
Check this documentation.
You need string's isdigit method.
Something like this?
def marbles():
marbles = 0
count_flag = False
while count_flag is False:
try:
x = raw_input("How many marbles? ")
if not x.isdigit():
raise ValueError
except ValueError:
print "You can't enter %s marbles! How many marbles do you have?" % (x)
else:
x = int(x)
count_flag = True
for i in range(x):
x = int(input("Please enter how many marbles between 0 and 100: "))
if 0 <= x and x <= 100:
marbles = marbles + x
else:
print("Your number is out of range!")
y = int(input("Please enter how many marbles between 0 and 100: "))
return marbles
print marbles()
Also, in case of python, instead of doing 0<=x and x<=100, you can do either 0<=x<=100(my preference) or x in range(0, 101). Second one is not recommended though :-)
Also a flaw with your for statement logic. If a user gives two bad inputs, they are not considered. You need a while there also.
while x > 0:
y = int(input("Please enter how many marbles between 0 and 100: "))
if 0 <= y and y <= 100:
marbles = marbles + y
x -= 1
else:
print("Your number is out of range!")
To be honest, the cleaner practice would be to put the input validation in another function and call it in the marbles function.
def get_number(screen_input):
flag = False
while flag is False:
try:
x = raw_input(screen_input)
if not x.isdigit():
raise ValueEror
except ValueError:
print("You can't enter %s marbles! How many marbles do you have?" % (x))
else:
return int(x)
def marbles():
marbles = 0
x = get_number("How many marbles?")
while x > 0:
y = get_number("Please enter how many marbles between 0 and 100:")
if 0 <= y <= 100:
marbles += y
x -= 1
else:
print("Your number is out of range!")
return marbles
print marbles()

While loop in python not working

pointsToAdd = 30
strengthPoints = 0
healthPoints = 0
wisdomPoints= 0
dexterityPoints = 0
while pointsToAdd > 0:
choice = int(input("Choice(1-4): "))
if choice == 1:
pointsToAdd = int(input("How many Strength points would you like to add: "))
if pointsToAdd < 31 and pointsToAdd > 0 and pointsToAdd - strengthPoints > 0:
strengthPoints += pointsToAdd
pointsToAdd -= strengthPoints
print("You now have",strengthPoints,"strength points")
elif pointsToAdd > 30:
print("You cannot add that many!")
elif pointsToAdd<1:
print("You cannot add less than one point!")
elif pointsToAdd - strengthPoints <= 0:
print("You only have",pointsToAdd,"points!")
else:
print("We are sorry, but an error has occurred")
I am trying to make it so that the user can enter points for any of the four categories, but has no more than 30 points to expend(I have not yet written the code for the health, wisdom or dexterity points). Why when i run the program does the loop only run again if you choose to add a number of points between 1-30? If the user enters the points they want to allocate towards strengthPoints using numbers not between 1-30, the loop will run the associated if statement, but will not run through the loop again, why is this the case?
you are using the same variable for two different purposes pointsToAdd. You have it as the total points to assign, and what was selected by the user to add to a stat. Once you stomp the total points to assign with the users choice, you then add it to the 0 strength and subtract it from your user entered value, setting it to zero. Using to separate variables like below will fix it.
totalPointsToAdd = 30
strengthPoints = 0
healthPoints = 0
wisdomPoints= 0
dexterityPoints = 0
while totalPointsToAdd > 0:
choice = int(input("Choice(1-4): "))
if choice == 1:
pointsToAdd = int(input("How many Strength points would you like to add: "))
if pointsToAdd < 31 and pointsToAdd > 0 and pointsToAdd - strengthPoints > 0:
strengthPoints += pointsToAdd
totalPointsToAdd -= pointsToAdd
print("You now have",strengthPoints,"strength points")
You do
pointsToAdd = 30
Then in the loop
pointsToAdd = int(input("How many Strength points would you like to add: "))
Then in the test
# Here pointsToAdd is not 30, but the value inputed by the user
strengthPoints += pointsToAdd
# Here strengthPoints == pointsToAdd == the value from the input
pointsToAdd -= strengthPoints
# Here pointsToAdd == 0
This results in pointsToAdd == 0 after than.
You need to use another variable for the input of your user.
As other pointed out you are overwriting the same variable pointsToAdd. I also consider that you can cut down your conditions to two:
pointsToAdd = 30
strengthPoints = 0
while pointsToAdd:
print ('You have', pointsToAdd, 'available points.')
choice = int(input("Choice(1-4): "))
if choice == 1:
toBeAdded = int(input("How many Strength points would you like to add: "))
if toBeAdded < 1: # Can't assign negative or null values
print("You cannot add less than one point!")
continue
if toBeAdded > pointsToAdd: # Don't have enough points to spend
print("You only have", pointsToAdd, "available points!")
continue
strengthPoints += toBeAdded
pointsToAdd -= toBeAdded
print("You now have", strengthPoints, "strength points")
In Python 2.x use: raw_input
In Python 3.x use: input
If you want compatibility between Python 2.x and 3.x, you can use:
try:
input = raw_input
except NameError:
pass

Categories