Python if statement not executing - python

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

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.

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

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

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

Related

Typing effect Python [duplicate]

I am writing a program in Python and want to replace the last character printed in the terminal with another character.
Pseudo code is:
print "Ofen",
print "\b", # NOT NECCESARILY \b, BUT the wanted print statement that will erase the last character printed
print "r"
I'm using Windows8 OS, Python 2.7, and the regular interpreter.
All of the options I saw so far didn't work for me. (such as: \010, '\033[#D' (# is 1), '\r').
These options were suggested in other Stack Overflow questions or other resources and don't seem to work for me.
EDIT: also using sys.stdout.write doesn't change the affect. It just doesn't erase the last printed character. Instead, when using sys.stdout.write, my output is:
Ofenr # with a square before 'r'
My questions:
Why don't these options work?
How do I achieve the desired output?
Is this related to Windows OS or Python 2.7?
When I find how to do it, is it possible to erase manually (using the wanted eraser), delete the '\n' that is printed in python's print statement?
When using print in python a line feed (aka '\n') is added. You should use sys.stdout.write() instead.
import sys
sys.stdout.write("Ofen")
sys.stdout.write("\b")
sys.stdout.write("r")
sys.stdout.flush()
Output: Ofer
You can also import the print function from Python 3. The optional end argument can be any string that will be added. In your case it is just an empty string.
from __future__ import print_function # Only needed in Python 2.X
print("Ofen",end="")
print("\b",end="") # NOT NECCESARILY \b, BUT the wanted print statement that will erase the last character printed
print("r")
Output
Ofer
I think string stripping would help you. Save the input and just print the string upto the length of string -1 .
Instance
x = "Ofen"
print (x[:-1] + "r")
would give you the result
Ofer
Hope this helps. :)

Python 2.7.10: readline causes a leading space on the following line

I'm writing a simple command line prompt script and noticed that lines printed immediately after doing a readline start with a leading space. Is there any way to avoid this behavior?
Sample function to demonstrate:
import sys
def foo():
print 'Enter some text.\n> ',
bar = sys.stdin.readline()[:-1]
print 'You entered "{0}"'.format(bar)
When I run this code I get:
>>> foo()
Enter some text.
> Hi
You entered "Hi"
^ the leading space I want to get rid of
This is Python 2's "soft-space" behavior. After a print thing, statement, the next print will print a leading space to separate the output from the previous print output. This can look weird when a different text source, such as user input, causes the output of the two prints to appear on different lines.
There are various ways to get around soft-spacing, but here, the most appropriate would be to use raw_input instead of sys.stdin.readline. It auto-strips the newline for you and allows you to specify a prompt:
print 'Enter some text.'
foo = raw_input('> ')
print 'You entered "{0}"'.format(foo)

Replacing more than one line in the console in python

I'm writing a program in python and I'd like to replace more than one line in the console with new text.
For example if I have 3 sentences printed to the console with:
print("Hello World!")
print("How are you!")
print("What's going on?")
Where each on is on a different line (and so has an \n).
How do I go about replacing all of this text when it displays in the console? I can't us \r in this situation due to the \n.
This is kind of an old post, but I came across it and worked out a solution as well. Added a timer, because otherwise the print statements bury each other and you'll only be able to read the last one. I'm on python 2.7:
import os
import time
os.system("printf 'Hello World!'")
time.sleep(1)
os.system("printf '\rHow are you?!'")
time.sleep(1.5)
os.system("printf '\rWhats going on?'")
os.system("echo ")
A simple fix would be to simply change the end separator for printing your strings. you can specify how you want the print function to separate calls with the end argument
print("hello world!", end="")
print("\rhello world again!")
In this case, we're setting the separator to "", which is nothing. So printing the next strings starts on the same line thus \r can be used. Compiling that gives you hello world again! on one line.

In python carriage return \r returns a musical note

print "-------------------\r"
produces a musical note instead doing the carriage return. Why?
Thanks in advance for reply.
EDIT: I was using it in this code in order to change dinamically data by 'print' instead to re-print it all:
import math
import time
while True:
reading = read_world_2c(0x43) #it's a function for reading data from a sensor
print "data: \r", reading
time.sleep(0.5)
That musical note is the symbol for line breaks. If you have MS Word or Notepad++ or similar, open or type some text and then find the menu command for "show nonprinting characters ". You will see those "musical notes" at the end of each line.

Python code to cause a backspace keystroke?

I keep finding ways to map the backspace key differently, but that's not what I'm after.
I'm in a program writing a python code, and basically I want to write a line of code that causes the program to think someone just hit the Backspace key in the GUI (as the backspace key deletes something)
How I would code in a backspace key stroke?
The character for backspace is '\b' but it sounds like you want to affect the GUI.
if your program changes the GUI, then simply delete the last character from the active input field.
and i got it !
print('\b ', end="", flush=True)
sys.stdout.write('\010')
it backspace !
foo = "abc"
foo = foo + "\b" + "xyz"
print foo
>> abxyz
print len(foo)
>> 7
if key == '\b': delete_selected_points()
As other answers have said, use '\b' to backspace. The trick in your case is to use sys.stdout.write instead of print to not get a newline appended. Then wait and print the appropriate number of backspace characters.
import time
import sys
print("Good morning!")
while True:
time_fmt = "It's %I:%M:%S %p on %A, %b %d, %Y"
time_str = time.strftime(time_fmt)
sys.stdout.write(time_str)
sys.stdout.flush()
time.sleep(1)
sys.stdout.write("\b"*len(time_str))
Updating since this still pops up in search.
In Python3 print() can and does work if you use the \<end\> parameter. Meaning sys.stdout.write() and .flush() aren't needed.
eg.
print("\b"*len(time_str),end='')

Categories