Kyle Davidson

Equality Comparison doing opposite

Recommended Posts

I am new to python, the code im doing just now is my first attempt and im following a tutorial video course.

 

I have an issue where == & != are doing the opposite 

print("Hello World")
myName = input('What is your name?')
myVar = input('How old are you?')
print(myName)
if(myName == "Kyle" and myVar == 25):
    print("Hello Kyle")    
else:
    print("Hello World")

 

when i enter Kyle & 25 it will print "Hello World" whereas if i type a different number it will print "Hello Kyle" 

If i change the code to != it does the opposite but my understanding both are reversed for some strange reason?

 

Any advice would be greatly appreciated. I can go on using it this way but from the tutorial it seems my code is doing the opposite of what im telling it to do 

Share this post


Link to post
Share on other sites

This is because the input function returns a string type. For example, if you type '25' into the console the variable myVar = '25' and not myVar = 25. There is a difference between a string (text) and a number (integer). Text can be a number but you have to tell the computer to convert it first. You need to use the int() function to parse your string into an integer. Change your code to this to see what is going on.

print("Hello World")
myName = input('What is your name?')
myVar = input('How old are you?')
print(myVar)
myVar = int(myVar)
print(myVar)
print(myName)
if(myName == "Kyle" and myVar == 25):
    print("Hello Kyle")    
else:
    print("Hello World")

Note this will crash if you enter anything other than a number for your age. 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...