How to convert a string variable to int?

6

As I correctly declare an integer value, it is returning that my variables are strings .

n1 = input("informe um número ")
n2 = input("informe um número ")

soma = n1 + n2
print ("O resultado da soma de ", soma)
  

report a number 25
  report a number 25
  2525

     

> > >

    
asked by anonymous 17.09.2015 / 22:52

3 answers

8

As mentioned in the other answers, the return of the input() function is type string , the same is true for raw_input() function in Python 2.x .

numero1 = int(input("Informe um numero: "))
numero2 = int(input("Informe um numero: "))

Also consider handling possible exceptions that might occur, for example exception ValueError that is thrown when a function receives an argument that has the right type but an invalid value.

See:

try:
    numero1 = int(input("Informe um numero: "))
    numero2 = int(input("Informe um numero: "))

    soma = numero1 + numero2
    print ("{0} + {1} = {2}".format(numero1, numero2, soma))

except ValueError:
    print("Somente numeros sao aceitos. Tente novamente.")

View demonstração

    
17.09.2015 / 23:32
5

You have to convert the string , which is the return of the function input , to a number:

n1 = input ("informe um número ")
n2 = input ("informe um número ")
soma = int(n1) + int(n2)
print ("O resultado da soma de", soma)

See running on ideone .

Function documentation .

    
17.09.2015 / 22:54
5

The input recognizes the values in the form of a string. then you should do the following:

soma = int(n1) + int(n2)

int (), makes the values numbers

    
17.09.2015 / 22:54