What is the input(). split(" ") for in python?

Asked

Viewed 162 times

0

I’m solving some exercises in python and when I put the code this way:

A = float(input(""))
B = float(input(""))
C = float(input(""))

triangulo = float((A*C)/2)
circulo = float(3.14159*(C**2))
trapezio = float(((A + B)*C)/2)
quadrado = float(B*B)
retangulo = float(A*B)

print("TRIANGULO: %0.3f" %triangulo)
print("CIRCULO: %0.3f" %circulo)
print("TRAPEZIO: %0.3f" %trapezio)
print("QUADRADO: %0.3f" %quadrado)
print("RETANGULO: %0.3f" %retangulo) 

Gives an error where it says it cannot convert string to float, right on the first line (A = float(input(""))). But seeing the answer, I realized that a correct way to do it would be:

valor = input().split(" ")
a, b, c = valor
pi = 3.14159
triangulo = (float(a) * float(c))/2
circulo = pi * (float(c)* float(c))
trapezio = float(c) *(float(a) + float(b)) / 2
quadrado = float(b) * float(b)
retangulo = float(a) * float(b)
print("TRIANGULO: %0.3f\nCIRCULO: %0.3f\nTRAPEZIO: %0.3f\nQUADRADO: %0.3f\nRETANGULO: %0.3f" % (triangulo, circulo, trapezio, quadrado, retangulo))

and wanted to understand the reason and meaning of valor = input().split(" ") in that code.

  • 1

    In the statement of the year it says that the entries will be informed in the same row, at once?

  • Say yes, that’s the purpose of the split?

  • 5

    Yes. When receiving on the same line you will receive the string "1 2 3" (example) when using input(). Since there are multiple values, you divide the string into whitespace, split(' '), to get a list ['1', '2', '3'] and so I was able to convert to float.

  • nossaa, thank you so much!!!!

  • And instead of every time convert to float, vc can do this only once at the beginning, like this: https://ideone.com/yYx8B5

No answers

Browser other questions tagged

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