简单的python代码错误

时间:2015-06-20 04:01:19

标签: python

 error: Can't convert int to str implicitely

代码:

user_name = input("What is your name? ")
print("Hello {}!, this program is going to ask you to type in a series of numbers (all positive integers)" .format(user_name))

total_numbers = input("How many numbers would you like to add")

for i in range(1, total_numbers):
  number = float(input("State a numbers {}: " .format(i)))
  total_numbers += number

  print("Total number: {}" .format(total_numbers))

我的任务是:要求输入用户名。它应存储在合适的变量中(如user_name) 询问将输入多少个数字。将其存储在合适的变量中。 (比如“num_values”) 然后输入每个数字。 您需要有一些方法来保存所有数字的总和,最后,一旦输入所有数字,您需要打印出类似的东西..

1 个答案:

答案 0 :(得分:0)

问题在于行 -

total_numbers = input("How many numbers would you like to add")
for i in range(1, total_numbers):
    number = float(input("State a numbers {}: " .format(i)))
    total_numbers += number

您必须将total_numbers转换为int才能在range函数中使用。喜欢 -

total_numbers = int(input("How many numbers would you like to add"))
for i in range(1, total_numbers):
    number = float(input("State a numbers {}: " .format(i)))
    total_numbers += number

另外,我看到你在循环内部向total_numbers添加数字,也许你想要创建一个新变量,使用0初始化并添加到它,增加total_numbers本身就会给你意想不到的结果。

代码将是 -

total_numbers = int(input("How many numbers would you like to add"))
total = 0.0
for i in range(1, total_numbers):
    number = float(input("State a numbers {}: " .format(i)))
    total += number
print("Total number: {}" .format(total))