乘法的python错误

时间:2016-01-15 02:08:25

标签: python

我正在创建一个乘法程序,这里是乘法的代码:

 def multiply():
    print('enter two numbers in this format (x, y)')
    mult = input()
    multy = list(mult)
    answer = multy[1] * multy[2]
    print(answer)

这是我的错误:

`Traceback (most recent call last):
  File "C:/Python34/math clac.py", line 36, in <module>
    multiply()
  File "C:/Python34/math clac.py", line 17, in multiply
    answr = multy[1] * multy[2]
IndexError: list index out of range`

我做错了什么?

2 个答案:

答案 0 :(得分:0)

试试这个:

def multiply():
    print('enter two numbers in this format (x, y)')
    mult = input()
    multy = list(mult)
    answer = multy[0] * multy[1]
    print(answer)

指数为0和1,而不是1和2

答案 1 :(得分:0)

你也可以这样做

def multiply():
    print('enter two numbers in this format (x, y)')
    mult = input()
    multy = list(mult)

    #the second item in list will be space or either your delimeter
    #in python list index always start with 0, this follow the other programming language also
    answer = int(multy[0]) * int(multy[2])
    print(answer)


multiply()

输出

enter two numbers in this format (x, y)
1,2

2

enter two numbers in this format (x, y)
7,7

49