Hello,


This is a really simple question but I just don't see the error here:

def foo():
	x = input('write something: ')
	if x == 1 or x == 2:
		print('OK')
	else:
		print('NO')
	print(x)

Why does it keep printing NO?


Also, I have a more complicated one:


def foo(x, y):
if x == 'a' or x == 'b' and y == 'z':
print('OK')
elif x == 'a' or x == 'b' and y == 'w':
print('OK2')

It keeps printing OK instead of OK2.

I have read the documentation and the use I'm giving to the and and or expressions seems correct and logical to me, but obviously it's not (or my logic is flawed).

Any ideas?

It depends on which version of Python you are using as x could be a string or an integer so print the type().

x = input('write something: ')
    print type(x)
assert("1"==1), "Not equal"

And don't use tabs to indent as the tab can be set to anything on any computer, so is not the same as yours.

Edited 5 Years Ago by woooee: n/a

This is not clear:

if x == 'a' or x == 'b' and y == 'z':

It should be:

if (x == 'a' or x == 'b') and y == 'z':
#
# or
if x == 'a' or (x == 'b' and y == 'z'):
#
# or better yet
if y == 'z' and x in ['a', 'b']:
#
# "or" is the same as if(), elif()
# if x == 'a' or (x == 'b' and y == 'z'):
if x =='a':
elif x == 'b' and y == 'z':
#
# "and" is the same as nested if() statements
x = 'a'
for y in ['w', 'z']:
    if x == 'a' or x == 'b':
        if y == 'z':         ## x=='a' and y=='z'
            print(y, 'OK')
        elif y == 'w':
            print(y, 'OK2')  ## x=='a' and y=='w'

Edited 5 Years Ago by woooee: n/a

It depends on which version of Python you are using as x could be a string or an integer so print the type().

x = input('write something: ')
    print type(x)
assert("1"==1), "Not equal"

And don't use tabs to indent as the tab can be set to anything on any computer, so is not the same as yours.

I'm using python 3.1.


The problem was that input returns a STRING in python 3.1.

I solved the first problem like this:

def foo():
	x = int(input('write something: '))
	if x == 1 or x == 2:
		print('OK')
	else:
		print('NO')

And voilà. It works perfectly now.

The second problem needed the () to clarify which part could be variable. I didn't know that python accepted parentheses in if statements.


Thank you Woooee, it all works perfectly now.

Edited 5 Years Ago by G_S: n/a

This question has already been answered. Start a new discussion instead.