1
I did a time-calculation program on medications. According to the calculations everything is running perfectly, but I did not understand a detail, why the need to use a int()
at a certain point in time.
Can you explain me? Follow the complete code and below the specific part of the 'problem'':
# utf -8
import shutil
columns = shutil.get_terminal_size().columns
print("Olá, Rafaela, vamos calcular quantos dias seus medicamentos irão durar!".center(columns))
quantidade1 = float((input("Quantos comprimidos de 300MG você possui? ")))
quantidade2 = float((input("Quantos comprimidos de 600MG você possui? ")))
dosagem = float((input("Quantos MG você toma diariamente? ")))
total_mg = (quantidade1 * 300) + (quantidade2 * 600)
dias = (total_mg / dosagem)
meses = int((dias / 30))
if dias < 30:
print("Seus medicamentos irão durar %.2f dias!".center(columns) % dias)
elif 60 > dias >= 30:
dias -= 30
print("Seus medicamentos irão durar %d mês e %d dias!".center(columns) % (meses, dias))
else:
dias = dias - (meses * 30)
print("Seus medicamentos irão durar %d meses e %d dias!".center(columns) % (meses, dias))
The question is: if on line 14 I remove the int()
, the else
simply stops working properly and all answers will be X months and 0 days (always 0 days), but I did not understand why. Can someone explain to me?
meses = int((dias / 30))
Here is the example of output of code with and without int()
, to the else
, with the inputs()
of which 240, 450 and 1500.
Seus medicamentos irão durar 7 meses e 18 dias!
using int()
Seus medicamentos irão durar 7 meses e 0 dias!
not using int()
Because you are casting float for integer. Your print is using %d to show the number, which expects an integer. Try switching from %d to %.2f as above and take out the int.
– Kevin Kouketsu
If you wrote the code, I strongly recommend reviewing your development process. The natural is first you understand the problem and from there elaborate the solution; not elaborate a solution to from it seek to understand the problem, as he did.
– Woss
I switched to %.2f and took the int, but the problem came back! Your medications will last 822463 months and 0.00 days!
– Aleczk
As for the development process, I understand the point, but it’s only because I was trying to put into practice what I learned about Control Flow even and it seemed all right, but exceptionally the Else did not match the expected result. I went through all the calculations thinking they were the cause, but in the end it turned out to be this int.
– Aleczk
The function
int()
removes all values after ".". It serves to transform a value to decimal basis integer, which ends up truncating the values to 0 decimal places. So instead of being "3.5 months", the correct one to show to the user would be "3 months and 15 days"– Breno