I'm trying to create a program that asks if there was school that day and if so, subtracts that from the total, (86 days left as of 1-22-18). It works, but the program ends after one subtraction, so my question is, is there any way for it to continue running and update itself, or maybe ask the user again in 24 hours (no clue how)?
Python 3.4.4
Windows 10
import time
localtime = time.asctime(time.localtime(time.time()))
day = localtime[0:3]
check = 0
daysLeft = 87 #As of 1-22-18
daysOfTheWeek = ["Mon", "Tue", "Wed", "Thu", "Fri"]
yesPossibilities = ["yes", "y", "yeah"]
print ("Did you have school today?")
schoolToday = input().lower()
if schoolToday in yesPossibilities:
if day in daysOfTheWeek:
daysLeft -= 1
print ("There are", daysLeft, "days of school left!")
I think what you're really trying to do is save the results each time you run your script (Ex: If you run it today, it tells you there are 86 days left, if you run it tomorrow, it tells you there are 85 days left, etc). You probably don't want to run the script forever because if you turn your computer off, the script is terminated, which means you'll lose all of your results. I would save the output to a text file in the following manner:
print("There are" daysLeft, "days of school left!")
with open("EnterNameOfFileHere.txt",'w') as f:
print(daysLeft,file=f)
This will save the daysLeft variable in a text file, which you can access at the start of your program in the following manner:
check = 0
with open("EnterNameOfFileHere.txt") as f:
daysLeft = int(f.readline().strip())
daysOfTheWeek = ....
In summary, implementing this will allow you to save your results each time you run your script so that you can start from that value the next time you run the script.
You need an infinite loop and a sleep timer
import time
time.sleep(86400) #this will make the code sleep for 1 day = 86400 seconds
Next, put the sleep into the infinite loop
while True:
#get input
if input meets condition:
reduce day count by 1
print number of days left
time.sleep(86400)
if days left meets some threshold:
print "school over"
break
Related
I am trying to get into coding and this is kinda part of the assignments that i need to do to get into the classes.
In this task, you will implement a check using the if… else structure you learned earlier.You are required to create a program that uses this conditional.
At your school, the front gate is locked at night for safety. You often need to study late on campus. There is sometimes a night guard on duty who can let you in. You want to be able to check if you can access the school campus at a particular time.
The current hour of the day is given in the range 0, 1, 2 … 23 and the guard’s presence is indicated by with a True/False boolean.
If the hour is from 7 to 17, you do not need the guard to be there as the gate is open
If the hour is before 7 or after 17, the guard must be there to let you in
Using predefined variables for the hour of the day and whether the guard is present or not, write an if statement to print out whether you can get in.
Example start:
hour = 4
guard = True
Example output:
'You're in!'
Make use of the if statement structure to implement the program.
One of my ideas was:
Time = int(input("Time of getting in: "))
open = 7
closed = 17
if Time > open and Time < closed:
print("You can not enter")
cap O will solve
Time = int(input("Time of getting in: "))
Open = 7
closed = 17
if Time > Open and Time < closed:
print("You can not enter")
It's not too difficult, you can do a simple function like that :
def go_to_study(hour, start_day = 7, end_day = 17):
if (hour >= start_day and hour <= end_day):
return True
else:
return False
// on one line, uncomment if you want.
// return (hour >= start_day and hour <= end_day)
hour=int(input("Enter the Hour"))
if hour>=7 and hour<=17:
print("You can Go")
else:
print("You need Guard to let you in")
I have a table of how many hours each employee worked for a week. They can start and end at any time of the day, including overnight shifts. But for each time period, there is a different payrate. For example, from 5am-5pm Mon-Fri is $20/h. But 5pm-11:59pm Fri is $21/h. Sat and Sun full day is $23/h, and Monday 00:00am to 5am is again $20.
Say a worker starts 4pm Fri and ends 2am Sat, so the calculation comes (1 * 20) + (7 * 21) + (2 * 23). Doing these types of calculations for half a dozen workers across the whole week is time consuming and prone to making mistakes.
Instead of doing this manually, how can I write a program to take inputs of the day, start and end time and then calculate what the pay should be?
Not necessarily looking for code (although that would be helpful), but a way to break this down into a way that can be coded.
payrates = {'p1':20, 'p2': 21, 'p3':23, 'p4':20}
#p1 = 5am-5pm Mon-Fri
#p2 = 5pm-11:59pm Fri
#p3 = Sat and Sun full day is $23/h
#p4 = Monday 00:00am to 5am
name = input("Please Enter Staff's Name: ")
stop = ''
totalpay=0
while True:
wrate = input('Enter payrate type: ')
hours = input('No of Hours worked: ')
pay = payrates[wrate] * int(hours)
totalpay += pay
print(f'Subtotal = {totalpay}')
stop = input('Press Enter to continue or type "stop" to finish: ')
if stop == 'stop':
break
else:
continue
print(f'Total pay for {name} is {totalpay}')
Here, I've simply created a dictionary that stores that various pay rates(p1,p2,p3,p4), then with a while loop, i can input the payrate and number of hours worked. Within the loop, I get the total pay calculated, and generate the final value.
This is a basic illustration, in a situation where you have many workers, you can have a dictionary hold all work details of each worker(something like {'victor':{'p1':7, p2:2, p3:1}, 'david': {'p1':8, 'p2':1, 'p3':3},...}, in which case you can run an iteration through the workers dictionary to generate their respective total pay. You may use pandas if your records are much.
I was wondering if someone can point me in the right direction of a basic script.
This is for a game I created and wanted to create a countdown script to go along with it.
I want be able to have 4 users in which the program will first will ask for their name. After that each user will take turns entering their score starting at 100 and decreasing based on their input. Once they hit zero they win. Once the first person hits 0 the others will have a chance to as well until the end of the round. Each 4 inputs will be considered 1 round.
There will be a lot more to the game but I just need the start. I am new to Python but the easiest way for me to learn is to start off on a working script
Thanks!
Are you looking for something like this?
import cmd
number_users = 4
number_rounds = 10 # or whatever
user_names = [None]*number_users
user_scores = [None]*number_users
for i in range(number_users):
print("Enter name for user #{}: ".format(i+1))
user_names[i] = input()
user_scores[i] = 100
for round_number in range(number_rounds):
print(" --- ROUND {} ---".format(round_number+1))
for i in range(number_users):
print("{}, Enter your score: ".format(user_names[i]))
user_scores[i] = input()
print("--- Scores for Round {} ---".format(round_number+1))
for i in range(number_users):
print("{} : {}".format(user_names[i], user_scores[i]))
print("Done")
I am trying to make a program in Python that beeps every hour. and no of beeps should be equal to no of hours. such as for 12 o'clock it should beep 12 times.
but I have no idea how to detect change in hour.
def bep(h):
for i in range(h):
winsound.Beep(2000,800)
sleep(2)
the above code beeps for h no of times and
def hour():
return hour=int(time.ctime(time.time()).split()[3].split(':')[0])
it gives the hour.
but how to detect that hour has changed.
whether should I check every regular time interval and use previous hour and current hour to detect changes? I think this idea is not effective. because of time delay of interval time i.e.
check current time every 5 second and compare two successive check to detect change in hours.
is there any method to accomplish it directly.
At its simplest:
import datetime
import time
current = 0
while True:
time.sleep(5)
if datetime.datetime.now().hour != current:
current = datetime.datetime.now().hour
print "beep" , str(current)
Note you can test the code by using .minute rather than .hour Which will allow you to see if it fits your purposes.
You will have to replace the print "beep", str(current) with a call to your function bep(current)
Also you might want to consider adding a little extra code to your bep(h) function.
if h>12: h=h-12
if h == 0: h = 12
To ensure that for example: at 16:00 you only hear 4 beeps rather than 16 and at midnight, you hear 12 beeps, rather than none.
I'm currently working on a life calculator that i have programmed in python. I need ideas of what to add to it and examples on how to add it and also how do i add a end control so i can just input end and the program stops. I'm trying to make this better because i plan to take it to a technology fair im going to. Here is my code.
print("The Life Calculator")
name = input("What is you're name? ")
age = int(input("age: "))
months = age * 12 #This equals to how many months you have been alive.
days = age * 365 #This equals to how many days you have been alive.
hours = age * 8765.81 #This equals to how many hours you have been alive.
minutes = age * 31556926 #This equals to how many minutes you have been alive.
seconds = age * 3.156e+7 #This equals to how many seconds you have been alive.
miliseconds = age * 3.15569e10 #This equals to how many miliseconds you have been alive.
microseconds = age * 3.156e+13 #This equals to how many microseconds you have been alive.
nanoseconds = age * 3.156e+16 #This equals to how many nanoseconds you have been alive.
print("This is how many months you have been alive.")
print (months) #This shows how many months you have been alive.
print("This is how many days you have been alive.")
print (days) #This shows how many months you have been alive.
print("This is how many hours you have been alive.")
print (hours) #This shows how many hours you have been alive.
print("This is how many minutes you have been alive.")
print (minutes) #This shows how many minutes you have been alive.
print("This is how many seconds you have been alive.")
print (seconds) #This shows how many seconds you have been alive.
print("This is how many miliseconds you have been alive.")
print (miliseconds) #This shows how many miliseconds you have been alive.
print("This is how many microseconds you have been alive.")
print (microseconds) #This shows how many microseconds you have been alive.
print("This is how many nanoseconds you have been alive.")
print (nanoseconds) #This shows how many nanoseconds you have been alive.
lastline = ("this is how long you have been alive, so what are you going to do with the rest of your life?")
print (name)
print (lastline)
Here is a spiffed-up version.
I took a lot of the repetitive statements and converted them to data:
from collections import namedtuple
TimeUnit = namedtuple("TimeUnit", ["name", "per_year"])
units = [
TimeUnit("decade", 0.1 ),
TimeUnit("month", 12.0 ),
TimeUnit("fortnight", 26.09),
TimeUnit("day", 365.25),
TimeUnit("hour", 8765.81),
TimeUnit("minute", 31556926),
TimeUnit("second", 3.156e+7),
TimeUnit("millisecond", 3.15569e10)
]
def get_float(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
pass
def main():
print("The Life Calculator")
name = input("What is your name? ")
years = get_float("What is your age? ")
print("You have been alive for:")
for unit in units:
print(" {} {}s".format(years * unit.per_year, unit.name))
print("what are you going to do with the rest of your life, {}?".format(name))
if __name__ == "__main__":
main()
Your program is running once, not multiple times so actually you don't have to ask to user for end. However, if you want to run your program until user types end, you have to put that codes in a while loop.
If you want to stop running your program when user types end, just add this line to your program;
while True:
#your codes here
#end of your codes add this line
ask=input("Want to end it?")
if ask.lower()=="end":
break
Using lower() so even user types END or eND or EnD etc. it will be ok.