Getting python to respond to a specific key press - python

I am trying to create a program that reads the text from a text file line by line. For the first 3 lines, the user simply needs to press enter to advance to the next line. For the fourth line, however, they need to press a specific key (the letter "u" in this case). I tried doing this using getch(), but for some reason pressing the "u" key does not generate any response. Here is the code:
from os import path
from msvcrt import getch
trial = 1
while trial < 5:
p = path.join("C:/Users/Work/Desktop/Scripts/Cogex/item", '%d.txt') % trial
c_item = open(p)
print (c_item.readline())
input()
print (c_item.readline())
input()
print (c_item.readline())
input()
print (c_item.readline())
if ord(getch()) == 85:
print (c_item.readline())
input()
trial += 1
I've also read about people using pygame or Tkinter, but I don't know if it is possible to use these without having the program use a graphical interface. Thanks in advance!

The problem with this is that input on most modern ttys is buffered - it is only sent to the application when the enter key is pressed. You can test this in C as well. If you create a GUI application that gets its' keyboard data directly from the OS then yes, you could do this. However, this would likely be more trouble than just asking the user to print the enter key after pressing u.
For example:
result = input()
if result == 'u':
print(c_item.readline())
input()

85 is the ordinal for capital 'U'. For lowercase 'u', you need the ordinal 117.
if ord(getch()) == 117:
You could also simply check whether the character is b'u'.
if getch() == b'u':
Or you could do a case-insensitive check for the ordinal:
if ord(getch()) in (85, 117):
Or for the string:
if getch().lower() == b'u'
You also need to move trial += 1 into the loop:
if getch().lower() == b'u':
print (c_item.readline())
input()
trial += 1

Related

Getting EOF error but running my code in Thonny produces no errors

I'm learning python and one of my labs required me to:
Write a program whose input is a string which contains a character and a phrase, and whose output indicates the number of times the character appears in the phrase. The output should include the input character and use the plural form, n's, if the number of times the characters appears is not exactly 1.
My code ended up being:
char = input()
string = input()
count = 0
for i in string:
if i == char:
count +=1
if count > 1 or count == 0:
print(f"{count} {char}'s")
else:
print(f'{count} {char}')
Whenever I run the code in Thonny or in the Zybooks development tab it works but when I select the submit option I keep getting and EOF error:
Traceback (most recent call last):
File "main.py", line 2, in <module>
string = input()
EOFError: EOF when reading a line
Does anyone know what's causing the error?
I tried using the break command but it didn't help though I think if I used break at the end of my for statement it wouldn't count all the way. Any ideas folks?
Thank you Mr. Roberts the number of inputs was the issue. I had to create a single input and pull what I needed from that single line. My code ended up being:
string = input()
char = string[0]
phrase = string[1:]
count = 0
for i in phrase:
if i == char:
count +=1
All good now.

(Beginner) Why my code skips some of the functions ? (Python 3)

I'm trying to write code that receives two texts and thereafter I am writing code that finds common words among the texts. This is put in a new list. sys.stdin.read() is being used instead of input() because I need to process a long piece of text.
Below is what I wrote thus far. When I run the code it seems to hang because its only asking for input for text1 and never reaches text 2 input request.
What is going on and how can I fix it?
size text 1 = approx. 500.000 chars.
size text 2 = approx. 500.000 chars.
import sys
text1 = sys.stdin.read()
print(text1)
text2 = sys.stdin.read()
print(text2)
# ... snippet ... compare code here ...
I think this will work
text1 = input("Input some text: ")
text2 = input("Input some text: ")
I don't actually know whats going wrong in yours thoough
In the code below you have two different type of input(). At text-1 you add unlimited amount of text, press enter, then type "EOF!' and press enter to go to input for text 2. At text-2 you have the input() bound to the amount of characters (likely to be ASCII or UTF-8 type; accepts all types as written for now). When 500.000 characters is received text-2 is done and you can go to the compare step, which you might have written by now. If that gives problems too post a new question for that.
The print statements are there to show you what the input per text is minus "EOF!" marker for text-1. It can be any type of marker but End Of File seemed to be obvious for now to explain the stop-marker.
import sys
text1 = ''
text2 = ""
nr_lines = 2
while True:
text1 += input()+'\n'
# print(text1[-5:-1])
if text1[-5:-1] == 'EOF!':
break
print(f'\nlen: {len(text1)}, text1 {text1}\n\n'[:-7])
while True:
text2 = input()
if len(text2) >= 500000:
break
print(f'\nlen: {len(text2)}, text2 {text2}\n\n')
The reason why sys.stdin.read() is not working is due to a different purpose and therefore the lack of functionality written into the method. Its one direction communication and not bi-directional.

