[英]How to fix this: ValueError: invalid literal for int() with base 10:
student_heights = input("Input a list of student heights ").split()
for n in range(0, len(student_heights)):
student_heights[n] = int(student_heights[n])
total_height =0
for i in student_heights:
total_height += i
print(total_height)
for n in range(0, len(student_heights)):
if student_heights[n].isalpha():
print("Enter only num's list, not letters")
exit(1)
student_heights[n] = int(student_heights[n])
Add if student_heights[n].isalpha()
if is any letter in list of students height.添加if student_heights[n].isalpha()
if 是学生身高列表中的任何字母。
( isalpha()
is checking if are in your list/text are letters, if it is, it return True , if not False ) ( isalpha()
正在检查您的列表/文本中是否是字母,如果是,则返回True ,如果不是False )
exit()
, if True it will exit. exit()
,如果为True它将退出。
the default behaviour of split()
is to split by whitespace. split()
的默认行为是按空格分割。 You code would not throw errors if the input only contained numbers and whitespaces, eg 156 178 165 171 187
.如果输入仅包含数字和空格,您的代码不会抛出错误,例如156 178 165 171 187
。
If you want a different split seperator, eg the comma ,
, you could use split(",")
instead.如果你想要一个不同的分割分隔符,例如逗号,
你可以使用split(",")
代替。
Valid input would be eg 156,178,165,171,187
.有效输入将是例如156,178,165,171,187
。
Note that [156,178,165,171,187]
is not valid input.请注意, [156,178,165,171,187]
不是有效输入。 It would split the string only at the comma, resulting in the first element to be equal to [156
, clearly not a valid number.它只会在逗号处拆分字符串,导致第一个元素等于[156
,显然不是有效数字。
If you want to skip the input step and use a list instead, replace:如果您想跳过输入步骤并改用列表,请替换:
student_heights = input("Input a list of student heights ").split()
with:和:
student_heights = [156,178,165,171,187]
If you realy need to pass [156,178,165,171,187]
as an input, you could also use literal_eval
to convert it to a list.如果您确实需要传递[156,178,165,171,187]
作为输入,您还可以使用literal_eval
将其转换为列表。 Don't forget to import
the required module:不要忘记import
所需的模块:
from ast import literal_eval
student_heights = literal_eval(input("Input a list of student heights "))
for n in range(0, len(student_heights)):
student_heights[n] = int(student_heights[n])
total_height =0
for i in student_heights:
total_height += i
print(total_height)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.