The goal of the function is to output a value in a given range. Including the start and end value if it is entered as input. The function only outputs the expected result for values at the start and between the range.
def main():
#assume user input will be formatted in 24-hour time as #:## or ##:##
time = input("What is the time: ")
if time >= "7.0" and time <= "8.0":
print("breakfast time")
elif time >= "12.0" and time <= "13.0":
print("lunch time")
elif time >= "18.0" and time <= "19.0":
print("dinner time")
def convert(time):
h, m = time.split(":")
time = float(((float(h) * (60)) + float(m)) / 60)
return time
if __name__ == "__main__":
main()
current output when input is i.e 8:00 --> ""
expected output when input is i.e 8:00 --> breakfast
You need first to call you convert method, and change the conditions to avoid exception comparing string with float
def main():
time = convert(input("What is the time: "))
if time >= 7.0 and time <= 8.0:
print("breakfast time")
elif time >= 12.0 and time <= 13.0:
print("lunch time")
elif time >= 18.0 and time <= 19.0:
print("dinner time")
def convert(time):
h, m = time.split(":")
time = float((int(h) * (60) + int(m)) / 60)
return time
if __name__ == "__main__":
main()
Use datetime.strptime to parse text representations of times, then compare them to other time values.
from datetime import datetime, time
def main():
#assume user input will be formatted in 24-hour time as #:## or ##:##
current_time = input("What is the time: ")
current_time = datettime.strptime(current_time, "%H:%M").time()
if time(7) <= now <= time(8):
print("breakfast time")
elif time(12) <= now <= time(13):
print("lunch time")
elif time(18) <= now <= time(19):
print("dinner time")
if __name__ == "__main__":
main()
Related
The code has successfully able to compute same value of arrival times given by user input. However, its calculations are inaccurate. I do think the code messed up its computation in the initialisation part of priority queue. Please help me to modify it where it can accurately solve/compute with same value of arrival times as well as burst times.
Here is the code:
import sys
import pandas as pd
def srtf():
num_processes = []
# Get number of processes from user (between 5 and 10)
while True:
try:
num_processes = int(input("Enter the number of processes (minimum of 5 and maximum of 10): "))
if 5 <= num_processes <= 10:
break
else:
print("Invalid input. Number of processes must be between 5 and 10.")
except ValueError:
print("Invalid input. Only integers are allowed.")
print("\n")
# Get burst times and arrival times for each process
burst_times = []
for i in range(num_processes):
while True:
try:
burst_time = int(input("Enter burst time for process {} (minimum of 5 and maximum of 15): ".format(i+1)))
if 5 <= burst_time <= 15:
burst_times.append(burst_time)
break
else:
print("\nInvalid input. Burst time must be between 5 and 15.")
except ValueError:
print("\nInvalid input. Only integers are allowed.")
print("\n")
arrival_times = []
for i in range(num_processes):
while True:
try:
arrival_time = int(input("Enter arrival time for process {} (minimum of 0 and maximum of 12): ".format(i+1)))
if 0 <= arrival_time <= 12:
arrival_times.append(arrival_time)
break
else:
print("\nInvalid input. Arrival time must be between 0 and 12.")
except ValueError:
print("\nInvalid input. Only integers are allowed.")
# Initialize variables
process_id = [i+1 for i in range(num_processes)]
remaining_time = burst_times.copy()
completion_time = [0 for i in range(num_processes)]
waiting_time = [0 for i in range(num_processes)]
turnaround_time = [0 for i in range(num_processes)]
response_time = [0 for i in range(num_processes)]
current_time = 0
completed_processes = 0
import heapq
...
# Initialize the priority queue
priority_queue = []
...
while completed_processes != num_processes:
# Add all processes that have arrived to the priority queue
for i in range(num_processes):
if arrival_times[i] <= current_time and remaining_time[i] > 0:
heapq.heappush(priority_queue, (remaining_time[i], i))
if priority_queue:
remaining_time[priority_queue[0][1]] -= 1
current_time += 1
if response_time[priority_queue[0][1]] == 0: # first time process runs
response_time[priority_queue[0][1]] = current_time - arrival_times[priority_queue[0][1]]
if remaining_time[priority_queue[0][1]] == 0:
completed_processes += 1
completion_time[priority_queue[0][1]] = current_time
heapq.heappop(priority_queue)
else:
current_time += 1
# Calculate waiting time and turnaround time
for i in range(num_processes):
waiting_time[i]= completion_time[i] - burst_times[i] - arrival_times[i]
turnaround_time[i] = completion_time[i] - arrival_times[i]
# Calculate average waiting time, average turnaround time and average response time
avg_waiting_time = sum(waiting_time) / len(waiting_time)
avg_turnaround_time = sum(turnaround_time) / len(turnaround_time)
# Create a table with the results
results = {"Process ID": process_id, "Burst Time": burst_times, "Arrival Time": arrival_times,
"Completion Time": completion_time, "Waiting Time": waiting_time, "Turnaround Time": turnaround_time, "Response Time": response_time}
df = pd.DataFrame(results)
# Print the table
print("\n", df)
# Print the average turnaround time, waiting time and response time
print("\n")
print("Average Turnaround Time: ", "{:.2f}".format(avg_turnaround_time))
print("Average Waiting Time: ", "{:.2f}".format(avg_waiting_time))
return df, avg_turnaround_time, avg_waiting_time
srtf()
This is an example of the output(inaccurate) from the terminal:
def main():
x = abc_to_def(input("What time is it? "))
if x >= "7.0" and x <= "8.0":
print("breakfast time")
elif x >= "12.0" and x <= "13.0":
print("lunch time")
elif x >= "18.0" and x <= "19.0":
print("dinner time")
else:
print()
def abc_to_def(p):
hours, minutes = p.split(":")
if float(int(hours)) + int(minutes)/int(60):
return p
if __name__ == "__main__":
main()
When I run the code in the terminal, everything is correct, but when I run check50 it says my output is "".
#!/usr/local/bin/python3
def main():
y = input("What time is it? ")
x = abc_to_def(y)
if x >= 7.0 and x <= 8.0:
print("breakfast time")
elif x >= 12.0 and x <= 13.0:
print("lunch time")
elif x >= 18.0 and x <= 19.0:
print("dinner time")
else:
print("no food")
def abc_to_def(p):
hours, minutes = p.split(":")
p = float(int(hours)) + int(minutes)/int(60)
return p
if __name__ == "__main__":
main()
I just startet with Python and wanted to make a little countdown app, i am able to do it with seconds but when i try to do it with minutes it just goes into the negatives, i tried it with a if statement but instead it goes into the negatives. Any Ideas? Also anything I should change to make my code cleaner? Thanks in advance :)
import winsound
frequency = 1000
duration = 1000
def calc(num):
if dictionary["unit"] == "seconds":
for i in range(num):
print(num)
time.sleep(1)
num = num - 1
if num == 0:
winsound.Beep(frequency, duration)
elif dictionary["unit"] == "minutes":
num2 = 60
sum = 60
for i in range(num*60):
num2 = num2 -1
print(f"{num} Minutes {num2}")
time.sleep(0.005)
if num2 == 0:
num -1
num2 +60
def validation():
try:
number = int(dictionary["time"])
if number > 0:
calc(number)
except ValueError:
print("Do it again")
user = (input("Enter your Time\n"))
splitet = user.split()
dictionary = {"time": splitet[0], "unit": splitet[1]}
validation()
You can convert the minutes to seconds and do while loop for counting down. in for range loop, i already acts like a count down so you don't need to check if num is 0.
import time
import winsound
frequency = 1000
duration = 1000
def parse_time(input_str):
parts = input_str.split()
if len(parts) != 2:
raise ValueError("Wrong format.")
try:
number = int(parts[0])
except ValueError:
raise ValueError("Time is not integer")
if number <= 0:
raise ValueError("Negative Time")
return number, parts[1]
def calculate_seconds(count, measure):
if measure == "seconds":
return count
if measure == "minutes":
return 60 * count
def countdown(n_sec):
# A reversed range loop to count down
# i will decrease from n_sec to 0 in each iteration
for i in reversed(range(n_sec)):
print("%d minutes %d seconds" % (i / 60, i %60))
time.sleep(1)
winsound.Beep(frequency, duration)
if __name__ == "__main__":
# Use raw_input for raw string input.
input_str = raw_input("Enter your Time\n")
count, measure = parse_time(input_str)
seconds = calculate_seconds(count, measure)
countdown(seconds)
I tried these codes.
x = 6
while 1:
if x < 0.999:
break
#execute you function after 6 seconds.
x -= 0.01
sleep(0.01)
But i need to execute on a particular time . So i tried this:
if (self.is_hour_between("09:55:00", "11:20:00")) == True:
#your function
else:
#your function
def time_between(self, start, end):
# Time Now
now = datetime.now().time()
# Format the datetime string
time_format = "%H:%M:%S"
# Convert the start and end datetime to just time
start = datetime.strptime(start, time_format).time()
end = datetime.strptime(end, time_format).time()
is_between = False
is_between |= start <= now <= end
is_between |= end <= start and (start <= now or now <= end)
return is_between
i wanted to run the function at exactly 10 Am and 11Am .If its not the time then wait for it.else if its the time then go for it without waiting
Anwser :
import datetime
import time
while True:
current_dt = datetime.datetime.now()
time_a = datetime.datetime(current_dt.year, current_dt.month, current_dt.day, 9, 55)
time_b = datetime.datetime(current_dt.year, current_dt.month, current_dt.day, 11, 20)
if (time_a<current_dt) and (time_b > current_dt):
print('ok')
else:
time.sleep(60)
I'm writing a program that will do something if now == specific time and day and wait till that time if is not equal.
I have a morning, evening, days values, which shows start time, end time and today's day. I would like to make a program that check if today is a weekday and specific time (between morning and evening) if True to do something and if even one of these is False, gonna wait till that time and after that do something.
I did it with while loop but when it starts with False value(not in right time) it continue printing False even if that time came and value should change to True but it shows True when I start it in right time.
Here is the code:
import datetime
from datetime import date
from time import sleep
#setting values
now = datetime.datetime.now()
morning = now.replace(hour=9, minute=00, second=0, microsecond=0)
evening = now.replace(hour=16, minute=0, second=0, microsecond=0)
days = now.strftime("%A")
#check if time is in range and return True or False
def time_in_range(morning, evening, x):
if morning <= evening:
return morning <= x <= evening
else:
return morning <= x or x <= evening
timerange = time_in_range(morning, evening, now)
#check if today is weekday
if date.today().weekday() == 0:
dayz = True
else:
dayz = False
# If today weekday and time range do something
if dayz == True and timerange == True:
print("Yes")
while dayz == False or timerange == False:
sleep(5)
timerange = time_in_range(morning, evening, now)
print(timerange) #this printing false even if is right time.
# But it shows True when I turn it on in right time
You only initialize your now variable once and never update its value to the current now. You should update the value inside the while loop, for example:
while dayz == False or timerange == False:
sleep(5)
now = datetime.datetime.now()
...
If you are interested in checking just the hours to determine morning and evening as I can see in your code, you can use below snippet:
from datetime import datetime
from datetime import timedelta
from time import sleep
morning_hour = 9
evening_hour = 16
while True:
curr_time = datetime.now()
print("Current time : {0}".format(curr_time))
if curr_time.hour < morning_hour or curr_time.hour > evening_hour or not curr_time.isoweekday():
print("Job start conditions not met. Determining sleep time")
add_days = 0
current_day = curr_time.weekday() == 4
# Add 3 days for fridays to skip Sat/Sun
if current_day == 4:
add_days = 3
# Add 2 days for Saturdays to skip Sunday
elif current_day == 5:
add_days = 2
else:
add_days = 1
next_window = (curr_time + timedelta(days=add_days)).replace(hour=9, minute=0,second=0,microsecond=0)
delta = next_window - datetime.now()
print("Sleep secs : {0}".format(delta.seconds))
sleep(delta.seconds)
else:
print("Do something")
break