Reputation: 1
# TEST
import sys
a=sys.stdin.readline() # here the user inputs the string "HELLO"
print a
if a == "HELLO":
sys.stdout.write("GOOD_BYE")
print "AAAAAAAAAAA"
raw_input('\npress any key to continue')
Hi there. I am new to Python.
I am using Python 2.7.11.
I do not understand why control is not entering the if
statement.
The output for the given code comes out as
HELLO
HELLO
AAAAAAAAAAA
press any key to continue
NOTE: The first "HELLO" above is user input
I've tried sys.stdout.flush()
for the sys.stdout.write()
statement. But it doesn't seem to help.
If I write the same code with a=raw_input()
instead of the second line, it works perfectly fine.
Can anyone explain the reason for this.
Upvotes: 0
Views: 106
Reputation: 61
You are pressing 'ENTER' after input string to send input. So your input is 'HELLO\n' while your if statement 'if' condition is 'a == "HELLO"'.
Use strip() method. The method strip() returns a copy of the string in which all chars have been stripped from the beginning and the end of the string (default whitespace characters).
So new working code :
import sys
a=sys.stdin.readline().rstrip('\n')
a=a.strip() # This will remove \n from input
print (a)
if a == "HELLO":
sys.stdout.write("GOOD_BYE")
print ("AAAAAAAAAAA")
raw_input('\npress any key to continue')
Upvotes: 0
Reputation: 28
Try using 'in' instead of '==' in your if condition, sometimes the lines might have some hidden characters.
if "HELLO" in a:
Upvotes: 0
Reputation: 4506
readline() function read newline character from standard input console. Please use rstrip("\n") to remove the same.
import sys
a=sys.stdin.readline().rstrip('\n')
print (a)
if a == "HELLO":
sys.stdout.write("GOOD_BYE")
print ("AAAAAAAAAAA")
raw_input('\npress any key to continue')
Upvotes: 0
Reputation: 722
readline
comes with a newline character at the end. So what you are actually doing is comparing
HELLO\n == HELLO
which is actually false.
Do a.rstrip()
to remove newline.
Upvotes: 2