1

I am looking to print some data on screen in python, I use the formatting of strings so that they are presented in an orderly and rounded way, this data is printed based on a conditional.

I have created two variables: If a > b, rounded numbers should be printed like this:

01         -807.8
02        -6337.8
03        -6045.9
04       -15531.6
05       -26803.0
06       -40534.2
07        20364.4
08        12678.4

But if a < b, a text like this should be printed:

01       Does not apply
02       Does not apply
03       Does not apply
04       Does not apply
05       Does not apply
06       Does not apply
07       Does not apply
08       Does not apply
09       Does not apply
10       Does not apply

The problem is that: When executing the command if a> b the values are printed, but if a < b, I get an error: TypeError: type str doesn't define __round_ method.

Is there a way to correct that problem?

My code is as follows:

datos = [[1,1154,5412],[2,4527,5698],[3,2879,-5687],[4,5547,-5698],[5,7658,6589],
     [6,9651,-4565],[7,-4156,-6548],[8,-2264,6568],[9,-1657,6597],[10,-1643,5481]]

for i in range(len(datos)):

    a = 7
    b = 8

    if a < b:                
        Respuesta = 'Does not apply'                  
    elif a > b:            
        Respuesta = (0.7*datos[i][0]*datos[i][1])/(b-a)    

    print(f"{i+1:02} {round(Respuesta, 2):>20}")
2
  • What would round('Does not apply', 2) mean? Commented Apr 14, 2020 at 18:17
  • Round the value in the elif suite ... Respuesta = {round(Respuesta, 2) then it won't be in the print function. Commented Apr 14, 2020 at 18:19

2 Answers 2

1

Several ways, but this is probably the simplest:

    if a < b:                
        Respuesta = 'Does not apply'                  
    elif a > b:            
        Respuesta = round((0.7*datos[i][0]*datos[i][1])/(b-a), 2)

    print(f"{i+1:02} {Respuesta:>20}")
Sign up to request clarification or add additional context in comments.

Comments

0

if a < b your variable Respuesta will be this string 'Does not apply' which will be used with the round function that will raise your error because the round built-in function accepts only numbers as argument

you can use:

for i in range(len(datos)):

    a = 7
    b = 8

    if a < b:                
        print('Does not apply')
    elif a > b:            
        Respuesta = (0.7*datos[i][0]*datos[i][1])/(b-a)    

        print(f"{i+1:02} {round(Respuesta, 2):>20}")

since in your code, a is always < b (7<8) you can use the following one line:

print(*['Does not apply'] * len(datos), sep='\n')

1 Comment

Thank you very much for the feedback.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.