Day and night cycle won't work (graphics.py) - python

Whenever I type n for night, it only plays the day cycle. I'm generally new to python and would appreciate help.
userinput = input("Is it day (d) or night (n) - type d or n:")
n = win.setBackground("MidnightBlue")
d = win.setBackground("DeepSkyBlue")
n_message = ("Time has been set to night!")
d_message = ("Time has been set to day!")
for character in range(1333):
if userinput == n:
print(n_message)
win.setBackground("MidnightBlue")
update(30)
sun.undraw()
moon = Circle(Point(100, 100), 90)
moon.setFill("LightYellow")
moon.draw(win)
moon_cover = Circle(Point(140, 90), 60)
moon_cover.setFill("MidnightBlue")
moon_cover.setOutline("MidnightBlue")
moon_cover.draw(win)
else:
print(d_message)
update(30)
win.setBackground("DeepSkyBlue")
break

Related

How do I get just the hours, minutes, and seconds, but separately?

print("Enter your start time!")
time1h = int(input("Hour: "))
time1m = int(input("Minute: "))
time1s = int(input("Second: "))
print("Enter your finishing time!")
time2h = int(input("Hour: "))
time2m = int(input("Minute: "))
time2s = int(input("Second: "))
time1 = datetime.time(time1h,time1m,time1s)
time2 = datetime.time(time2h,time2m,time2s)
diff = datetime.timedelta(hours=(time2.hour - time1.hour), minutes=(time2.minute - time1.minute), seconds=(time2.second - time1.second))
print(diff)
I am trying to print the results from the diff variable separately from each other so I can format it like
"You ran for (diffhours) hours, (diffminutes) minutes, and (diffseconds) seconds"
Alternatively you could do something like this
output_string = str(diff).split(':')
print("You ran for {} hours, {} minutes, and {} seconds".format(*output_string))
While you can use diff.seconds and then carry out various calculations to convert it to hours and minutes as suggested in the other answers, it's also possible to convert diff to a string and process it that way:
diff = str(diff).split(':') # diff will be something like 1:01:23
print(f'You ran for {diff[0]} hours, {diff[1]} minutes and {diff[2]} seconds')
Example output:
You ran for 1 hours, 01 minutes and 01 seconds
Here is the code:
print("Enter your start time!")
time1h = int(input("Hour: "))
time1m = int(input("Minute: "))
time1s = int(input("Second: "))
print("Enter your finishing time!")
time2h = int(input("Hour: "))
time2m = int(input("Minute: "))
time2s = int(input("Second: "))
time1 = timedelta(hours=time1h, minutes=time1m, seconds=time1s)
time2 = timedelta(hours=time2h, minutes=time2m, seconds=time2s)
diff = time2-time1
total_sec = diff.total_seconds()
h = int(total_sec // 3600)
total_sec = total_sec % 3600
m = int(total_sec // 60)
s = int(total_sec % 60)
print(f"You ran for {h} hours, {m} minutes, and {s} seconds")

I get a spare output out of nowhere

My code right here emits a strange output, it gives me the second part of inp_a even though I didn`t ask for it. couldn't find the reason why.
Thanks in advance for the help
inp_a = input("What`s the time you want to start from? ")
military_time = input("is it AM or PM: ").upper()
inp_b = input("How long would you like to wait? ")
day = input("What`s the day today?\nThe day must be one of the weekdays ")
inp_a = inp_a.split(":")
inp_b = inp_b.split(":")
day = day.lower()
if military_time == "AM":
inp_a[0] = inp_a[0]
elif military_time == "PM":
inp_a[0] = int(inp_a[0]) + 12
inp_a[0] = str(inp_a[0])
try:
convert_a1 = int(inp_a[0])
convert_a2 = int(inp_a[1])
convert_b1 = int(inp_b[0])
convert_b2 = int(inp_b[1])
except:
print("-"*50)
print("One of the inputs is incorrect, try again")
while True:
if day == "sunday":
break
elif day == "monday":
break
elif day == "tuesday":
break
elif day == "wednsday":
break
elif day == "thursday":
break
elif day == "friday":
break
elif day == "saturday":
break
else:
print(day,"is not one of the weekdays try again")
quit()
rl_time = int(inp_a[0])*60 + int(input(inp_a[1]))
time2add = int(inp_b[0]*60) + int(input(inp_b[1]))
result = rl_time + time2add
hh = result // 60
mm = result % hh
The error is in this part of the code:
rl_time = int(inp_a[0])*60 + int(input(inp_a[1]))
time2add = int(inp_b[0]*60) + int(input(inp_b[1]))
You're calling input again for no reason, and input prompts the user with its argument (in this case inp_a[1], which is the extra output you're seeing). If you enter something it'll do the same thing on the next line with inp_b[1].
Here's a fixed version of the full thing -- you can simplify a lot by just doing the int conversion once, rather than converting to int, converting back to str, back to int, etc. You also had your while loop in the wrong spot if the intent is to re-prompt the user for new values when something is incorrect.
while True:
inp_a = input("What`s the time you want to start from? ")
military_time = input("is it AM or PM: ").upper()
inp_b = input("How long would you like to wait? ")
day = input("What`s the day today?\n"
"The day must be one of the weekdays"
).lower()
try:
ah, am = map(int, inp_a.split(":"))
bh, bm = map(int, inp_b.split(":"))
except (TypeError, ValueError):
print("Time must be entered as HH:MM")
continue
if day not in ("monday", "tuesday", "wednesday", "thursday", "friday"):
print(f"{day.title()} is not one of the weekdays, try again.")
continue
break
if military_time == "PM":
ah += 12
rl_time = ah * 60 + am
time2add = bh * 60 + bm
result = rl_time + time2add
hh, mm = divmod(result, 60)

find an overlapping apppointment in a list

After it validates the date and time for the appointment I need to make sure it doesn't overlap with a pre-existing appointment in the appontmentList[] and I'm stuck as to where to start.
I'm thinking somewhere along the lines of:
for x in appointmentList:
if start <= x:
print('invalid, overlapping appointment! ')
else:
break
See my full code below:
appointmentList = []
def add_sort():
choice = input ('Add item to diary (a) or sort (s)')
if choice == 's':
print ('sorting')
sortRecords()
elif choice == 'a':
print ('adding')
add_record()
else:
add_sort()
def add_record():
while True:
Priority = input ('What is the priority of your appointment? ')
if 'low' != Priority != 'Low' and 'high' != Priority != 'High':
print('invalid, must be low or high! ')
else:
break
# is_valid_date():
while True:
dt = input('enter date of appointment in dd/mm/yyyy format. ')
day_string, month_string, year_string = dt.split('/')
day = int(day_string)
month = int(month_string)
year = int(year_string)
if month in [1, 3, 5, 7, 8, 10, 12]:
max_days=31
elif month in [4, 6, 9 ,11]:
max_days=30
elif year%4==0 and year%100!=0 or year%400==0:
max_days=29
else:
max_days=28
if month<1 or month>12:
print('invalid, enter a number between 1 - 12')
elif day<1 or day>max_days:
print('invalid, check day')
elif 10000 > year <2022:
print('invalid, enter a year greater than 2021')
# is_valid_time():
Start = int(input('What is the starting time of your appointment? '))
if Start < 7 or Start > 22:
print('invalid, enter a time between 7 - 22. ')
End = int(input('What is the ending time of your appointment? '))
if End < Start or End > 22:
print('invalid, please choose a time after starting time. ')
# def is_concurrent():
from datetime import datetime
start = datetime.combine(datetime.strptime(dt, '%d/%m/%Y'), datetime.strptime(str(Start), '%H').time())
end = datetime.combine(datetime.strptime(dt, '%d/%m/%Y'), datetime.strptime(str(End), '%H').time())
current = datetime.now()
if start < current:
print('invalid, enter a time & date in the future! ')
elif end < start:
print('invalid, enter an end time after the start time! ')
else:
break
Subject = input ('What is the subject of your appointment?')
appointment = ['{}; {}; {}; {}; {};'.format(Priority, dt, Start, End, Subject)]
appointmentList.append(appointment)
print(appointmentList)
add_sort()
def sortRecords():
choice = input ('Do you want to sort by priority or time or END. ')
if choice.lower() == 'priority':
print ('priority')
print(appointmentList)
plist = sorted(appointmentList, key = lambda x: x[0])
print(plist)
sortRecords()
elif choice.lower() == 'time':
print('time')
print(appointmentList)
tlist = sorted(appointmentList, key = lambda x: x[1])
print(tlist)
sortRecords()
elif choice.lower() != 'end':
print ('invalid')
sortRecords()
add_sort()
for x in appointmentList:
print (x)
add_sort()
the idea is the user inputs an appointment with priority, date, start time, end time and subject, it first prints like this '[['high; 15/7/2022; 8; 9; Hello;']]' and then saves it to the appointment list, I need to find out how to see if a previously made appointment overlaps with the appointment the user is currently trying to enter.

datetime format over 24 hours

I'm trying to add time and have the output as hh:mm:ss, but when datetime gets over 24 hours it becomes x Days, hh:mm:ss. Is there anyway to only have hh:mm:ss greater than 24 hours?
import datetime
from datetime import timedelta
# intro
print("Welcome to TimeCalc")
print("Calculating Durations")
clear = True
while clear == True:
# first input
firstNumber = True
while firstNumber == True:
time_1 = input("Please enter a time [hh:mm:ss] including 0s: ")
if len(time_1) > 0 and len(time_1) >= 8 and time_1[-6] == ":" and time_1[-3] == ":" and int(time_1[-5:-3]) < 60 and int(time_1[-2:]) < 60:
hours_1 = time_1[:-6]
minutes_1 = time_1[-5:-3]
seconds_1 = time_1[-2:]
hours_1 = int(hours_1)
minutes_1 = int(minutes_1)
seconds_1 = int(seconds_1)
firstNumber = False
else:
print("Invalid Syntax")
time_1 = datetime.timedelta(hours=hours_1, minutes=minutes_1, seconds=seconds_1)
cont = True
while cont == True:
# second input
secondNumber = True
while secondNumber == True:
time_2 = input("Please enter a time to add [hh:mm:ss] including 0s: ")
if len(time_2) > 0 and len(time_2) >= 8 and time_2[-6] == ":" and time_2[-3] == ":" and int(time_2[-5:-3]) < 60 and int(time_2[-2:]) < 60:
hours_2 = time_2[:-6]
minutes_2 = time_2[-5:-3]
seconds_2 = time_2[-2:]
hours_2 = int(hours_2)
minutes_2 = int(minutes_2)
seconds_2 = int(seconds_2)
secondNumber = False
else:
print("Invalid Syntax")
time_2 = datetime.timedelta(hours = hours_2, minutes = minutes_2, seconds = seconds_2)
total = time_1 + time_2
print("The total duration is: " + str(total))
# continue, clear, or exit
choice = input("Continue: Y | Clear: N | Exit: X: ")
if choice == "Y" or choice == "y":
time_1 = total
elif choice == "N" or choice == "n":
cont = False
elif choice == "X" or choice == "x":
quit()
after total variable, can you try to put this code, maybe this is not a super solution but it works
seconds = int(total.total_seconds())
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
print("The total duration is: {h:02d}:{m:02d}:{s:02d}".format(h=hours,
m=minutes, s=seconds))
Use the .strftime() method to format your datetime string.
For example,
>>> import datetime
>>> d = datetime.delta(hours=1)
>>> dt = datetime.datetime(2017,10,30,23,10,10) + d
>>> dt.strftime("%H:%M:%S")
'00:10:10'
Hope it help.

I am trying to figure the best way to split up this function into two separate functions

I am trying to figure out the best way to split up this function into two separate functions. One being Main() and the other being determineStatus(). I have to use Main() to call determineStatus. The code does exactly what I want it to do just not sure a effective way to split it up.
Not really sure a way to split it up without getting tons of errors.
message="How many current credit hours do you have?"
def determineStatus(message):
while True:
try:
userInput = int(input(message))
except ValueError:
print("Please use whole numbers only. Not text nor decimals.")
continue
else:
return userInput
hours = determineStatus(message)
F=30
J=60
S=90
Max=200
if hours <= Max:
if hours < F:
print("You are classified as a Freshman")
if hours > F and hours < J:
print("You are classified as a Sophmore")
if hours >= J and hours < S:
print("You are classified as a Junior")
if hours >= S and hours < Max:
print("You are classified as a Senior")
else:
print("With",hours," hours you are either an Alumni, 2nd Degree seeking student or lying about your hours.")
determineStatus(message)
A right data structure is a great code-cutting tool.
# python 3.x
CLASSIFIER = [
# (min, max, status)
(0, 30, 'Freshman'),
(30, 60, 'Sophomore'),
(60, 90, 'Junior'),
(90, 200, 'Senior'),
]
def classify(hours):
assert hours >= 0, 'WTF, negative hours'
for (lower, upper, status) in CLASSIFIER:
if lower <= hours < upper:
return status
return 'Alumni, 2nd Degree seeking student or lying about your hours'
def ask(message):
while True:
try:
return int(input(message))
except ValueError:
print('Try entering a non-negative whole number again.')
def main():
hours = ask('How many hours? ')
print('With %d hours, you are %s' % (hours, classify(hours)))
# Optional: auto-invoke main() if we're being executed as a script.
if __name__ == '__main__':
main()
I would do it this way.
Create a module
F = 30
J = 60
S = 90
Max = 200
def determineStatus(message):
while True:
try:
userInput = int(input(message))
except ValueError:
print("Please use whole numbers only. Not text nor decimals.")
continue
else:
return userInput
def calculateStatus(hours):
if hours <= Max:
if hours < F:
return "You are classified as a Freshman"
if hours > F and hours < J:
return "You are classified as a Sophmore"
if hours >= J and hours < S:
return "You are classified as a Junior"
if hours >= S and hours < Max:
return "You are classified as a Senior"
else:
return "With {0} hours you are either an Alumni, 2nd Degree seeking student or lying about your hours.".format(hours)
Now create a little script:
import temp
message = "How many current credit hours do you have?"
# You can repeat the lines below by using a while loop
hours = temp.determineStatus(message)
print temp.calculateStatus(hours)
For your multiple ifs, you get a warning from the Department of Redundancy Department!
If hours is not smaller than J, there's no need in checking it's greater than or equal to J.
Also, if hours = F, you'll return that the student is lying.
Finally, you won't return anything for hours = Max.
Here's an optimized determine_status function :
statuses = [
(30, 'Freshman'),
(60, 'Sophomore'),
(90, 'Junior'),
(200, 'Senior')
]
def determine_status(hours):
for max_hours, status in statuses:
if hours < max_hours:
return "You are classified as a %s" % status
return "With %d hours you are either an Alumni, 2nd Degree seeking student or lying about your hours." % hours
print(determine_status(0))
# You are classified as a Freshman
print(determine_status(30))
# You are classified as a Sophomore
print(determine_status(55))
# You are classified as a Sophomore
print(determine_status(75))
# You are classified as a Junior
print(determine_status(100))
# You are classified as a Senior
print(determine_status(205))
# With 205 hours you are either an Alumni, 2nd Degree seeking student or
# lying about your hours.

Categories

Resources