How to transform a String list into a Float list?

0

If I run this code, it will give a list in string:


SothatIcannotdotheaverageofthenumberscorrectly(sinceitisinstring).WhatcanIdotogetthenumberprintedinfloat/int?

Doesthis"error" happen only with Python.3x? What would happen if I migrated to 2x? Would it print in float?

   vet_aluno = [0]*2
for i in range(2):
    vet_aluno[i] = input ("Digite o nome do(a) aluno(a): ")

vet_nota1 = [0]*2
for k in range(2):
    vet_nota1[k] = input("Digite a nota de " + str(vet_aluno[0]) + ": ")


vet_nota2 = [0]*2
for a in range(2):
    vet_nota2[a] = input("Digite a nota de " + str(vet_aluno[1]) + ": ")

#Calculando a média
media1 = media(vet_nota1[0],vet_nota1[1])
media2 = media(vet_nota2[0],vet_nota2[1])
    
asked by anonymous 23.02.2017 / 04:47

1 answer

1

In Python3, when you use the input function to prompt for user input, it always returns a string. If you want you can turn the string into float, as follows:

vet_nota1 = [0]*2
for k in range(2):
    vet_nota1[k] = float( input("Digite a nota de " + str(vet_aluno[0]) + ": "))

vet_nota2 = [0]*2
for a in range(2):
    vet_nota2[a] = float( input("Digite a nota de " + str(vet_aluno[1]) + ": "))

However, by doing just that, you are relying on the user to always type a string that can be made into a float. If the user types anything else, such as 'Test', when prompted for the note, there will be an exception of type ValueError and your program will be terminated.

In Python2, there are 2 functions to request input from the user: input and raw_input.

Raw_input functions as the Python3 input, only returns the string that was entered. The input tries to interpret what the user typed as an expression in Python. So, if he typed something in the form of a float, it would already return the input as a float, not as a string.

In Python2, you could have written the following program:

vet_aluno = [0]*2
for i in range(2):
    vet_aluno[i] = raw_input("Digite o nome do(a) aluno(a) {}: ".format(i))

vet_nota1 = [0]*2
for k in range(2):
    vet_nota1[k] = input("Digite a nota de " + str(vet_aluno[0]) + ": ")

vet_nota2 = [0]*2
for a in range(2):
    vet_nota2[a] = input("Digite a nota de " + str(vet_aluno[1]) + ": ")
    
23.02.2017 / 05:03