How to format input with float and range in Python 2?

1

I need to make an average calculator (student notes) where the entries have a decimal place and are in the range [0, 10]. The outputs must have five decimal places and so far, with what I have been able to describe, the code is:

a = float("%.1f" % input())  
b = float("%.1f" % input()) 
MEDIA = (a + b) / 2  
print 'MEDIA =', "%.5f" % MEDIA  
exit()

How do I insert the range in this code to limit the entries in the range [0.10] with numbers in a decimal place?

    
asked by anonymous 26.04.2017 / 16:53

1 answer

1

You should use the while construct to continue asking while the input is not good, and construct "if" with conditions to verify this. Another good practice, to avoid code duplication is to use a function -

It may look something like this:

from __future__ import print_function
import sys

if sys.version[0] == '2':
    input = raw_input

def obtem_nota(nome):
   ok = False
   while not ok:
       texto = input("Por favor, digite a nota {}: ".format(nome))
       # tentamos converter a nota entrada como texto para um valor.
       # se ocorrer um erro, não foi um número válido:
       try:
           nota = float(texto)
       except ValueError:
           print("Entrada de nota incorreta. Digite novamente.", file=sys.stderr)
           continue
       # Verificar se há apenas um dígito apos o ponto,
       # E se não há caracteres além de digitos e .
       # e se o valor está entre 0 e 10:
       if (len(texto.split(".")[-1]) <= 1 and
           texto.replace(".", "").isdigit() and
           0 <= nota <= 10
          )
          ok = True
       else:
           print("Entrada de nota incorreta. Digite novamente.", file=sys.stderr)
   return nota

a = obtem_nota("a")
b = obtem_nota("b")
media = (a + b) / 2  
print ('MEDIA =', "%.5f" % media) 

The way you were trying to do: a = float("%.1f" % input()) should give error, because the string formatting with code "%f" expects the parameter to be a number - only that the input returns a string, and it is only after the call to float that we have a number. Oh, it does not make a mistake because you're using Python 2 - which does the value conversion in the input automatically.

One thing to keep in mind is that while we are dealing with text, it makes sense to speak "a position after the decimal point" - when converting the value to float, it starts using an internal representation of the computer that can occupy multiple houses after the comma. But if we limit the value while it is still text, and format the text again at the time of printing with the desired number of houses, this is not a problem.

And another piece of advice is: since you are learning language now, learn Python 3 (version 3.6 preferably) - are a few differences, but they make language much more consistent (eg input always returns text, without trying to guess what the user might have typed). In the code above I put some preliminary lines so that the program is written as in Python 3, but it will work also in Python 2.

    
26.04.2017 / 20:05