Lior Raif
Lior Raif

Reputation: 23

Trouble with if in python

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!

Upvotes: 1

Views: 160

Answers (4)

Nafiul Islam
Nafiul Islam

Reputation: 82440

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"

Upvotes: 0

user2555451
user2555451

Reputation:

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.

Upvotes: 5

Vineeth Guna
Vineeth Guna

Reputation: 398

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

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121296

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:

Upvotes: 11

Related Questions