How to divide two variables properly?

2

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:

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

    
asked by anonymous 22.02.2017 / 23:01

1 answer

4

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

You can simply do this:

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)

See running on ideone . Also put it on GitHub for future reference .

But note that this code is not treating typos. The most correct is to catch the exception that can generate or check if what was typed is ok.

    
22.02.2017 / 23:24