so im Writing python script test i got from scholl but for some reason it dosen't even starts ... no error no nothing ..
its supposed to be and employes log system .. used threading for the infinite loop that's supposed to count the min and creat checking clock for the "employs" and run in background and another function that suppused to read the employ name check if his allready signed in or not and if not to add him to a file with the clock time and name or for the other way around , to log him off but for some reason the code dosent even run , no error , nothing just blank run screen, ill be glad to get some help ..
#!/bin/usr/python
from datetime import datetime
import threading
import time
users=open("logfile.txt","w")
def background():
seconde = 0
minute = 0
hour = 0
while True:
time.sleep(1)
seconde = seconde + 1
if seconde == 60:
minute = minute + 1
seconde = 0
elif minute == 60:
hour = hour + 1
minute = 0
alltime = str(hour) + ":" + str(minute) + ":" + str(seconde)
def foreground():
alin = []
name = input("Hello Deal employ , please insert your name:\n")
if name not in alin:
login=input("your not logged in , do you wish to log?\n")
if login == "yes" or "Y" or "y" or "Yes":
users.write("{} Entry Hour :".format(name) + alltime)
alin.append(name)
elif login == "no" or "N" or "n" or "No":
print("ok") and exit()
elif name in alin:
logout=input("Your allready signed in , do you wish to check out?\n")
if logout == "Yes" or "Y" or "Y" or "yes":
users.write("{} Leaving Hour :".format(name) + alltime)
elif logout == "no" or "N" or "n" or "No":
print("ok") and exit()
b = threading.Thread(name='background', target=background())
a = threading.Thread(name='foreground', target=foreground())
b.start()
a.start()
b = threading.Thread(name='background', target=background())
target should be a callable object. As is, you are running background before starting the thread. As background never stops, your program runs forever. Try:
b = threading.Thread(name='background', target=background)
I'm not sure exactly what you're trying to do, but I'm pretty sure it's not going to work.
Related
import time
print("The timer on this project Will start")
#Ask To Begin
start = input('Would you like to begin learning now? (yes / no):')
if start == 'yes':
timeloop = True
#variable to keep the time
Sec = 0
Min = 0
#Begin process
timeloop = start
while timeloop:
Sec +=1
print(str(Min) + " Mins " + str(Sec) + " Sec ")
time.sleep(1)
if Sec == 60:
Sec = 0
Min +=1
print(str(Min) + " Minute ")
This is my timer program so far but I am not sure How I can get it to stop once it starts in the command prompt?. I want to be able to press X and have the code pause. Or perhaps press Y and then it resumes, and Z just closes the program all together, but I have no idea as to how.
time.sleep actually stop the execution of the current process the code is running on. If you want to keep time and still make the process responsive, you may want to use a thread to keep time and install the keyboard package to use keyboard.is_pressed()!
This article is really good:
https://realpython.com/intro-to-python-threading/#what-is-a-thread
So I'm making a little speed game. A random letter is going to be generated by a function, right after that, I want the program to wait some seconds. If nothing is pressed, you will lose and your record will be displayed If you press the right key, another random letter is going to be displayed. I used the time function and simulated a cronometer that lasts in a range (0,2). This is what I have so far. It works, the thing is, it displays the first letter, if you press it wrong you lose (good) but even if you press it right, the cronometer obviously keeps running, so it gets to 2 and you lose. I want it to stop and reset after I hit the key, but I have no idea of how to do it. Im new in programming so I'm sorry if you don't get something.
import string
import random
import msvcrt
import time
def generarletra():
string.ascii_lowercase
letra = random.choice(string.ascii_lowercase)
return letra
def getchar():
s = ''
return msvcrt.getch().decode('utf-8')
print("\nWelcome to Key Pop It!")
opcion = int(input("\n Press 1 to play OR\n Press 2 for instructions"))
if(opcion == 1):
acum=0
while True:
letra2 = generarletra()
print(letra2)
key = getchar()
for s in range (0,2):
print("Segundos ", s)
time.sleep(2)
acum = acum + 1
if((key is not letra2) or (s == 2)):
print("su record fue de, ", acum)
break
elif(opcion == 2):
print("\n\nWelcome to key pop it!\nThe game is simple, the machine is going to generate a
random\nletter and you have to press it on your keyboard, if you take too\nlong or press the wrong
letter, you will lose.")
else:
print("Invalid option!")
PD: You need to run it with a console simulation in your IDE or directly from the console. msvcrt library won't work inside an IDE for some reason.
msvcrt.getch() is blocking, so you don't actually measure the time it took the user to press the key. The for loop starts after the user already pressed it.
also, time.sleep() is blocking, so the user will have to wait the sleep time even if he already pressed the key.
To solve the first problem you can use msvcrt.kbhit() to check if the user pressed on some key, and call msvcrt.getch() only if he did. This way msvcrt.getch() will return immediately after you call it.
To solve the second problem you can just use time.time() to get the start time of the round, and compare it to current time inside a loop. You can print how much time passed inside the loop also.
Here is the final code (with some extra naming and formatting changes):
import string
import random
import msvcrt
import time
MAX_TIME = 2
def get_random_char():
return random.choice(string.ascii_lowercase)
def get_user_char():
return msvcrt.getch().decode('utf-8')
print("\nWelcome to Key Pop It!")
option = input("\n Press 1 to play OR\n Press 2 for instructions\n")
if option == "1":
score=0
while True:
char = get_random_char()
print("\n" + char)
start_time = time.time()
while not msvcrt.kbhit():
seconds_passed = time.time() - start_time
print("seconds passed: {0:.1f}".format(seconds_passed), end="\r")
if seconds_passed >= MAX_TIME:
key = None
break
else:
key = get_user_char()
if key != char:
break
score = score + 1
print("\nsu record fue de, ", score)
elif option == "2":
print("""
Welcome to key pop it!
The game is simple, the machine is going to generate a random
letter and you have to press it on your keyboard, if you take too
long or press the wrong letter, you will lose.""")
else:
print("Invalid option!")
Timestamp-solution:
from time import time, sleep
start = time() # start time measuring by creating timestamp
def time_passed(start, duration):
"""tests if an amount of time has passed
Args:
start(float): timestamp of time()
duration(int): seconds that need to pass
Returns:
bool: are 'duration' seconds over since 'start'
"""
return start + duration <= time()
# Use as condition for while
while not time_passed(start, 5):
sleep(1)
# ... or if statements or <younameit>
if time_passed(start, 5):
print("Do something if 5 seconds are over")
So I'm fairly new to Python and I am trying to write a code for a timer. My code is supposed to get the hour, minute, whether it's AM or PM, and a message that they want the program to print out when their timer is done. As of now, the program asks several questions and stores them in variables, but doesn't print out the message when it is done.
I have tried looking at each part of the code and the code is fairly simple so I don't understand why this is occurring.
# Set up variables
hour = int(input('What should the hour be? '))
minute = input('What should the minute be? ')
ampm = input('A.M. or P.M.? ')
if (ampm == 'A.M.'):
if (hour == 12):
hour = 0
else:
hour = hour
if (ampm == 'P.M.'):
if (hour == 12):
hour = hour
else:
hour = hour + 12
message = input('What should the message be? ')
import datetime
current_hour = datetime.datetime.today().strftime('%H')
current_minute = datetime.datetime.today().strftime('%M')
alarm = True
# Set up loop
while (alarm):
if (hour != datetime.datetime.today().strftime('%H')):
alarm = True
else:
if (minute == datetime.datetime.today().strftime('%M')):
print(message)
alarm = False
else:
alarm = True
It is supposed to print out the message that the user inputted. It's not doing that.
The variable of hour returns an int value and datetime.datetime.today().strftime('%H') returns string so your program get in the infinite loop.Change condition like
if (hour != int((datetime.datetime.today().strftime('%H')))):
So i created a while loop that the user input and an output is returned
choice = input()
while True:
if choice == "Mark":
print("Zuckerberg")
elif choice == "Sundar":
print("Pichai")
and i want to keep time so when i hit Facebook is going to keep time for FB and when i type Google is going to keep time for google like this
import time
choice = input()
while True:
if choice == "Facebook":
endb = time.time()
starta = time.time()
if choice == "google":
enda = time.time()
startb = time.time()
if choice == "Mark":
print("Zuckerberg")
elif choice == "Sundar":
print("Pichai")
if i make this like above when i get to print the elapsed time is going to print
the same number but is going to be minus instead of plus, and vice versa
elapseda = enda - starta
elapsedb = endb - startb
print(elapseda)
print(elapsedb)
How do i keep track of the time but be able to interact with my other input/outputs?
Thanks
##############################################################################
Edit: Sorry for making it not clear. What i meant by tracking time it that instead of print an output when you type a keyword is going to track time. This will be used to take the possession time of a sport match but meanwhile count other stats like Penalty Kicks and stuff. I cant post my code due to character limit but here is an idea:
while True:
choice = input()
if choice == "pk":
print("pk")
elif choice == "fk":
print("fk")
elif choice == "q":
break
and in there i should put possession time but meanwhile i want to interact with the others
In the while loop you could count seconds like so.
import time
a = 0
while True:
a = a + 1
time.sleep(1)
That would mean that a is about how many seconds it look to do the while loop.
I have another question related to this game, here it is:
https://stackoverflow.com/questions/28545444/python-3-game-bug-message-repeating
I made a game thats a knock off of Cookie Clicker (just for coding practice!). And I ran into a problem where the user can hold down the enter key, and get coins really fast. I'd like to prevent that. here is my code:
coin = 0
keepgoing = True
while keepgoing == True:
print('You have ' + str(coin) + ' cmd-coins' )
response = input('Press enter to get a coin!')
if response == 'q':
keepgoing = False
print('Thanks for playing!')
coin = coin + 1
I wrote a rather "gimmicky" solution to your problem, which works to an extent but definitely isn't flawless. Based on your compiler you may have to change the conditional value for start-end such that it is a value which allows you to static press as fast as humanly possible without breaking but not allow the user to hold the enter key. For me in WingIde, 0.03 is the optimal value.
Were you to import a module such as Pygame you would find this sort of game much easier to make.
import time
coins = 0
keepgoing = True
end = -1
while keepgoing:
print('You have ' + str(coins) + ' cmd-coins' )
response = input('Press enter to get a coin!')
start = time.time()
if start-end < 0.03:
print ("Don't hold down the Enter key you cheater!")
keepgoing = False
if response == 'q':
print('Thanks for Playing!')
keepgoing = False
coins = coins + 1
end = time.time()
NOTE: This solution is for Python 3, for < Python 3 you'll have to substitute raw_input() for input(). Also, I wouldn't advise trying to use it on an online compiler.
G Force dog,
You could change your game a bit by making a few changes till someone or I figure out a good solution(Mom gave orders to go to bed). Till we don't find a solution, use this code which isn't exactly a solution.
coins = 0
real = 0
while real == 0:
if True:
print('You have ' + str(coins) + ' cmd-coins' )
response = input('Press c to get a coin, then press ENTER!')
if response == 'c' or response == 'C':
coins = coins + 1
if response == 'q':
print('Thanks for playing!')
real = 1
And 2 things:-
Nice answer Yeniaul! Good try!
Elizion, nice try but your method isn't working. But it is a good idea.
I have used time too, but it seems that when one presses ENTER key for a long time, it just comes out on the screen all together.
I think I do have somewhat of an idea forming... if we make another while loop, after importing 'time', with a condition which makes the loop active every 2 seconds by assigning a variable 'time.clock()' and when its value is a multiple of 2, it activates!
Got it? I know what to do, but can't seem to put it in code. See if you can, reader(especially Elizion and Yeniaul)
Try using time.sleep(seconds of delay) for slowdown
So you could do
coin = 0
keepgoing = True
while keepgoing == True:
time.sleep(0.25)
print('You have ' + str(coin) + ' cmd-coins' )
response = input('Press enter to get a coin!')
if response == 'q':
keepgoing = False
print('Thanks for playing!')
coin = coin + 1
This would make it a quarter-second delay before they could get another coin.