简体   繁体   English

简单的python代码错误

[英]Simple python code error

 error: Can't convert int to str implicitely

Code:代码:

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))

MY TASK IS TO: Ask for the user's name to be entered.我的任务是:要求输入用户名。 It should be stored in a suitable variable (like user_name ) Ask for how many numbers are going to be entered.它应该存储在一个合适的变量中(比如user_name )询问将要输入多少个数字。 Store this in a suitable variable too.也将其存储在合适的变量中。 (like “ num_values ”) Then get each of the numbers entered. (如“ num_values ”)然后获取输入的每个数字。 You will need to have some way of keeping a total of all of the numbers and at the end, once all numbers have been entered, you need to print out something like..您将需要某种方式来保留所有数字的总数,最后,一旦输入了所有数字,您需要打印出类似..

The issue is in lines -问题在于——

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

You have to convert total_numbers to int to use in range function.您必须将total_numbers转换为int才能在range函数中使用。 Like -喜欢 -

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

Also, I see that you are adding numbers to total_numbers inside the loop itself, maybe you instead want to create a new variable , initilize with 0 and add to it instead, Increasing total_numbers itself would give you unexpected results.另外,我看到您在循环内部向total_numbers添加数字,也许您想要创建一个新变量,用 0 初始化并添加到它,增加total_numbers本身会给您带来意想不到的结果。

Code would be -代码将是 -

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM