查看: 1520|回复: 4

TypeError unsupported operand types - 'str' and 'int'

[复制链接]

4

主题

33

帖子

88

积分

注册会员

Rank: 2

积分
88
发表于 2018-9-19 17:13:01 | 显示全部楼层 |阅读模式


报错的下面代码
  1. def cat_n_times(s, n):
  2.     while s != 0:
  3.         print(n)
  4.         s = s - 1

  5. text = input("What would you like the computer to repeat back to you: ")
  6. num = input("How many times: ")

  7. cat_n_times(num, text)
复制代码

报错
TypeError unsupported operand types - 'str' and 'int'
有人知道吗
回复

使用道具 举报

15

主题

97

帖子

310

积分

论坛管理

Rank: 4

积分
310
发表于 2018-9-19 17:15:15 | 显示全部楼层
失败的原因是因为(Python 3)input返回一个字符串。要将其转换为整数,请使用int(some_string),你通常不会在Python中手动跟踪索引。实现这样一个功能的更好方法是
  1. def cat_n_times(s, n):
  2.       for i in range(n):
  3.            print(s)
  4. text = input("What would you like the computer to repeat back to you: ")
  5. num = int(input("How many times: ")) # Convert to an int immediately.

  6. cat_n_times(text, num)
复制代码

我稍微改变了你的API。在我看来n应该是次数,s应该是字符串。
回复

使用道具 举报

9

主题

74

帖子

185

积分

注册会员

Rank: 2

积分
185
发表于 2018-9-19 17:16:31 | 显示全部楼层
Python是强类型的。不像其他动态语言,它不会自动地投对象从一种类型或其他(比如从str到int),所以你必须自己做
回复

使用道具 举报

0

主题

32

帖子

80

积分

注册会员

Rank: 2

积分
80
发表于 2018-10-10 08:12:13 | 显示全部楼层
楼上说的有道理
回复

使用道具 举报

2

主题

54

帖子

122

积分

注册会员

Rank: 2

积分
122
发表于 2018-10-10 08:36:22 | 显示全部楼层
嗯嗯一楼正解
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表