Python TypeError: must be str, not int

2019-08-14 08:54发布

问题:

I'm using Python 3.6.2 on Windows 64-bit, I have an error: A TypeError....

   A = 0
   ns = input('Input start:')
   nf = input('Input finish:')
   steps = input('Input steps:')
   for i in range(steps + 1):
       d_n = (nf-ns)/steps
       n = ns + i * d_n
       f_n = n*n
       A = A + f_n * d_n

   next


   print('Area is: ', A)

And here's the error....

    Traceback (most recent call last):
      File "C:/Users/UNO/Documents/Python 3.6/Curve_Area2.py", line 5, in 
    <module>
        for i in range(steps + 1):
    TypeError: must be str, not int 

And I want this result....

Input start:3
Input finish:5
Input steps:100000
Area is:  32.66700666679996 

I don't know how to fix this... Please help!!!!

回答1:

Here what you are looking for :

A = 0
ns = int(input('Input start:'))
nf = int(input('Input finish:'))
steps = int(input('Input steps:'))
start=[]
finish=[]

for i in range(steps + 1):
    d_n = (nf - ns) / steps

    n = ns + i * d_n
    f_n = n * n
    A = A + f_n * d_n




print('Area is : {} \n Start at {} \n Finish at {} \n steps {}'.format(A,ns,nf,steps))

Input:

Input start:3
Input finish:5
Input steps:1000

output:

Area is : 32.70066799999998 
 Start at 3 
 Finish at 5 
 steps 1000


回答2:

Edit: Sorry. Use int(input()) to fix the issue. The input function gives str.

ns = str(input('Input start:')


回答3:

The input function returns string in python 3. Therefore you need to convert the values of ns, nf and steps into integers.
Change these lines

ns = input('Input start:')
nf = input('Input finish:')
steps = input('Input steps:')

to

ns = int(input('Input start:'))
nf = int(input('Input finish:'))
steps = int(input('Input steps:'))