Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python乘法错误_Python - Fatal编程技术网

python乘法错误

python乘法错误,python,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/

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

 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`
`回溯(最近一次呼叫最后一次):
文件“C:/Python34/math clac.py”,第36行,在
乘
文件“C:/Python34/math clac.py”,第17行,乘法
answr=multy[1]*multy[2]
索引器:列表索引超出范围`
我做错了什么?

试试这个:

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,您也可以这样做

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

python中的列表基于
0
。如果输入两个元素,列表中的元素位于索引
multy[0]
multy[1]
,而不是
multy[1]
multy[2]
。当您尝试访问
multy[2]
python时,它会告诉您:列表索引超出范围。噢,对了,我的大脑放屁,很抱歉,谢谢您的时间!