import time
listy = ['timer','stopwatch']
def intro():
print("This is a program which contains useful tools")
print(listy)
def timer():
x = int(input("How long Seconds ?"))
while x > 0:
print(x)
time.sleep(1)
x -= 1
def stopwatch():
verif = input("Do you want to start y/n \n")
if verif == 'y':
x = 0
while True:
print(x, end = "\b"*5)
time.sleep(1)
x += 1
def main():
intro()
decider = input("Which Program?")
if decider.lower() == 'timer':
timer()
elif decider.lower() == 'stopwatch':
stopwatch()
main()
in this code i dont know why the \b escape sequence isnt working in cmd or in idle, can anyone explain why? Is it because of a logic error?
A flush may be required. How about...
print("{0}{1}".format("\b"*5, x), end="", flush=True)
Related
This is a program related to windows operations. I have made different versions of this program. So I tried writing a version using classes. I am a beginner and thought this will help me understand the concept but I am getting some errors like
Method 'shutdown_windows' may be 'static'
There are many errors like this and I would like to get some insight about them and how to solve them
This is my code:
import os
import datetime
import time
class WindowsOperations(object):
def __init__(self, shutdown, restart, open_app, close_app):
self.shutdown = shutdown
self.restart = restart
self.open_app = open_app
self.close_app = close_app
def shutdown_windows(self):
time.sleep(remaining_time)
while True:
if time_hour == datetime.datetime.now().hour and time_minutes == datetime.datetime.now().minute: #
os.system("shutdown /s /t 1")
break
def restart_windows(self):
time.sleep(remaining_time)
while True:
if time_hour == datetime.datetime.now().hour and time_minutes == datetime.datetime.now().minute:
os.system("shutdown /r /t 1")
break
def open_application(self):
app_name_open = input("Enter the application name you want to open: ").lower() + ".exe"
time.sleep(remaining_time)
while True:
if time_hour == datetime.datetime.now().hour and time_minutes == datetime.datetime.now().minute:
os.startfile(app_name_open)
break
def close_application(self):
app_name_close = input("Enter the application name you want to close: ").lower() + ".exe"
time.sleep(remaining_time)
while True:
if time_hour == datetime.datetime.now().hour and time_minutes == datetime.datetime.now().minute:
os.system("TASKKILL /F /IM " + app_name_close)
break
choice = int(input("Enter your choice \n1.Shutdown Windows \n2.Restart Windows "
"\n3.Open an application \n4.Close an application \n:"))
time_hour = int(input("Enter hour: "))
time_minutes = int(input("Enter minutes: "))
time_now = datetime.datetime.now()
remaining_time = ((time_minutes - time_now.minute) * 60 + (time_hour - time_now.hour) * 3600) % 86400
print(remaining_time)
my_windows_operation = WindowsOperations('shutdown', 'restart', 'open_app', 'close_app')
if choice == 1:
my_windows_operation.shutdown_windows()
elif choice == 2:
my_windows_operation.restart_windows()
elif choice == 3:
my_windows_operation.open_application()
elif choice == 4:
my_windows_operation.close_application()
else:
print("Please enter a valid input")
Please do modify the code if necessary and give me some tips
The second "Parameter 'shutdown' unfilled" is an error. It's coming because you've defined WindowsOperations intitializer to take 4 parameters:
def __init__(self, shutdown, restart, open_app, close_app):
But when actually creating the object you are passing noothing:
my_windows_operation = WindowsOperations()
You definitely need to fix that.
The first "Method 'shutdown_windows' may be 'static'" is more of a suggestion. It's coming because the method shutdown_windows does not use self - i.e. it need not be part of the class to do it's job.
Sometimes it works fine, sometimes throws an error. Cannot figure it out. No matter how many inputs.
Thats the error. Is it the order of the code or something else?
give_gift.remove(reciever)
ValueError: list.remove(x): x not in list
Code:
import random
import os
import time
random.seed()
buy_gift = []
give_gift = []
names = True
print('Add name, then press ENTER. To finish type "end".')
while names is True:
name = input()
if name == "end":
if len(buy_gift) < 2:
print("Go play with your own gift. Goodbye!")
print()
os.system("PAUSE")
quit()
else:
names = False
else:
buy_gift.append(name)
give_gift.append(name)
exchange = len(give_gift)
os.system("cls")
time.sleep(1)
print("Drawing pairs...")
print()
time.sleep(1)
while exchange > 0:
giver = random.choice(buy_gift)
reciever = random.choice(give_gift)
while giver == reciever:
reciever = random.choice(buy_gift)
print(giver,"buys gift for",reciever)
time.sleep(0.25)
buy_gift.remove(giver)
give_gift.remove(reciever)
exchange -= 1
print()
os.system("PAUSE")
There is an issue with this line:
while giver == reciever:
reciever = random.choice(buy_gift)
It should be:
reciever = random.choice(give_gift)
My python game isn't working, the sequences beginning with:
if int(total_time) > 10:
isn't triggering, but when I press D, C or W I am getting the 'you opened something' text though. The code there is right as far as I know, it's just not working. I used the or prevtime to allow you to do it the first time.
import random, time, pygame, sys
from pygame.locals import *
total_time = time.clock()
pygame.init()
XQR_prevtime = 0
ppayh_prevtime = 0
pu_ekaw_prevtime = 0
diff = 1
windowSurface = pygame.display.set_mode((400,400),0,32)
time.sleep(3)
XQR_awakened = False
ppayh_awakened = False
pu_ekaw_awakened = False
if int(total_time) > 10:
if int(XQR_prevtime) > (12 - diff) or int(XQR_prevtime) == 0 or XQR_awakened == True:
if XQR_awakened == True:
print("You left something open...")
time.sleep(2)
print("And a mystery came in")
time.sleep(2)
sys.exit()
if random.randint(0,diff) == 1:
print(3)
XQR_prevtime = time.clock()
door_opening.play()
XQR_awakened = True
if int(ppayh_prevtime) > (12 - diff) or int(ppayh_prevtime) == 0 or ppayh_awakened == True:
if ppayh_awakened == True:
print("You left something open...")
time.sleep(2)
print("And a friend came in")
time.sleep(2)
sys.exit()
if randint(0,diff) == 1:
print(3)
ppayh_prevtime = time.clock()
closet_opening.play()
ppayh_awakened = True
if int(pu_ekaw_prevtime) > (12 - diff) or int(pu_ekaw_prevtime) == 0 or pu_ekaw_prevtime == True:
if ekaw_up_awakened == True:
print("You left something open...")
time.sleep(2)
print("And an answer came in")
time.sleep(2)
sys.exit()
if randint(0,diff) == 1:
print(3)
pu_ekaw_prevtime = time.clock()
window_opening.play()
pu_ekaw_awakened = True
total_time never changes, so you can never reach your condition.
The line
total_time = time.clock()
assigns a numeric value (a float) to total_time. There is no reference back to the time.clock() function, the function returns just a normal float object, not a timer object.
And normal float values don't change, they are immutable. The total_time value is not going to change as you game runs.
If you want to measure elapsed time, just keep calling time.clock():
if time.clock() > 10:
You don't need to convert a float value to int here, comparisons with integers just work.
I'm trying to make a an input timer on a question that gives the user 5 seconds to answer the question before deciding that no input is the same as the wrong answer, but no body wants to touch it with a 10ft pole, so I'm trying to go about it a different way and break a for loop with input?
Any one got suggestions?
import random
import operator
qLimit = 10
oqLimit = 10
score = 0
maxNum = 10
timeLimit = 0
otimeLimit = 5
import time
ops = {
'+':operator.add,
'-':operator.sub
}
def generateQuestion():
x = random.randint(1,maxNum)
y = random.randint(1,maxNum)
op = random.choice(list(ops.keys()))
a = ops.get(op)(x,y)
print("What is {} {} {}?\n".format(x, op, y))
return a
def askQuestion(a):
timeLimit = otimeLimit
for i in range(0,timeLimit):
guess = input("")
print (timeLimit - i)
time.sleep(1)
if timeLimit == 0:
try:
integer_input = int(guess)
except ValueError:
print('Please enter a valid number')
return
global score
if integer_input == a:
print("Correct!")
score += 1
else:
print("Wrong, the answer is",a)
while qLimit != 0:
askQuestion(generateQuestion())
qLimit -= 1
print ("You have", qLimit, "questions remaining")
print("Your score is",score)
if (qLimit == 0):
break
Adapting the example from the Python docs:
import signal
class OutOfTime(Exception):
"too slow"
def handler(signum, frame):
raise OutOfTime("no input received")
try:
# Set the signal handler and a 5-second alarm
signal.signal(signal.SIGALRM, handler)
signal.alarm(5)
ans = input('What is your favorite color? ')
signal.alarm(0)
except OutOfTime:
print('\nout of time! too slow!')
else:
print('%s, huh? Mine, too!' % ans)
I want to do a countdown loop for a normal raw_input were the normal raw_input don't change, only the numbers (in raw_input).
So, Do you want to try again? [15-1] outputs on one line and the numbers only change.
This is what I have so far and it doesn't work. So how would I do this?
while True:
for i in range(15,-1,-1):
con1=raw_input("\n Do you want to try again? " + str(i,))
if i == 0:
print "\n Thanks for playing!"
exit(0)
elif con1 == "no":
print "\n Thanks for playing!"
time.sleep(3)
exit(0)
elif con1 == "yes":
break
Linux answer -- will not work on Windows
Python 3
import select
import sys
def has_input(timeout=0.0):
return select.select([sys.stdin], [], [], timeout)[0]
def getans(timeout=15):
i = timeout
max_num_length = len(str(timeout))
while i:
print("\rDo you want to try again? {:{}} ".format(i, max_num_length),
end="", flush=True)
i -= 1
if has_input(1):
return input()
print()
return None
print(getans())
Python 2
import select
import sys
def has_input(timeout=0.0):
return select.select([sys.stdin], [], [], timeout)[0]
def getans(timeout=15):
i = timeout
max_num_length = len(str(timeout))
while i:
sys.stdout.write("\rDo you want to try again? {:{}} ".format(i, max_num_length))
sys.stdout.flush()
i -= 1
if has_input(1):
return raw_input()
print
return None
print getans(5)
getans will return None on timeout, or the response otherwise. Theoretically, if a Windows version of has_input could be implemented, this could work on Windows, but I haven't tested that.