I have taken an excerpt from my code where the problem still happens. I believe this is because of my slow_type function but while the dialogue is being "slow typed" my input will take any values typed during the "slow_type" even before the input shows up. I want the input to only be able to be typed in once the slow_type function is finished. How would I do this?
import time
import sys
def slow_type(line, speed):#You input the dialogue and speed(smaller = faster)
for l in line:
sys.stdout.write(l)
sys.stdout.flush()
time.sleep(speed)
time.sleep(.5)
NL1 = "Huh, I see you finally came. "
NL2 = "You know I sent you that message a long time ago.\n"
NL3 = "But I guess you are here now, and that's what matters. "
NL4 = "So...\n"
NL5 = "\n\t\t\t\tAre you ready?\n\n"
slow_type(NL1, .05)
slow_type(NL2, .05)
slow_type(NL3, .05)
slow_type(NL4, .2)
slow_type(NL5, .05)
print("\t\t1:Yes, I am. 2:Who are you? 3:No, I am leaving.\n")
first_choice = input("\t\t\t\t ").lower()
I am using Windows 10 cmd.
Related
I'm doing a school assignment and I need some help. I have to connect to hp 54600 oscilloscope and collect data from both channels and then do some measurements. But I tried every command I could think off, and it still does measurements from channel1, no matter what I do. It changes the source to channel2 when I do it directly from the terminal, but it doesn't do anything when i run my program. So, I will send you my basic code and I hope you can tell me what to add to solve this.
**
import serial, time, sys
from pylab import *
hp = serial.Serial('/dev/ttyUSB0',460800,timeout = 5)
kanal=int(sys.argv[1])
if kanal==1:
hp.write('wav:sour chan1\r')
else:
hp.write('wav:sour chan2\r')
hp.write('+eoi:0\r')
hp.write('+eos:13\r')
hp.write('+a:5\r')
time.sleep(1)
hp.write('wav:form asc\r')
time.sleep(1)
hp.write('wav:poin 5000\r')
time.sleep(1)
hp.write('wav:data?\r')
x = hp.readline()
x = x.replace('\x00','')
x = x[10:-1]
x = x.split(',')
xx = []
for entry in x:
xx.append(float(entry))
np.save(str(kanal),xx)
plot(xx,'m-',linewidth=2)
show()
hp.close()
**
I'm a python starter and need some help on a quiz like game.
This is my code:
import time
from threading import Timer
import random as rnd
q = ["q1", "q2", "q3"]
a = ["a1 b1 c1", "a2 b2 c2", "a3 b3 c3"]
ca = ["b", "c", "b"]
points = 0
rand_q = rnd.randint(0, len(q) - 1) # Choosing random question
print(q[rand_q] + "\n" + a[rand_q] + "\n") # Asking question and showing answers
time.sleep(0.5) # Little pause between prompts
t = Timer(10, print, ['Time is up!']) # Setting up timer
t.start() # Start timer
start = time.time() # Start of time check
answer = input("You have 10 seconds to choose the correct answer.\n") # User input
if answer is ca[rand_q]: # Check if answer is correct
print("Correct answer!")
points = (points + round(10 - time.time() + start, 1)) * 10 # Calculate points
else:
print("Wrong answer!")
t.cancel() # Stop timer
print("Points:", points)
input("Press ENTER to quit")
del q[rand_q] # Removing the question
del a[rand_q] # Removing the answer
del ca[rand_q] # Removing the correct answer
When I run this I can answer questions and get points, but whenver i wait out the timer I get a prompt saying the time is up, but I can still fill in and answer the question.
I want the input to stop working after the 10 seconds, but I can't seem to make this work. Is there any way I can make the timer timeout all previous inputs on top of the "Time is up" prompt.
I've seen more posts like this but they seem outdated and I didn't get them to work.
EDIT: the sleep command doesn't work. It prints a line saying it's too late but you can still enter an answer after. Same for the threading timer. I want to terminate the input command after 10 seconds, but there seems to be no solution for windows.
The problem is that python's input function is blocking, which means the next line of code will not be executed until the user enters some data. A non blocking input is something that a lot of people have been asking for, but the best solution would be for you to create a separate thread and ask the question on there. This question has sort of been answered in this post
This solution will work except the user will still have to press enter at some point to progress:
import time
import threading
fail = False
def time_expired():
print("Too slow!")
fail = True
time = threading.Timer(10, time_expired)
time.start()
prompt = input("You have 10 seconds to choose the correct answer.\n")
if prompt != None and not fail:
print("You answered the question in time!")
time.cancel()
You can do what you intend to do, but it gets very complicated.
I'm using python with select and system library here the code :
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from select import select
import sys
def main():
timeout = 5
print('Please type something: ', end = '')
sys.stdout.flush()
rlist, wlist, xlist = select([sys.stdin],[],[], timeout)
k=sys.stdin.readline()
if k=="f":
data = sys.stdin.readline()
print('you entered', data)
else:
print('\nSorry, {} seconds timeout expired!'.format(timeout))
print(k) #see the sys.stdin result
if __name__ == '__main__':
main()
this program wait the user until put a char
i put in the program a condition if the user put a char after 5 second so the program stop also if the user give something different of the 'f' char but the problem the condition doesn't work i put a test to see the result of the sys.stdin value he give me the 'f char but when i put the result in the if statement the program don't work
this screenshot of the result:
enter image description here
Can someone give me the reason of this result ?
I don't know much about the select library. But here is an error the immediately caught my eyes.
You read from the input with k=sys.stdin.readline(). This means that k will contain the complete line, including the \n (newline) symbol. So if you press f + Enter the value of k will be "f\n", not "f". This is the reason why the comparison is always wrong.
It would be best to compare the values with if k.strip() == "f":.
Edit
Just had a quick look into the select library. If you want to determine if a timeout happened, you need to work with the return values of the select function. And not read from input directly. Otherwise you will wait regardless if a timeout happened or not.
I'm not sure what you want to accomplish, but something similar to the following code will work.
from __future__ import print_function
from select import select
import sys
timeout = 5
print('Please type something: ', end = '')
sys.stdout.flush()
inputready, _, _ = select([sys.stdin],[],[], timeout)
if inputready:
k = sys.stdin.readline()
if k.strip()=="f":
print("You printed 'f'")
else:
print("Not 'f'")
else:
print('\nSorry, {} seconds timeout expired!'.format(timeout))
Here is my code:
from random import randint
doorNum = randint(1, 3)
doorInp = input("Please Enter A Door Number Between 1 and 3: ")
x = 1
while (x == 1) :
if(doorNum == doorInp) :
print("You opened the wrong door and died.")
exit()
now, that works fine, if I happen to get the unlucky number.
else :
print("You entered a room.")
doorNum = randint(1, 3)
This is the part where it stops responding entirely. I am running it in a bash interactive shell (Terminal, on osx). It just ends up blank.
I am new to programming in Python, I spent most of my time as a web developer.
UPDATE:
Thanks #rawing, I can not yet upvote (newbie), so will put it here.
If you are using python3, then input returns a string and comparing a string to an int is always false, thus your exit() function can never run.
Your doorInp variable is a string type, which is causing the issue because you are comparing it to an integer in the if statement. You can easily check by adding something like print(type(doorInp)) after your input line.
To fix it, just enclose the input statement inside int() like:doorInp = int(input("...."))
In python3, the input function returns a string. You're comparing this string value to a random int value. This will always evaluate to False. Since you only ask for user input once, before the loop, the user never gets a chance to choose a new number and the loop keeps comparing a random number to a string forever.
I'm not sure what exactly your code is supposed to do, but you probably wanted to do something like this:
from random import randint
while True:
doorNum = randint(1, 3)
doorInp = int(input("Please Enter A Door Number Between 1 and 3: "))
if(doorNum == doorInp) :
print("You opened the wrong door and died.")
break
print("You entered a room.")
See also: Asking the user for input until they give a valid response
Basically I want to record high scores in my program. I'm new to coding so need a bit of help. I will create this basic program to demonstrate what I want.
import time
name = input("Please enter your name: ")
mylist=["Man utd are the best team","I am going to be a pro typer.","Coding is really fun when you can do it."]
x=random.choice (mylist)
print ("The sentence I would like you to type is: ")
print (x)
wait = input ("Please press enter to continue, The timer will start upon hitting enter!")
start = time.time()
sentence = input("Start typing: ")
end = time.time()
overall = end - start
if sentence == (x):
print ("It took you this many seconds to complete the sentence: %s" % overall)
if overall <= 9:
print ("Nice job %s" % name)
print ("You have made it to level 2!")
How would I be able to save the time it took and if someone beats the time make that the new high score?
You're looking for a way to persist data across program executions. There are many ways to do it, but the simplest is just writing to a file.
In addition, if you want to use a database, look into SQLite3 for Python.