Timer shutdown computer(python3.x) - python-3.x

i had code a timer shutdown pc which will shutdown after the times up, but it will keep printing the time remaining which is not good if i want to shutdown my computer after 30 minutes, it will print about 1800 lines, how should i modify it if i want it to print one line of time remaining which will keep changing.
import time
seconds = int(input("seconds:"))
for i in range(seconds):
x = (seconds - i)
print(x)
time.sleep(1)
check = input("do u want to shutdown ur computer?(yes/no):")
if check == "no":
exit()
else:
os.system("shutdown /s /t 1")

Try this. Just replace the string "Shutdown has started" with the shutdown command.
import time
import sys
x=int(input("seconds: "))
print("The timer has started. Time remaining for shut down: ")
def custom_print(string, how = "normal", dur = 0, inline = True):
if how == "typing": # if how is equal to typing then run this block of code
letter = 1
while letter <= len(string):
new_string = string[0:letter]
if inline: sys.stdout.write("\r")
sys.stdout.write("{0}".format(new_string))
if inline == False: sys.stdout.write("\n")
if inline: sys.stdout.flush()
letter += 1
time.sleep(float(dur))
if new_string=="0":
print("\nShut down has started")
else:
pass
for k in range(1,x+1):
k=x-k
custom_print(str(k), "typing", 1)

Related

How can create a count down timer for user input?

So I am wanting to create a program that allows for a limited time for user input. I want the countdown timer that continuously gets updated; while asking for user input on a different line. Currently, the countdown timer is printing to the same line as the user input line. How can I get them on separate lines? Or how do I cancel out user input after a specific time?
def showTime():
h = 0
m = 1
s = 0
total_seconds = h * 3600 + m * 60 + s
while total_seconds > 0:
timer = datetime.timedelta(seconds=total_seconds)
print(timer, end="\r")
time.sleep(5)
total_seconds -= 5
print("Out of time")
def main():
p = Process(target=showTime)
p.start()
user_input = input('\nPlease enter your answer: ')
if user_input == A:
p.terminate()
print('Correct')
else:
p.terminate()
print('Incorrect')
if __name__ == '__main__':
main()

