I am creating a sort of a game where the player has to guess a word within a given time limit everything is working accept i dont know how do i run a timer and take input at the same time that too in a loop.
I tried some code but it took input then ran the timer and asked input again so one happened after the other and not simultaneously
How do i fix it
Here is what i tried
import time
def countdown(seconds):
while seconds > 0:
seconds -= 1
time.sleep(1)
seconds = 6
while seconds > 0:
input = ("guess word : ")
countdown(6)
^^ that is only a fraction of my code
Full code here - https://sourceb.in/QYk1D9O2ZT
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.
So I've written an Electric Bill Calculator in Python. The great news is that it works! However, I need to make it work better. When asked how many hours per day, the user can type in 25, or any other number they want. Obviously there isn't 25 hours in a day. I've tried a few things but I cannot get it to work correctly.
I've tried something like:
hours = input("How many hours per day? ")
if hours > 24:
print("Don't be silly, theres not more than 24 hours in a day ")
else:
main()
What I'm trying to do, is make the program display an error msg, if they enter more than 24 hours, and if they do, then skip to the bottom code that asks if they want to try another calculation. And if they enter 24 hours or less, then continue the program with no error msg. I've spent about 2 days trying to fix this, searched google for hours, I may have seen the right answer but can't seem to make it work. I assume I need some kind of while True statement, or if;then, but as many times as i have tried, I'm pulling my hair out at this point. The code to the entire program is below:
def main():
star = '*' * 70
print star
print ("Nick's Electric Bill Calculator")
print star
watts = input("Enter the watts of appliance, or total watts of appliances ")
hours = input("Enter the number of hours that appliance(s) run per day ")
cost = input("Enter the cost in cents per KwH you pay for electricty " )
# print ("Don't be silly, there isn't more than 24 hours in a day!")
x = (watts * hours / 1000.0 * 30) * cost
total = x
print star
print ("""If you use %s watts of electricity for %s hours per day, at a cost of
%s cents per Kilo-watt hour, you will add $%s to your monthly
electric bill""") % (watts, hours, cost, total)
print star
playagain = 'yes'
while playagain == 'yes':
main()
print('Would you like to do another Calculation? (yes or no)')
playagain = raw_input()
I'm new to programming, I've only been learning Python for a few weeks, many thanks in advance for any advice.
An optimized version of #JamesRusso code :
def main():
star = '*' * 70
print star
print ("Nick's Electric Bill Calculator")
print star
watts = int(input("Enter the watts of appliance, or total watts of appliances"))
hours = int(input("Enter the number of hours that appliance(s) run per day"))
# Check that the hours number is good before getting to the cost
while (hours > 24) or (hours < 0):
print("Don't be silly, theres not more than 24 or less than 0 hours in a day ")
hours = int(input("Enter the number of hours that appliance(s) run per day "))
cost = int(input("Enter the cost in cents per KwH you pay for electricty "))
# We don't need an auxiliary variable x here
total = (watts * hours / 1000.0 * 30) * cost
print star
print ("""If you use %s watts of electricity for %s hours per day, at a cost of %s cents per Kilo-watt hour, you will add $%s to your monthly electric bill""") % (watts, hours, cost, total)
print star
if __name__ == '__main__':
playagain = 'yes'
while playagain == 'yes':
main()
print 'Would you like to do another Calculation? (yes or no)'
playagain = raw_input()
# Checking that the user's input is whether yes or no
while playagain not in ['yes', 'no']:
print "It's a yes/no question god damn it"
print 'Would you like to do another Calculation? (yes or no)'
playagain = raw_input()
I put your error message in an if statment, and the calculation code in an else. This way it won't do the calculation when the hour isn't correct and instead will exit main and go back to the while loop and ask the user if they will like to play again. Also as other user's have pointed out following what I did below you should add more error testing and messages for negative numbers, etc.
def main():
star = '*' * 70
print star
print ("Nick's Electric Bill Calculator")
print star
watts = input("Enter the watts of appliance, or total watts of appliances ")
hours = input("Enter the number of hours that appliance(s) run per day ")
cost = input("Enter the cost in cents per KwH you pay for electricty " )
if hours > 24:
print("Don't be silly, theres not more than 24 hours in a day ")
else:
x = (watts * hours / 1000.0 * 30) * cost
total = x
print star
print ("""If you use %s watts of electricity for %s hours per day, at a cost of %s cents per Kilo-watt hour, you will add $%s to your monthly electric bill""") % (watts, hours, cost, total)
print star
playagain = 'yes'
while playagain == 'yes':
main()
print('Would you like to do another Calculation? (yes or no)')
playagain = raw_input()
My python skills are a little rusty, but when I have to do stuff like checking input, I usually use a structure something like this:
hours = 0
while True:
hours = input("How many hours per day? ")
#first make sure they entered an integer
try:
tmp = int(hours) #this operaion throws a ValueError if a non-integer was entered
except ValueError:
print("Please enter an integer")
continue
#2 checks to make sure the integer is in the right range
if hours > 24:
print("Don't be silly, theres not more than 24 hours in a day ")
continue
if hours < 1:
print("Enter a positive integer")
continue
#everything is good, bail out of the loop
break
Basically, it starts by going into an 'infinite' loop. It gets the input, goes through all the checks to see if it is valid, and hits the break (leaving the loop) if everything went okay. If the data was bad in any way, it informs the user and restarts the loop with the continue. hours = 0 is declared outside the loop so it is still accessible in the scope outside, so it can be used elsewhere.
Edit: adding an idea to the example code that I thought of after seeing #Ohad Eytan's answer
The input you get from the user is a string type, but you compare it to int type. That's an error. You should cast the string to int first:
hours = int(input("How many hours per day? "))
# ----^---
Then you can do something like:
while hours > 24:
print("Don't be silly, theres not more than 24 hours in a day ")
hours = int(input("How many hours per day? "))
If you don't sure the user will input a number you should use a try/catch statemant.
Except from this you should validate you indent the code correctly
I've been working on a sleep calculator that needs a validation error message. The code that I need to validate is:
hourspernight = int(input("How many hours do you sleep in a day?")
hoursperweek = hourspernight * 7
input("You Sleep for",hoursperweek,"hours every week!")
I need to add validation so that, if the user inputs a character that is not an integer, it shows an error message asking for an integer.
Use a try/except inside a while loop which will keep asking for input until the user enters something valid:
while True:
try:
hourspernight = int(input("How many hours do you sleep in a day?"))
break
except ValueError:
print("Invalid input")
hoursperweek = hourspernight * 7
print ("You Sleep for {} hours every week!".format(hoursperweek))
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.