How to format float and range input in Python 2?

Asked

Viewed 2,606 times

1

I need to make an average calculator (student grades) where the entries have a decimal place and are in the range [0, 10]. The exits need to present five decimal places and so far, with what I’ve 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 should I enter the range in this code to limit the entries to the range [0.10] with numbers of one decimal place?

1 answer

1

You should use the "while" construction to keep asking while the input is not good, and the "if" command with conditions to check this. Another good practice, to avoid duplication of code is to use a function -

It could be 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 it: a = float("%.1f" % input()) should give error, why formatting string 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, there is no error because you are using Python 2 - that makes the conversion of the value into input automatically.

Another thing to note is that while we are dealing with text, it makes sense to speak "one position after the decimal point" - when converting the value to float, it uses an internal representation of the computer that can take up to several places 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 number of desired houses, this is not a problem.

And another piece of advice is: since you’re learning the language now, learn Python 3 (preferred version 3.6) - are a few differences, but they make the language much more consistent (for example, the 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 will work also in Python 2.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.