0
#   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.

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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')

Comments

0

Try using 'in' instead of '==' in your if condition, sometimes the lines might have some hidden characters.

if "HELLO" in a:

Comments

0

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')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.