How exactly do you divide two variables?

Asked

Viewed 957 times

1

In the code below I try to divide the values, but I end up getting a completely wrong answer from the calculation:

nota1 = input ("Digite a nota 1: ")
nota12 = input ("Digite a nota 1: ")

nota2 = input ("Digite a nota 2: ")
nota22 = input ("Digite a nota 2: ")
media1 = (float(nota1 + nota12)/2)
media2 = (float(nota2 + nota22)/2)

print(media1)
print(media2)

The result I get is this:

Imagem

How do I get the calculation out correctly (5+10/2 = 7.5 and 7+7/2=7)?

1 answer

6


You need to convert already in data acquisition. What your code is doing is adding two strings and then convert to float. The problem is that adding up string is a concatenation, so when you type 5 and 10, you’re getting 510.

Simply can do so:

nota1 = float(input("Digite a nota 1: "))
nota12 = float(input("Digite a nota 1: "))

nota2 = float(input("Digite a nota 2: "))
nota22 = float(input("Digite a nota 2: "))
media1 = ((nota1 + nota12) / 2)
media2 = ((nota2 + nota22) / 2)

print(media1)
print(media2)

Behold working in the ideone. And also in the repl it.. Also put on the Github for future reference.

But note that this code is not handling possible typos. The most correct is to capture the exception you can generate or verify that what was typed is ok.

Browser other questions tagged

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