TypeError: unsupported operand type(s) for -: 'str' and 'int'

前端 未结 2 1084
死守一世寂寞
死守一世寂寞 2020-11-22 13:30

New to python and programing how come I\'m getting this error?

def cat_n_times(s, n):
    while s != 0:
        print(n)
        s = s - 1

text = input(\"Wh         


        
相关标签:
2条回答
  • 2020-11-22 13:58
    1. The reason this is failing is because (Python 3) input returns a string. To convert it to an integer, use int(some_string).

    2. You do not typically keep track of indices manually in Python. A better way to implement such a function would be

      def cat_n_times(s, n):
          for i in range(n):
              print(s) 
      
      text = input("What would you like the computer to repeat back to you: ")
      num = int(input("How many times: ")) # Convert to an int immediately.
      
      cat_n_times(text, num)
      
    3. I changed your API above a bit. It seems to me that n should be the number of times and s should be the string.

    0 讨论(0)
  • 2020-11-22 14:09

    For future reference Python is strongly typed. Unlike other dynamic languages, it will not automagically cast objects from one type or the other (say from str to int) so you must do this yourself. You'll like that in the long-run, trust me!

    0 讨论(0)
提交回复
热议问题