python print error after custom add method - python-3.x

I'm trying to make a Timecode calculator using python but I don't get why the output is wrong:
class Time:
def __init__(self, hour=0, minute=0, second=0, image=0):
self.hour = hour
self.minute = minute
self.second = second
self.image = image
def __str__(self):
return "{:02d}:{:02d}:{:02d}:{:02d}".format(self.hour, self.minute, self.second, self.image)
def __add__(self, second_time):
new_time = Time()
#define image add for 24 FPS
if(self.image + second_time.image) >= 24:
self.second += 1
new_time.image = (self.image + second_time.image) - 24
else:
new_time.image = self.image + second_time.image
#define second add for 24 FPS
if(self.second + second_time.second) >= 60:
self.minute += 1
new_time.second = (self.second + second_time.second) - 60
else:
new_time.second = self.second + second_time.second
#define minutes add for 24 FPS
if(self.minute + second_time.minute) >= 60:
self.hour += 1
new_time.minute = (self.minute + second_time.minute) - 60
else:
new_time.minute = self.minute + second_time.minute
#define hours add for 24 FPS
if(self.hour + second_time.hour) >= 24:
new_time.hour = (self.hour + second_time.hour) - 24
else:
new_time.hour = self.hour + second_time.hour
return new_time
time1 = Time(2, 23, 21, 10)
time2 = Time(2, 21, 2, 22)
test = time1 + time2
print(time1)
if I print time1 before "test = time1 + time2" time1 = 02:23:21:10 but when I print it after test like in the code above the value of time 1 is 02:23:22:10...
did I miss something? why would the value of time1 change?
Thanks for your help

Related

PySimpleGUI Checkbox

