python类计算器开发,Python创建计算器

I am fairly new to python.

I have been asked to create a calculator using only string commands, conversions between int/string/float etc.(if needed), and using functions is a requirement. while and for loops can also be used.

The program needs to take an input of the form x/y or x/y/z, where x y z are any positive or negative number. Where "/" can be replaced by addition multiplication and subtraction as well. And where any number of white spaces can exist between operands and operators. This is an idea of what I have so far.

I would have a unique definition for +,-,/, and *. I would create a function for what the user inputs. I would use ".lstrip" and ".rstrip" to get rid of white spaces.

Now what I am having trouble with is creating the input function. I am very new to functions and this is basically what I have. I know it isn't much to work with but I am really stuck on how to properly enter the function.

def multiplication(x,a,y,b,z):

if (a== "*"):

return x*y

if (b== "*"):

return y*z

def division(x,a,y,b,z):

if (a== "/"):

return x/y

if (b== "/"):

return y/z

def addition(x,a,y,b,z):

if (a== "+"):

return x+y

if (b== "+"):

return y+z

def subtraction(x,a,y,b,z):

if (a== "-"):

return x-y

if (b== "-"):

return y-z

def (x,y,z):

x=0

y=0

z=0

zxc=int(input()):# this is where I get stuck and I don't know how to implement x,y,z into the input.

All help is appreciated. If you are unsure of whether the code you provide is too intense for my needs, please ask before wasting your time for me, making code that I can't possibly use. I promise to reply ASAP.

Basically I am trying to find a way to split the inputted string AND THEN start calculations with it.

解决方案

Here is a possible solution outline using regular expressions. Error checking left as exercise. If this isn't homework and you'd like to see the fleshed-out solution, view it here

import re

# input is a list of tokens (token is a number or operator)

tokens = raw_input()

# remove whitespace

tokens = re.sub('\s+', '', tokens)

# split by addition/subtraction operators

tokens = re.split('(-|\+)', tokens)

# takes in a string of numbers, *s, and /s. returns the result

def solve_term(tokens):

tokens = re.split('(/|\*)', tokens)

ret = float(tokens[0])

for op, num in :

#

return ret

# initialize final result to the first term's value

result = solve_term(tokens[0])

# calculate the final result by adding/subtracting terms

for op, num in :

result += solve_term(num) * (1 if op == '+' else -1)

print result

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值