1

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 wrong?

x= raw_input("Enter your name: ")
y= raw_input("Enter your grade: ")
print(y)
if y>=50 and y<=100:
    print("Good input")
else:
     print ("Invaild input")

It always prints Invalid input thanks!

4 Answers 4

11

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:
Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

1

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

Comments

0

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"

1 Comment

? If you are going to do that, you need to remove the int around raw_input.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.