loop prints a error message multiple times

edited for clarity. When a loop prints an error message multiple times, it is usually caused by poor control flow. In this case, adding a Breakafter print solved the problem.
Following a simple loop structure with some control flow, is generally a good starting point.
for ...:
if ...:
print ...
break
input_seq = "";
#raw_input() reads every input as a string
input_seq = raw_input("\nPlease input the last 12 nucleotide of the target sequence
before the PAM site.\n\(The PAM site is by default \"NGG\"\):\n12 nt = ")
#print "raw_input =", input_seq
for bases in input_seq:
if not (bases in "ACTGactg"):
print "\nYour input is wrong. Only A.T.C.G.a.t.c.g are allowed for
the input!\n\n";
break
Use break. I am using regular expressions to avoid using a for loop.
input_seq = ""
import re
while True:
#raw_input() reads every input as a string
input_seq = raw_input("\nPlease input the last 12 nucleotide of the target sequence
before the PAM site.\n\(The PAM site is by default \"NGG\"\):\n12 nt = ")
#print "raw_input =", input_seq
if len(input_seq)==12:
match=re.match(r'[ATCGatcg]{12}',input_seq)
if match:
break
else:
print "\nYour input is wrong. Only A.T.C.G.a.t.c.g are allowed for the input!\n\n"
continue
else:
print "\nYour input should be of 12 character"
Add a break after your print statement. That will terminate your loop.
Using a flag to check if there were atleast one wrong input is one way to do it. Like this:
invalid = False
for bases in input_seq:
if not (bases in "ACTGactg"):
invalid = True
if invalid:
print "\nYour input is wrong. Only A.T.C.G.a.t.c.g are allowed for the input!\n\n";
You could alternately use a break statement as soon as you find the first wrong input.
Place a break after the print:
for ...:
if ...:
print ...
break

Why doesn't the result from sys.stdin.readline() compare equal when I expect it to?

I m trying to compare keyboard input to a string:
import sys
# read from keyboard
line = sys.stdin.readline()
if line == "stop":
print 'stop detected'
else:
print 'no stop detected'
When I type 'stop' at the keyboard and enter, I want the program to print 'stop detected' but it always prints 'no stop detected'. How can I fix this?
sys.stdin.readline() includes the trailing newline character. Either use raw_input(), or compare line.rstrip("\n") to the string you are looking for (or even line.strip().lower()).

Python, writing multi line code in IDLE

How do i write
>>> x = int(raw_input("Please enter an integer: "))
>>> if x < 0:
... x = 0
... print 'Negative changed to zero'
... elif x == 0:
... print 'Zero'
... elif x == 1:
... print 'Single'
... else:
... print 'More'
...
this in IDLE. As soon as I hit enter after writting first line, it executes the first line and i am not able to write full code. I am very new to python, just started it today. Any help will be appreciated.
Try File => New File in top menu. Then write your code in this windows and run it by F5 key (or Run in top menu)
Shift + Enter takes you to next line without executing the current line.
1: Use semicolons between lines
2: Try iPython
3: Write it as a function, e.g.
def myfunc():
x = int(raw_input("Please enter an integer: "))
if x < 0:
x = 0
print 'Negative changed to zero'
elif x == 0:print 'Zero'
elif x == 1:print 'Single'
else:print 'More'
Using the exec function along with multi-line strings (""") worked well for my particular use case:
exec("""for foo in bar:
try:
something()
except:
print('Failed')"""
Can't write multi-line code in python console. Need a 3rd-party app.
If you do File --> New File, it should open a new savable window that you can write multiple lines and save as a .py file.
creating a new file enables you to write your code in multiline in IDLE and before writing the code you need to save the file as *.py format. That's all

Categories

Resources