首页 > 解决方案 > 乘法和除法破坏了我的代码

问题描述

当我做加法和减法时,我的计算器可以工作,当我除法和乘法时,它会完全中断。对代码的评论更深入

我试过编辑列表中的数字/变量,但如果我修复乘法和除法,它会破坏加法和减法。

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 这是正确的

标签: python

解决方案


这段代码有几个错误:

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一条语句将两个替代分支重新组合在一起:无论第一个是真还是假,第二都会运行ifif


推荐阅读