0

My son wrote a code, it's quite simple but second if statement isn't working as expected.

print ('hi')
print ('How are you?')
print ('Hope ok!')
print ('So I will ask you a few questions')
print ('What is 2 + 2?')
answer = input() 
if answer == 4:
    print ('Well done!')
else:
    print ('Are you able to count?')
    print ('Well anyway.Another question.')
    print ('What is 50 % 50?')

anser = input() 

if anser == 1:
    print ('Well done!')
elif anser == 5:
    print ('What?')
elif anser == 50:
    print ('Who are you? Are you already in 1st class?')
else:
    print ('Ok.I got you.You cannot count.')
    print ('Арролбьітрцо')
    print ('The code is broken! can you fix it?')
    print ('Press Enter')
    input()
    for i in range (1,70):
        print ('Error')

It doesn't matter what second answer is, program still prints

"Ok.I got you.You cannot count. Арролбьітрцо The code is broken! can you fix it? Press Enter"

even if you type 1 or 5...

Can anyone suggest please what is wrong.

Thank you.

Oleg V
  • 9
  • 1

3 Answers3

1

the reason is because anser is a str. if you put print(type(anser)) after anser = input() you will see

<class 'str'>

change if anser == 1: to if anser == '1': then it will work

Alex Hall
  • 34,833
  • 5
  • 57
  • 89
OLIVER.KOO
  • 5,654
  • 3
  • 30
  • 62
0

Using input() will always result in a string unless you specify otherwise.

To make it an integer use:

answer = int(input("question"))

An alternative would be:

if int(answer) == 1:

This will make it an integer so you are comparing two numbers in the if statement

Rlz
  • 1,649
  • 2
  • 13
  • 36
-1

Essentially, when you compare using the == operator using one of more objects, Python will check if the pointers are the same (essentially, if they're in the same location in the memory). You have two types of data, primitives (like ints or booleans) and objects. Strings don't compare with pimitives when using the == operator, so you have to convert the numbers to strings or convert the input to an int

Rather than: if anser == 5:

Do: if int(anser) == 5:

Or: if anser == '5'

jst
  • 9
  • 1
  • You're thinking of Java. The conversion is necessary but there is no `.equals` in Python - `==` is the equivalent. Java's `==` is like Python's `is`. – Alex Hall Aug 29 '17 at 20:09
  • Alex - You're right. I had a bit of a brain fart but edited my answer to reflect this. – jst Aug 29 '17 at 20:11
  • No, saying "Python will check if the pointers are the same (essentially, if they're in the same location in the memory)" is still wrong, `==` can compare by value as I just said. There's also no primitives in Python, everything (including ints) is an object. – Alex Hall Aug 29 '17 at 20:13