怎么使用python实现输入数字的连续加减方法

这篇文章将为大家详细讲解有关怎么使用python实现输入数字的连续加减方法,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

eval程序如下:

s=input("请输入要运算的数字")
print("The result is{}".format(eval(s)))

下面是不用eval实现加减的代码:主要思想就是通过一个标志位flag来计算是否进行加减,其他的都很好理解

s=input("请输入要运算的数字")
l=len(s)
h=0
i=0
flag=1
a=0
for i in range(0,l):
 if s[i]=='+' or s[i]=='-':
  flag=1
  c=s[i]
 else:
  flag=0
  a=a*10+round(int(s[i]))
 if flag==1 and s[i]=='+':
  h+=a
  a=0
 elif flag==1 and s[i]=='-':
  h-=a
  a=0
print(h)

现在贴上一直出错的代码,也算是长点经验,提醒自己下一次细心一点:

s=input("请输入要运算的数字")
l=len(s)
h=0
i=0
while i<=l:
 a=0
 c=s[i]
 i+=1
 while s[i]!='+' and s[i]!='-' and i<=l :
  a=a*10+round(int(s[i]))
  i+=1
 if c=='+':
  h+=a
 else:
  h-=a
print(h)
#错误类型:IndexError: string index out of range(字符串越界)

说明一下,越界有两个原因:

①能够访问的最大字符串是len(str)-1 (ps上图直接是len(str))

②python执行的方法是一句一句执行的,所以i<=l-1应该放在s[i] != '+'的前面

下面贴上修改过后能运行并且可以输出正确结果的代码:

s=input("请输入要运算的数字")
l=len(s)-1
h=0
i=0
while i<=l:
 a=0
 c=s[i]
 i+=1
 while i<=l and s[i]!='+' and s[i]!='-' :
  a=a*10+round(int(s[i]))
  i+=1
 if c=='+':
  h+=a
 else:
  h-=a
print(h)

关于“怎么使用python实现输入数字的连续加减方法”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。