Idk why, but when i check a checkbox in the menu nothings, happens, but if i close the menu the cheat start. I think that i made some mistakes setting up the checkboxes, but im trying to fix this problem from 3 days now and i can't continue anymore. Can someone help?
import PySimpleGUI as sg
import threading
from globals import *
import math
import time
import keyboard
switch = True
rcsonoff = True
r = 255
g = 3
b = 3
def normalizeAngles(viewAngleX, viewAngleY):
if viewAngleX > 89:
viewAngleX -= 360
if viewAngleX < -89:
viewAngleX += 360
if viewAngleY > 180:
viewAngleY -= 360
if viewAngleY < -180:
viewAngleY += 360
return viewAngleX, viewAngleY
def checkangles(x, y):
if x > 89:
return False
elif x < -89:
return False
elif y > 360:
return False
elif y < -360:
return False
else:
return True
def nanchecker(first, second):
if math.isnan(first) or math.isnan(second):
return False
else:
return True
layout = [
# Use a modern font and color scheme
[sg.Text("External 2.3", font="Helvetica 20", text_color="#d80fc6")],
# Use tabs to organize the buttons into different categories
[sg.TabGroup([
# Tab for aim-related buttons
[sg.Tab("Aim", [[
sg.Column(
# Define the grid layout for the buttons
[
[sg.Checkbox("No Recoil", default=False, key="no_recoil_checkbox")],
[sg.Checkbox("TriggerBot", default=False, key="triggerbot_checkbox")]
],
# Set the number of rows and columns in the grid
)
]]),
# Tab for visual-related buttons
sg.Tab("Visuals", [[
sg.Column(
# Define the grid layout for the buttons
[
[sg.Checkbox("Glow", default=False, key="glow_checkbox")],
[sg.Checkbox("Chams", default=False, key="chams_checkbox")],
[sg.Checkbox("Fov", default=False, key="fov_checkbox")],
[sg.Text("Fov Value (MAX 140): "), sg.InputText(key="fov")],
[sg.Button("Set FOV Value", button_color=("magenta", "#a9a9a9"))]
],
# Set the number of rows and columns in the grid
)
]]),
sg.Tab("Misc", [[
sg.Column(
[
[sg.Checkbox("Bunny Hop", default=False, key="bunny_hop_checkbox")],
[sg.Checkbox("Radar Hack", default=False, key="radar_hack_checkbox")],
[sg.Checkbox("Show Rank", default=False, key="show_rank_checkbox")],
[sg.Checkbox("Third Person", default=False, key="3_person_checkbox")],
[sg.Checkbox("No Flash", default=False, key="no_flash_checkbox")]
],
)
]]),
sg.Tab("LocalPlayer", [[
sg.Column(
[
[sg.Text("Player Health:")],
[sg.Text(key="Health")],
[sg.Text("Armor:")],
[sg.Text(key="Armor")],
[sg.Text("Enter a new value:")],
[sg.InputText(key="NewArmor")],
[sg.Button("Update Armor")],
[sg.Text("Enter a new money value:")],
[sg.InputText(key="Money")],
[sg.Button("Update Money")]
],
)
]]),
# Tab for color-related buttons
sg.Tab("Color and Debug", [[
sg.Column(
# Define the grid layout for the sliders
[
[sg.Button("Debug", button_color=("magenta", "#a9a9a9"))],
[sg.Text("Enter the glow color values:")],
[sg.Text("Red:"), sg.InputText(key="Red")],
[sg.Text("Green:"), sg.InputText(key="Green")],
[sg.Text("Blue:"), sg.InputText(key="Blue")],
[sg.Button("Set Glow Color")]
],
# Set the number of rows and columns in the grid
)
]])
]])]
]
window = sg.Window("Buck3ts41", layout, element_justification="center")
def debug():
while True:
print("crossID ", crosshairID)
print("corssTeam ", crosshairTeam)
print("LocalPlayer ", player)
print("LocalTeam ", localTeam)
print("GlowManager ", glow_manager)
print("GetTeam ", getTeam)
time.sleep(2)
def esp():
while True:
try:
if glow == True:
for i in range(1, 32):
entity = pm.read_int(client + dwEntityList + i * 0x10)
if entity:
entity_hp = pm.read_uint(entity + m_iHealth)
entity_team_id = pm.read_uint(entity + m_iTeamNum)
entity_dormant = pm.read_uint(entity + m_bDormant)
entity_glow = pm.read_uint(entity + m_iGlowIndex)
if entity_team_id == 2 and localTeam != 2 and not entity_dormant: ###TERRORIST###
pm.write_float(glow_manager + entity_glow * 0x38 + 0x8, float(r)) # R
pm.write_float(glow_manager + entity_glow * 0x38 + 0xC, float(g)) # G
pm.write_float(glow_manager + entity_glow * 0x38 + 0x10, float(b)) # B
pm.write_float(glow_manager + entity_glow * 0x38 + 0x14, float(255)) # A
pm.write_int(glow_manager + entity_glow * 0x38 + 0x28, 1) # START
elif entity_team_id == 3 and localTeam != 3 and not entity_dormant: ###COUNTER###
pm.write_float(glow_manager + entity_glow * 0x38 + 0x8, float(r)) # R
pm.write_float(glow_manager + entity_glow * 0x38 + 0xC, float(g)) # G
pm.write_float(glow_manager + entity_glow * 0x38 + 0x10, float(b)) # B
pm.write_float(glow_manager + entity_glow * 0x38 + 0x14, float(255)) # A
pm.write_int(glow_manager + entity_glow * 0x38 + 0x28, 1) # START
except Exception as err:
pass
time.sleep(0.001)
def chamshack():
if chams:
rgbt = [255, 0, 0]
rgbc = [0, 0, 255]
while True:
try:
time.sleep(0.001)
for i in range(1, 32):
entity = pm.read_int(client + dwEntityList + i * 0x10)
if entity:
entity_team_id = pm.read_uint(entity + m_iTeamNum)
if entity_team_id == 2: # terrorist
pm.write_int(entity + m_clrRender, (rgbt[0])) # R
pm.write_int(entity + m_clrRender + 0x1, (rgbt[1])) # G
pm.write_int(entity + m_clrRender + 0x2, (rgbt[2])) # B
elif entity_team_id == 3: # counter
pm.write_int(entity + m_clrRender, (rgbc[0])) # R
pm.write_int(entity + m_clrRender + 0x1, (rgbc[1])) # G
pm.write_int(entity + m_clrRender + 0x2, (rgbc[2])) # B
else:
pass
except Exception as err:
pass
time.sleep(0.001)
def norcs():
if no_recoil:
oldpunchx = 0.0
oldpunchy = 0.0
while switch:
try:
time.sleep(0.01)
if rcsonoff:
rcslocalplayer = pm.read_uint(client + dwLocalPlayer)
rcsengine = pm.read_uint(engine + dwClientState)
if pm.read_int(rcslocalplayer + m_iShotsFired) > 1:
rcs_x = pm.read_float(rcsengine + dwClientState_ViewAngles)
rcs_y = pm.read_float(rcsengine + dwClientState_ViewAngles + 0x4)
punchx = pm.read_float(rcslocalplayer + m_aimPunchAngle)
punchy = pm.read_float(rcslocalplayer + m_aimPunchAngle + 0x4)
newrcsx = rcs_x - (punchx - oldpunchx) * 2.0
newrcsy = rcs_y - (punchy - oldpunchy) * 2.0
newrcs, newrcy = normalizeAngles(newrcsx, newrcsy)
oldpunchx = punchx
oldpunchy = punchy
if nanchecker(newrcsx, newrcsy) and checkangles(newrcsx, newrcsy):
pm.write_float(rcsengine + dwClientState_ViewAngles, newrcsx)
pm.write_float(rcsengine + dwClientState_ViewAngles + 0x4, newrcsy)
else:
oldpunchx = 0.0
oldpunchy = 0.0
newrcsx = 0.0
newrcsy = 0.0
except Exception as err:
pass
time.sleep(0.001)
def bhop():
if bunny_hop:
while True:
try:
if keyboard.is_pressed("space"):
force_jump = client + dwForceJump
player = pm.read_int(client + dwLocalPlayer)
on_ground = pm.read_int(player + m_fFlags)
if player and on_ground and on_ground == 257:
pm.write_int(force_jump, 5)
time.sleep(0.08)
pm.write_int(force_jump, 4)
except Exception as err:
pass
time.sleep(0.001)
def fovhack():
if fov:
while True:
try:
player = pm.read_int(client + dwEntityList)
pm.write_int(player + m_iDefaultFOV, Fov)
except Exception as err:
pass
time.sleep(0.001)
def r5():
if radar_hack:
while True:
try:
for i in range(1, 32):
entity = pm.read_int(client + dwEntityList + i * 0x10)
if entity:
pm.write_uchar(entity + m_bSpotted, 1)
except Exception as err:
pass
time.sleep(0.001)
def trigger():
if triggerbot:
while True:
try:
# If the crosshair is on an enemy, shoot
if crosshairID > 0 and crosshairID < 64 and crosshairTeam != localTeam:
keyboard.press("attack")
time.sleep(0.1)
keyboard.release("attack")
time.sleep(0.1)
except Exception as err:
pass
time.sleep(0.001)
def person():
if third_person:
switch = 0
while True:
try:
localplayer = pm.read_int(client + dwLocalPlayer)
if keyboard.is_pressed('z') and switch == 0:
pm.write_int(localplayer + m_iObserverMode, 1)
switch = 1
time.sleep(0.5)
if keyboard.is_pressed('z') and switch == 1:
pm.write_int(localplayer + m_iObserverMode, 0)
switch = 0
time.sleep(0.5)
except Exception as err:
pass
time.sleep(0.001)
def noflash():
if no_flash:
if player:
flash_value = player + m_flFlashMaxAlpha
if flash_value:
pm.write_float(flash_value, float(0))
else:
pass
def rank():
if show_rank:
ranks = ["Unranked",
"Silver I",
"Silver II",
"Silver III",
"Silver IV",
"Silver Elite",
"Silver Elite Master",
"Gold Nova I",
"Gold Nova II",
"Gold Nova III",
"Gold Nova Master",
"Master Guardian I",
"Master Guardian II",
"Master Guardian Elite",
"Distinguished Master Guardian",
"Legendary Eagle",
"Legendary Eagle Master",
"Supreme Master First Class",
"The Global Elite"]
for i in range(0, 32):
entity = pm.read_uint(client.lpBaseOfDll + dwEntityList + i * 0x10)
if entity:
entity_team_id = pm.read_uint(entity + m_iTeamNum)
if entity_team_id:
player_info = pm.read_uint(
(pm.read_uint(engine.lpBaseOfDll + dwClientState)) + dwClientState_PlayerInfo)
player_info_items = pm.read_uint(pm.read_uint(player_info + 0x40) + 0xC)
info = pm.read_uint(player_info_items + 0x28 + (i * 0x34))
playerres = pm.read_uint(client.lpBaseOfDll + dwPlayerResource)
rank = pm.read_uint(playerres + m_iCompetitiveRanking + (i * 4))
wins = pm.read_uint(playerres + m_iCompetitiveWins + i * 4)
if pm.read_string(info + 0x10) != 'GOTV':
print(rank)
print(pm.read_string(info + 0x10) + " --> " + ranks[rank])
print(wins)
global glow, chams, no_recoil, triggerbot, bunny_hop, radar_hack, fov, third_person, no_flash, show_rank
while True:
event, values = window.read(timeout=100)
if event == "exit" or event == sg.WIN_CLOSED:
break
if event == "__TIMEOUT__":
# Read the health value of the player
health = pm.read_uint(player + m_iHealth)
# Update the displayed health value
window["Health"].update(str(health))
if event == "Set Glow Color":
# Split the input string into a list of strings representing the red, green, and blue values
r = values["Red"]
g = values["Green"]
b = values["Blue"]
# Convert the strings to integers
r = int(r)
g = int(g)
b = int(b)
if event == "Update Money":
# Read the new money value from the textbox
new_money = values["Money"]
# Convert the new money value to an integer
new_money = int(new_money)
# Write the new money value to the game's memory
pm.write_int(player + m_iAccountID, new_money)
if event == "Update Armor":
# Read the new armor value from the textbox
new_armor = values["NewArmor"]
# Convert the new armor value to an integer
new_armor = int(new_armor)
# Update the armor value
pm.write_int(player + m_ArmorValue, new_armor)
# Update the displayed armor value
window["Armor"].update(str(new_armor))
if event == "Set FOV Value":
Fov = values["fov"]
Fov = int(Fov)
if values["glow_checkbox"] == True:
glow = True
else:
glow = False
if values["chams_checkbox"] == True:
chams = True
else:
chams = False
if values["bunny_hop_checkbox"] == True:
bunny_hop = True
else:
bunny_hop = False
if values["fov_checkbox"] == True:
fov = True
else:
fov = False
if values["radar_hack_checkbox"] == True:
radar_hack = True
else:
radar_hack = False
if values["triggerbot_checkbox"] == True:
triggerbot = True
else:
triggerbot = False
if values["3_person_checkbox"] == True:
third_person = True
else:
third_person = False
if values["no_flash_checkbox"] == True:
no_flash = True
else:
no_flash = False
if values["show_rank_checkbox"] == True:
show_rank = True
else:
show_rank = False
if values["no_recoil_checkbox"] == True:
no_recoil = True
else:
no_recoil = False
if event == "Debug":
debug()
def start_threads():
try:
threading.Thread(target=esp, name='esp').start()
threading.Thread(target=chamshack, name='chamshack').start()
threading.Thread(target=person, name='person').start()
threading.Thread(target=rank, name='rank').start()
threading.Thread(target=norcs, name='norcs').start()
threading.Thread(target=trigger, name='trigger').start()
threading.Thread(target=bhop, name='bhop').start()
threading.Thread(target=r5, name='r5').start()
threading.Thread(target=noflash, name='noflash').start()
threading.Thread(target=fovhack, name='fovhack').start()
except Exception as err:
print(f'Threads have been canceled! Exiting...\nReason: {err}\nExiting...')
exit(1)
start_threads()
window.close()
i really don't know what im i doing wrong, i have decent experience with python but pysimpleGUI is another thing...

