Reputation: 1
This is my first ever post. I am a very new learner of programming language at the age of 30. The language I am learning is python and I dont seem to understand what the basic flaw of my simple programming code is.
a = input("What is the string?")
b = input("Enter a number:")
if(a == "Animal" and b == 1):
print("No 1 Executed!")
elif(a == "Dog"):
print("No 2 Executed")
else:
print("No 3 Executed")
Even if I type "Animal" and Number 1, line no.3 is executed instead of line no. 1. Can you guys please explain what is my basic fault here? Thanks!
Upvotes: 0
Views: 89
Reputation: 1599
The reason why the latest line is executed is input
returns str
object which is not equal to number. To make it comparable as you want, you need to convert b
to int
.
b = int(input("Enter a number:"))
Upvotes: 0
Reputation: 1199
the input command will always create a string, so even though you type in 1, python interprets that value as a string. b == 1
is expecting b to be a number, so the expression is always false. There's 2 ways you could fix it.
If you want to keep b as a string, just change that expression to compare against a string, ie b == "1"
If you want b as a number, convert it to an integer immediately after b = input("Enter a number:")
, just add a new line: b = int(b)
. Now your expression will work as expected, but the program will fail if you enter any value that's not a number.
Upvotes: 0
Reputation: 140
The problem is that the input function returns a String. That means that the variable b will be a string and in your if statement you are checking to see if it is equal to a number. You can fix this in several ways, one example would be to change your if statement to:
if(a == "Animal" and b == "1"):
Upvotes: 0
Reputation: 310
b is a string and if you compare it with a number the result is false. You should use:
if(a == "Animal" and b == "1"):
You could also convert b to number with int(b)
Upvotes: 1