是否可以将数字值分配给列表的字母元素,然后使用sum()函数添加?

时间:2019-05-27 14:52:56

标签: python-3.x list

我正在尝试以下问题,但不知道怎么了。有人可以帮我吗?

java=10
python=10
sql=5
unix=5
javascript=5
framework=10
i=eval(input("Enter courses done in a list"))
if sum(i)>=30:
    print("eligible since the score is", sum(i))
else:
    print("Not eligible since the score is",sum(i))

但是我遇到以下错误,

Traceback (most recent call last):
  File "E:/Python Notes/Python Programs/Eligible for placement.py", line 8, in <module>
    if sum(i)>=30:
TypeError: unsupported operand type(s) for +: 'int' and 'str'

提前谢谢!

3 个答案:

答案 0 :(得分:2)

我们假设用户输入的是一串用空格分隔的课程名称,然后:

courses = {"java":10,
           "python":10,
           "sql":5,
           "unix":5,
           "javascript":5,
           "framework":10}
user_input = input("Enter courses done in a list")
course_names = user_input.split()
i = sum([courses.get(course,0) for course in course_names])
if i >= 30:
    print("eligible since the score is", i)
else:
    print("Not eligible since the score is",i)

答案 1 :(得分:1)

您可以尝试将字符串设置为变量名

java=10
python=10
sql=5
unix=5
javascript=5
framework=10
i=input("Enter courses done in a list:").split() # ['python', 'java', 'sql']
sum_ = 0

for item in i:
    sum_ += int(vars()[item]) # "use string like a variable"

if sum_>=30:
    print("eligible since the score is ", sum_)
else:
    print("Not eligible since the score is ",sum_)

输出:

Enter courses done in a list:python java sql
Not eligible since the score is  25

答案 2 :(得分:0)

我忍无可忍地说你永远不应该只是eval()原始用户输入。看来您是在自己的提示下手动输入了字符串或存储了字符串的变量,因为错误消息说,在if sum(i)>=30:运算符的第8行(+)上,不能同时使用字符串和整数。例如,sum('foo', 1)给出相同的错误。

签出https://stackoverflow.com/help/minimal-reproducible-example。对于OP和响应者都一样。