Calculate extra time and write to excel with openpyxl

Good morning as per the attached code, I would like to create a function that if the work shift (Bezahltezeit variable is showed in the Überziet column in Excel) is more than 10 hours, a 25% surcharge is created for every minute worked after ten hours.
I should have a result in minutes so that I can then add it up and convert it to excel.
Also in the nachtzeit column the 10% surcharge is calculated for every minute worked between 10 am and 6 am, as you see in the table it is transcribed in hours and minutes, I should have the result in minutes again so that I can add it up and convert to excel.
The function was created with the help of user #constantstranger whom I thank again!
Thanks
Year = int(IcsStartData.year)
Month = int(IcsStartData.month)
Day = int(IcsStartData.day)
StartH = int(IcsStartData.hour)
StartM = int(IcsStartData.minute)
EndH = int(IcsEndData.hour)
EndM = int(IcsEndData.minute)
currentDateTime = datetime.now()
Date_Time_Stamp = currentDateTime.strftime("%d%m%Y%H%M")
Current_DateTime = currentDateTime.strftime("%d.%m.%Y %H:%M")
Datetime = IcsStartData.strftime("%d.%m.%Y")
StartTime = IcsStartData.strftime("%H.%M")
EndTime = IcsEndData.strftime("%H.%M")
Schichtdauer = IcsSchichtDauer.strftime("%H.%M")
Bezahltezeit = IcsBezahlteZeit.strftime("%H.%M")
Bezahltezeit_Stunden = float(IcsBezahlteZeit.strftime("%H"))
Bezahltezeit_Minuten = float(IcsBezahlteZeit.strftime("%M"))
Terminaldata = IcsEndData.strftime("%d.%m.%Y")
EndDay = int(IcsEndData.day)
EndMonth = int(IcsEndData.month)
EndYear = int(IcsEndData.year)
def excelworking():
endTime = IcsEndData
startTime = IcsStartData
def getRegularAndBonusHours(startTime, endTime):
if endTime < startTime:
raise ValueError(f'endTime {endTime} is before startTime {startTime}')
startDateStr = startTime.strftime("%d.%m.%Y")
bonusStartTime = datetime.strptime(startDateStr + " " + "20:00", "%d.%m.%Y %H:%M")
prevBonusEndTime = datetime.strptime(startTime.strftime("%d.%m.%Y") + " " + "06:00", "%d.%m.%Y %H:%M")
bonusEndTime = prevBonusEndTime + timedelta(days=1)
NachtArbeitZeit = timedelta(days=0)
dienstdauer = endTime - startTime
hours = dienstdauer.total_seconds() // 3600
if hours > 24:
fullDays = hours // 24
NachtArbeitZeit += fullDays * (bonusEndTime - bonusStartTime)
endTime -= timedelta(days=fullDays)
if startTime < prevBonusEndTime:
NachtArbeitZeit += prevBonusEndTime - startTime
if endTime < prevBonusEndTime:
NachtArbeitZeit -= prevBonusEndTime - endTime
if startTime > bonusStartTime:
NachtArbeitZeit -= startTime - bonusStartTime
if endTime > bonusStartTime:
NachtArbeitZeit += min(endTime, bonusEndTime) - bonusStartTime
return dienstdauer, NachtArbeitZeit
def getHours(startTime, endTime, extraFraction):
dienstdauer, NachtArbeitZeit = getRegularAndBonusHours(startTime, endTime)
delta = dienstdauer + NachtArbeitZeit * extraFraction
return delta
def testing(start, end):
dienstdauer, NachtArbeitZeit = getRegularAndBonusHours(start, end)
def getHoursRoundedUp(delta):
return delta.days * 24 + delta.seconds // 3600 + (1 if delta.seconds % 3600 else 0)
regularHours, nachtszulage = getHoursRoundedUp(dienstdauer), getHoursRoundedUp(NachtArbeitZeit)
# print(f'start {start}, end {end}, nachtszulage {nachtszulage}, Nachstüberzeit {NachtArbeitZeit / 60 * 10} dienstdauer: {dienstdauer} {NachtArbeitZeit}')
# Writing on a EXCEL FILE
filename = (f"{myPath}/Monatsplan {username} {month} {year}.xlsx")
emptycell = ' '
wegzeiten = (int('13'))
try:
wb = load_workbook(filename)
ws = wb.worksheets[0] # select first worksheet
except FileNotFoundError:
headers_row = ['Datum','Dienst','Funktion','Von','Bis','Schichtdauer','Bezahlte Zeit (Studen)','Bezahlte Zeit (Minuten)','Zeit Konvertierung','Überzeit (ab 10 St.)','Nachtzeitzuschlag.','Nachtdienstentschädigung','Wegzeiten']
wb = Workbook()
ws = wb.active
ws.append(headers_row)
wb.save(filename)
ws.append([f'{Datetime}',f'{string1}'f'{tagesinfo2}',f'{soup_funktion}',f'{StartTime}',f'{EndTime}',f'{Schichtdauer}',f'{Bezahltezeit_Stunden}',f'{Bezahltezeit_Minuten}',f'{emptycell}',f'{emptycell}',f'{NachtArbeitZeit / 60 * 10}',f'{nachtszulage}',f'{wegzeiten}'])
for cols in ws.iter_cols( ):
if cols[-1].value:
cols[-1].border = Border(left=Side(style='thin'),right=Side(style='thin'),top=Side(style='thin'),bottom=Side(style='thin'))
cols[-1].number_format = '0.00'
wb.save(filename)
wb.close()

