user2540878
user2540878

Reputation: 9

If statement not working - keeps going to else statement even when if condition is matched

This is what I've got right now in Python

import sys
num = input('Give me a four digit number.')
a = num[0]
b = num[1]
c = num[2]
d = num[3]

if d == 0:
    print(c + b + a)
else:
    print(d + c + b + a)

but when I input, say, 1230, it'll return 0321 back to me. Does any one know why?

Upvotes: 0

Views: 91

Answers (1)

ultima_rat0
ultima_rat0

Reputation: 290

If i try your code the first thing that occur is a TypeError due to the evaluation of the input, so it's casted to type int. But I assume you used quotes so this was not the problem.

The problem is, as you may notice, the type of the given input. In Python 2.X there was raw_input, which just returned the input string without evaluating it.
The answer is:

print(c+b+a if d=='0' else d+c+b+a)

# or

if d == '0':
    print(c + b + a)
else:
    print(d + c + b + a)

Upvotes: 1

Related Questions