I'm trying to make a sequence calculator with python, and I would like to restart the code at a certain point but I don't know how to do that [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed last year.
I am fairly new to programming and I scrapped some code together to make a sequence calculator using python.
I'm trying to restart it at the "user_continue = input ("Would you like restart [y/n]? ")" part whenever the user would input an invalid answer, but I don't know how to do that, help?
import time
from time import sleep
while True:
def sumOfAP( a, d,n) :
sum = 0
i = 0
while i < n :
sum = sum + a
a = a + d
i = i + 1
return sum
numsterm = int(input("Enter Number OF terms: "))
firstterm = int(input("Enter First Term: "))
difference = int(input("Enter The Difference: "))
print (sumOfAP(firstterm, difference, numsterm))
# restart here
user_continue = input ("Would you like restart [y/n]? ")
if user_continue == ('y'):
print("Continuing...")
sleep(0.5)
elif user_continue == ('n'):
print ("Thank you for using this program")
print ("")
print ("-PettyRap")
sleep(2)
break
else:
print("Error Command Not Found")
???
import time
from time import sleep
def sumOfAP( a, d,n) :
sum = 0
i = 0
while i < n :
sum = sum + a
a = a + d
i = i + 1
return sum
def takeInputs():
numsterm = int(input("Enter Number OF terms: "))
firstterm = int(input("Enter First Term: "))
difference = int(input("Enter The Difference: "))
print (sumOfAP(firstterm, difference, numsterm))
# restart here
takeInputs()
while True:
user_continue = input ("Would you like restart [y/n]? ")
if user_continue == ('y'):
takeInputs()
print("Continuing...")
sleep(0.5)
elif user_continue == ('n'):
print ("Thank you for using this program")
print ("")
print ("-PettyRap")
sleep(2)
break
else:
print("Error Command Not Found")

How to provide window of time for input(), let program move on if not used

what I have is
import time
r = 0
while True:
print(r)
r += 1
time.sleep(3)
number = input()
num = int(number)
#????????????
if num == r:
print('yes')
else:
print('no')
And what I want to do is make it so after every number printed there's a 3 second window for the user to input the value of r, and if the user does nothing then have the program move on. How do I do that?
Here is a working code using signal and Python 3.6+ That should run under any Unix & Unix-like systems and will fail under Windows:
import time
import signal
def handler_exception(signum, frame):
# Raise an exception if timeout
raise TimeoutError
def input_with_timeout(timeout=5):
# Set the signal handler
signal.signal(signal.SIGALRM, handler_exception)
# Set the alarm based on timeout
signal.alarm(timeout)
try:
number = input(f"You can edit your number during {timeout}s time: ")
return int(number)
finally:
signal.alarm(0)
r = 1
while True:
number = input("Enter your number: ")
num = int(number)
try:
num = input_with_timeout()
# Catch the exception
# print a message and continue the rest of the program
except TimeoutError:
print('\n[Timeout!]')
if num == r:
print('yes')
else:
print('no')
Demo 1: Execution without timeout
Enter your number: 2
You can edit your number during 5s time: 1
yes
Enter your number:
Demo 2: Execution with timeout
Enter your number: 2
You can edit your number during 5s time:
[Timeout!]
no
Enter your number:

Unable to record how many times my while loop runs- Python3

I am working on a number guessing game for python3 and the end goal of this is to show the user if they play more than one game that they'll receive an average number of guesses. However, I am unable to record how many times the game actually runs. Any help will do.
from random import randint
import sys
def guessinggame():
STOP = '='
a = '>'
b = '<'
guess_count = 0
lowest_number = 1
gamecount = 0
highest_number = 100
while True:
guess = (lowest_number+highest_number)//2
print("My guess is :", guess)
user_guess = input("Is your number greater than,less than, or equal to: ")
guess_count += 1
if user_guess == STOP:
break
if user_guess == a:
lowest_number = guess + 1
elif user_guess == b:
highest_number = guess - 1
print("Congrats on BEATING THE GAME! I did it in ", guess_count, "guesses")
PLAY_AGAIN = input("Would you like to play again? y or n: ")
yes = 'y'
gamecount = 0
no = 'n'
if PLAY_AGAIN == yes:
guessinggame()
gamecount = gamecount + 1
else:
gamecount += 1
print("thank you for playing!")
print("You played", gamecount , "games")
sys.exit(0)
return guess_count, gamecount
print('Hello! What is your name?')
myname = input()
print('Well', myname, ', I want you to think of number in your head and I will guess it.')
print("---------------------------------------------------------------------------------")
print("RULES: if the number is correct simply input '='")
print("---------------------------------------------------------------------------------")
print(" if YOUR number is GREATER then the output, input '>'")
print("---------------------------------------------------------------------------------")
print(" if YOUR number is LESS then the output, input '<'")
print("---------------------------------------------------------------------------------")
print(" ALRIGHT LETS PLAY")
print("---------------------------------------------------------------------------------")
guessinggame()
guess_count = guessinggame()
print(" it took me this many number of guesses: ", guess_count)
## each game the user plays is added one to it
## when the user wants to the game to stop they finish it and
## prints number of games they played as well as the average of guess it took
## it would need to take the number of games and add all the guesses together and divide it.
It is because you are either calling guessinggame() everytime user wants to play again or you are exiting the program. Also you are setting gamecount to 0 every time you call guessinggame(). You should move gamecount declaration and initialization out of your function. Also increment gamecount before you call guessinggame().

Stopwatch program

I need to make a stop watch program, I need Start, Stop, Lap, Reset and Quit functions. The program needs print elapsed times whenever the Stop or Lap key is pressed. When the user chooses to quit the program should write a log file containing all the timing data (event and time) acquired during the session in human readable format.
import os
import time
log = ' '
def cls():
os.system('cls')
def logFile(text):
logtime = time.asctime( time.localtime(time.time()) )
f = open('log.txt','w')
f.write('Local current time :', logtime, '\n')
f.write(text, '\n\n')
f.close()
def stopWatch():
import time
p = 50
a = 0
hours = 0
while a < 1:
cls()
for minutes in range(0, 60):
cls()
for seconds in range(0, 60):
time.sleep(1)
cls()
p +=1
print ('Your time is: ', hours, ":" , minutes, ":" , seconds)
print (' H M S')
if p == 50:
break
hours += 1
stopWatch()
I have it ticking the time, however they way I have it wont allow me to stop or lap or take any input. I worked to a few hours to find a way to do it but no luck. Any Ideas on how im going to get the functions working?

Resources