Tkinter convert entry.get() to integer problem

I am coding a program with Tkinter to calculate wind values. It takes Rwy Heading, Wind Direction and Wind Speed to calculate the wind whether headwind, tailwind or crosswind with the calculated relevant wind speed.
I get this error:
Traceback (most recent call last):
File "C:\Users\altug\Desktop\PROJECTS\ÇALIŞMA.py", line 40, in <module>
rwy_var= int(rwy)
ValueError: invalid literal for int() with base 10: ''
I both tried IntVar() and int(str) method to convert string into integer but it didn't sort out the problem.
Below you can find my code:
ent1 = Entry(root)
ent1.grid(row = 0, column = 1)
ent2 = Entry(root)
ent2.grid(row = 1, column = 1)
ent3 = Entry(root)
ent3.grid(row = 2, column = 1)
rwy = ent1.get()
wind_direction = ent2.get()
wind_speed = ent3.get()
rwy_var= IntVar()
wind_direction_var= IntVar()
wind_speed_var = IntVar()
rwy_var= int(rwy)
wind_direction_var= int(wind_direction)
wind_speed_var = int(wind_speed)
x = rwy_var - wind_direction_var
radx = math.radians(x)
sinx = math.sin(radx)
cosx = math.cos(radx)
def htwind():
txt.delete(0.0, "end")
b = rwy_var + 90
a = rwy_var - 90
if b > 360:
b -= 360
elif a <0:
a+= 360
if x == abs(90):
result = 0
txt.insert(0.0, result +'\n')
elif a <= wind_direction_var or wind_direction_var<= b :
sh = wind_speed_var * cosx
result = "Headwind"+ " " + round(abs(sh))+ " " + "kt"
txt.insert(0.0, result +'\n')
elif a >= wind_direction_var or wind_direction_var >= b :
st = wind_speed_var * cosx
result = "Tailwind"+ " " + round(abs(st))+ " " + "kt"
txt.insert(0.0, result +'\n')
return ""
def xwind():
txt.delete(0.0, "end")
c=rwy_var-180
d= rwy_var + 180
if d > 360:
d -= 360
elif c<0:
c+= 360
if x == 0 or x == abs(180) or y == 0 or y == abs(180):
print("0")
elif c< wind_direction_var:
sxwl = wind_speed_var * sinx
rslt = "L"+""+round(abs(sxwl))+""+"kt"
txt.insert(0.0, rslt +'\n')
elif wind_direction_var<d:
sxwr = wind_speed_var * sinx
rslt = "R"+""+round(abs(sxwr))+""+"kt"
txt.insert(0.0, rslt +'\n')
return ""
txt = Text(root, width=6, height=2, wrap =WORD)
txt.grid(row =1, column = 1)
button_1 =Button(root, text = "search", command=lambda:[htwind(),xwind()])
button_1.grid(row =0, column = 5)
What is my mistake ?
Thanks in advance.
The IntVar is special in that it can't be directly converted to an int. To get its int value, do
rwy_var = rwy.get()

