python - 乘法和除法破坏了我的代码
问题描述
当我做加法和减法时,我的计算器可以工作,当我除法和乘法时,它会完全中断。对代码的评论更深入
我试过编辑列表中的数字/变量,但如果我修复乘法和除法,它会破坏加法和减法。
s=input('What would you like to calculate? ')
index = s.find("-") #goes through the equation to find it, and numbers it
if index == -1:
index = s.find('+')
elif index == -1:
index=s.find('*')
elif index == -1:
index = s.find('/')
if index == -1:
index = s.find('+')
op = s[index] # defines index as op
lp = len(s) #defines the length of it as lp
p1 = s[0:index] #set variable for beginning through the operator
sign = s[index] #this defines the sign
p2=s[index+1:lp]#this goes from the number past the sign to the end
print(p1) #these three are just to visualize
print(sign) #each individual part of the equation
print(p2) #for + and - it shows each part correctly, for * or / doesn't
if sign == '+': #this is all the code that does the math
ans = int(p1)+int(p2) #variable that is defined as the answer
elif sign == '-':
ans = (int(p1)-int(p2))
elif sign == '*':
ans = (int(p1)*int(p2))
elif sign == '/':
ans = (int(p1)/int(p2))
else:
print ('I do not understand')
print (p1,sign,p2,'=',ans) #for the user, visualizes equation
当我输入 2/2 时,我应该得到 1,但我得到了一个错误代码。当我将打印语句放在单独的变量前面时,我应该得到 2 / 2 但相反我得到类似: 2/ 2 2/2 当我去加法时,我得到 10 + 10 这是正确的
解决方案
这段代码有几个错误:
index = s.find("-")
if index == -1:
index = s.find('+')
elif index == -1:
index=s.find('*')
elif index == -1:
index = s.find('/')
if index == -1:
index = s.find('+')
首先,if
最底部的语句是重复的,因此请立即删除。
接下来,考虑一下该elif
语句的作用。它是else if 的简写形式,意思是这样的代码:
if index == -1:
elif index == -1:
elif index == -1:
是自动错误的。“如果索引是-1,否则如果索引是-1,否则如果索引是-1”。
该控制流不允许在if
和之间执行任何其他语句elif
。执行语句的唯一方法是当其中一个条件匹配时,这意味着对elif/else
备选方案的评估由于匹配而停止。
我怀疑您有底部块 ( if ... s.find('+')
) 并且您插入了其他代码以尝试添加额外的操作。实际上,您之前使用的是简单的 if 语句。只需为其他情况复制它们:
index = s.find('-')
if index == -1:
index = s.find('+')
# Note: no ELSE here, just another 'if'
if index == -1:
index = s.find('*')
if index == -1:
index = s.find('/')
if index == -1:
print("Ack! No operator found")
这里的区别在于每个语句都在控制流中if
创建一个分支。但是下if
一条语句将两个替代分支重新组合在一起:无论第一个是真还是假,第二个都会运行if
。if
推荐阅读
- java - 如何使用扫描仪将项目添加到数组列表
- objective-c - 通过同名字符串名称检索 NSString 的值
- python - pygame中的悬停效果
- qbasic - 使用 DO UNTIL LOOP 打印数组中的最小数字
- java - 单击按钮时,如何在文本区域的文本字段中显示文本?
- c++ - 如何将 shmat 与非 NULL 页面对齐的 shmaddr 一起使用?
- php - 为什么“PHP flush()”在 IOS 中不起作用?
- laravel - 我的搜索中只有字符的搜索栏
- openrefine - 在 OpenRefine 中,如何使用正则表达式查找/替换首字母?
- android - 在 ActionBar Kotlin 上实现下一个按钮