Hey just starting to learn python and got some problems already I made a code with an if statement It should work but it isn\'t working can someone fix it and tell me what I did
You have convert it to an int
. raw_input
gives you a string.
x= raw_input("Enter your name: ")
y= raw_input("Enter your grade: ")
print(y)
if 50 <= int(y) <= 100:
print("Good input")
else:
print ("Invaild input")
But what if the user does not enter a number, then you need to add a Try-Except block:
x = raw_input("Enter your name: ")
y = raw_input("Enter your grade: ")
print(y)
try:
if 50 <= int(y) <= 100:
print("Good input")
else:
print ("Invaild input")
except ValueError:
print "You did not enter a number for your grade"
raw_input()
returns a string but you are comparing x
and y
with integers.
Turn y
into a integer before comparing:
y = int(y)
if y >= 50 and y <= 100:
You can simplify your comparison a little with chaining, letting you inline the int()
call:
if 50 <= int(y) <= 100:
You have to convert the input to an integer by putting it in int:
x= raw_input("Enter your name: ")
################
y= int(raw_input("Enter your grade: "))
################
print(y)
if y>=50 and y<=100:
print("Good input")
else:
print ("Invaild input")
Remember that raw_input
always returns a string. So, in your if-statement, you are comparing a string with integers. That is why it doesn't work.
Actually, whenever I need to print one message or another, I like to put it on one line (unless of course the messages are long):
print("Good input" if 50 <= y <= 100 else "Invaild input")
Making a whole if-else block seems a little overkill here.
raw_input()
function waits for user to input data , it is similar to scanf()
function in C. But the data which you input is stored as string, so we need to convert into our specified form like integer, float etc
Ex: y = raw_input("Enter data");
to convert the data into integer we need to use
y = int(y)
in the similar way we can convert into different datatypes