Not able figure out the error in Codewars Growth of a Population kata

I have just tried to attempt some challenges from Codewars. Unfortunately a test out of 106 is failing and I'm not able to find the error since I am new to Python and Codewars.
(see the image)
import math
def nb_year(p0, percent, aug, p):
counter = 0
nw_pop = p0
while nw_pop <= p:
nw_pop = math.floor(nw_pop)
nw_pop = nw_pop + (nw_pop * (percent/100)) + aug
counter += 1
return int(counter)
print(nb_year(1500, 5, 100, 5000))
51 should equal 50
This is using a recursive function.
If the while loop is TRUE it will call back the recursive function until it turns false (which will return the year).
Take note: on the int on line 4, it will turn any decimals into an int.
def nb_year(p0, percent, aug, p, year = 0):
while(p0 < p):
year += 1
p0 = p0 + int(p0 * (percent / 100)) + aug
return nb_year(p0, percent, aug, p, year)
return year
def nb_year(p0, percent, aug, p, count = 0):
if p0 >= p:
return count
else:
count += 1
n = p0 + p0 * (percent / 100) + aug
return nb_year(n, percent, aug, p, count)
print(nb_year(1500, 5, 100, 5000))

Python timer stops at random times

Just a warning, my code uses the pyperclip module but you don't have to pip install it because it is just for cosmetic reasons to make it a little easier. It also reads a file but the contents in the file is not important right now and can be replaced with any file with strings separated by lines.
What I want my code to do is:
WORKING 1. I want to be able to enter in a value for each line in the file, the first number representing hours and the second representing minutes.
NOT WORKING 2. I want to start a timer for for the hours and minutes for each time inputted. After I will add a sound but that is not there yet.
Problem: I input 1 minute for it to count down and it randomly stops in the middle of the count down. I don't know why because sometimes it finishes and sometimes it doesn't.
Code: https://pastebin.com/A2tTHtmK
import re
import pyperclip
from collections import OrderedDict
import time
import sys
import winsound
islandAndTimes = {}
fileObject = open("C:\\Users\\harry\\Desktop\\Skyblock Island bossmob warps.txt", "r")
message = fileObject.read()
whatToSearch = re.compile(r'\/is warp \w+')
l1 = whatToSearch.findall(message)
for eachInList in l1:
pyperclip.copy(eachInList)
typeIslandTime = input("How long until it spawns? (hours, minutes) ")
islandAndTimes[eachInList] = typeIslandTime
newIslandAndTimes = OrderedDict(sorted(islandAndTimes.items(), key=lambda t: t[1]))
if typeIslandTime == "0":
del islandAndTimes[eachInList]
print(newIslandAndTimes)
for everyIsland in newIslandAndTimes:
for firstKey, firstValue in newIslandAndTimes.items():
print("\n")
print(firstKey)
splitValues = firstValue.split()
newHours = int(splitValues[0])
newSecond = 0
newMins = int(splitValues[1])
print(newHours, newMins)
hour = time.strftime("%H")
minute = time.strftime("%M")
print("The hour is " + hour + " the minute is " + minute)
newerHours = newHours + int(hour)
newerMinute = newMins + int(minute)
print("total secodns is " + str(int((int(newHours) * 60 * 60) + int(newMins) * 60)-20))
totalSeconds = int(newHours) * 60 * 60 + int(newMins) * 60-20
while newSecond != 19:
time.sleep(1)
if int(hour) < newerHours or int(minute) < newerMinute:
#int(hour) > newerHours or int(minute) > newerMinute
minute = time.strftime("%M")
hour = time.strftime("%H")
second = time.strftime("%S")
sys.stdout.write('\r' + str("Time until ring: " + str(newHours) + " " + str(newMins) + " " + str(newSecond)))
sys.stdout.flush()
if newSecond == 0:
newSecond = 60
newMins = newMins - 1
elif newMins == 0 and newHours > 0:
newHours = newHours - 1
newSecond = newSecond - 1
print('completed')

Resources