0

I am REALLY new to this and have been trying to figure this out for a day now. Having a bit of an issue with Python34. Here is my code:

myName = input('What is your name? ')
myVar = input("Enter your age please! ")

if(myName == "Jerome" and myVar == 22):
    print("Welcome back Pilot!")
    print(myName, myVar)
elif(myName == "Steven"):
    print("Steve is cool!")
    print(myName, myVar)
else:
    print("Hello there", myName)
    print(myName, myVar)

When I input- Jerome enter 22 enter into the console it still goes to the condition by printing:

Hello there Jerome
Jerome 22

Why is this happening? I also tried messing with the if statement by writing it like this: if(myName == "Jerome") and (myVar == 22): and I still got the same response.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Euclid11
  • 1
  • 2

3 Answers3

3

In Python 3, the input() function returns a string, but you are trying to compare myVar to an integer. Convert one or the other first. You can use the int() function to do this:

myVar = int(input("Enter your age please! "))

if myName == "Jerome" and myVar == 22:

or use:

myVar = input("Enter your age please! ")

if myName == "Jerome" and myVar == "22":

Converting the user input to an integer has the advantage that you can make other comparisons, like smaller then, or greater then, etc.

You may want to read up on asking for user input with proper error handling, in that context. See Asking the user for input until they give a valid response.

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thank you Martijn for the help! I hope to see you again when I need help me on my future endeavors! :) – Euclid11 Jan 17 '15 at 15:47
1

This is the culprit

myVar = input("Enter your age please! ")

input always returns a string

type cast it to int like

myVar = int(input("Enter your age please! "))

OR

Change your if condition as

if(myName == "Jerome" and myVar == "22"):

But this is an inferior method, as if you want to use your age somewher else, then it will become a problem

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
0

The method input() returns a string, which is a word or sentence, but you need to make it an integer, a whole number. To do that, just simply type instead of input("Enter your age please"), you need to type int(input("Enter your age please")). That will turn it into an integer. Hope this helps!

Daniel Lewis
  • 88
  • 2
  • 9