I would like to ask a question that I have regarding a program, since I am new to Python and I am practicing with conditionals. My program is this:
print("QUE PORCENTAJE DE UNA HORA HA TRANSCURRIDO?")
minuto=int(input("Introduzca el minuto: "))
def porcentajes_hora(hora):
porcentaje=minuto/.6
if minuto>60:
porcentaje=("MINUTO INCORRECTO")
return porcentaje
print(porcentajes_hora(int(minuto)))
As you can see, what it does is ask the minute of the hour that we want to find out its percentage in "int" data type. So if we put "30", the program responds with "50.0". What I would like to know is how I can modify the code so that after the "50.0" the percent sign is put, so that the final answer is "50.0%".
Thank you in advance for your attention, it would be a great help if you could answer this question for me.
You can use
str.format
returning a string like you do in case the minute is greater than 60.either:
The method
format
replaces the targets defined by{}
the arguments passed as arguments.You can use the " Format Specification Mini-Language " to, for example, define the maximum number of decimal places you want to display.
Some observations:
You are not using the hour argument of the function, but the global variable minute. You should use the variable you pass to it as an argument.
Consider using four spaces between levels of indentation, as recommended in PEP-8.
If the minute value is greater than 60 you should avoid calculating the percentage. Use an
else
or make the function return.The code could be something like this:
In this case, two decimal places will always be shown.
The other option is to do:
If you're using Python >= 3.6 you can also use formatted string literals:
either:
Execution examples:
Edition:
As for the explanation of what it does
{0:.2f}
, the general structure is:{}
indicates a "target", it will be replaced in the output string by the corresponding argument passed toformat
, in this case it is replaced by the result ofminuto / 0.6
.That is, when it does
"Hola {}.".format("Mundo")
what it doesformat
is take the string"Hola {}."
and replace the{}
with"Mundo"
, resulting in the string"Hola Mundo."
.The first "0" indicates to use the first element passed to
format
, it's not really necessary in this case (:.2f
) is enough. Indicates the index of the element to use from the tuple passed toformat
. If not specified, they are used in the order they have in the tuple:f
tells it to treat the element to be formatted as a float, displaying it in fixed point format (fixed number of decimal places). We can see what the documentation says (Format Specification Mini-Language):.2
indicates that the precision to use is printing only 2 digits after the decimal point.Some examples:
In the case of
:.2%
equals, only the argument type is treated as an absolute frequency and is automatically formatted as percent percent: