制作一个简单的python计算器

问题描述 投票:0回答:4

嗨所以基本上我被要求制作一个简单的计算器,它只包含一行并且只包含一个整数,符号和另一个符号。

它需要做这些功能: 加法、减法、乘法、除法和模

如果中间有任何空格,小数,单词/字母,它必须作为“无效输入”出现

即: 输入:5+5 输出:10

输入:十减五 输出:无效输入。

输入:4.5+2 输出:无效输入。

输入:5 + 5 输出:无效输入。

问题是,当我输入数学问题(即 5+5)时,什么也没有出来,就像空白一样。有谁知道如何解决这个问题?

这是我目前所拥有的:

o = "+","-","*","/","%"
x = input("Enter a math problem: ")

if " " in x:
  print("Invalid input")
  try: 
    num1,o,num2 = x.split()
  except ValueError: 
    print("Invalid Input")
    try: 
      num1 = int(num1)
      num2 = int(num2)
    except ValueError:
      print("Invalid Input")
    if o not in x:
      print("Invalid Input")

if o == "+":
  r = int(num1) + int(num2)
elif o == "-":
  r = int(num1) - int(num2)
elif o == "*":
  r = int(num1) * int(num2)
elif o == "/":
  r = int(num1) / int(num2)
elif o == "%":
  r = int(num1) % int(num2)
  print("Result is", r)
python calculator basic
4个回答
1
投票

没有什么是正确的

“结果是”行仅在 final if 为真时打印。你是想把它弄凹吗?

你的拆分不正确

看看这个:

num1,o,num2 = x.split()

你意识到你正在覆盖

o
的价值吗?

快速破解可能如下:

operators = ["+","-","*","/","%"]
x = input("Enter a math problem: ")

if " " in x:
  print("Invalid input")

for operator in operators:
     if operator in x:
        num1,num2 = x.replace(operator," ").split()
        break
     print("Invalid Input")
try: 
      num1 = int(num1)
      num2 = int(num2)
except ValueError:
      print("Invalid Input")

if o == "+":
    r = num1 + num2
elif o == "-":
    r = num1-num2
elif o == "*":
    r = num1*num2
elif o == "/":
    r = num1/num2
elif o == "%":
    r = num1%num2

print("Result is", r)

0
投票

你的尝试有很多问题,我已经在下面的代码中以注释的形式解释了这些问题:

o = "+","-","*","/","%"
# o is now defined as a tuple containing all the allowed operators

x = input("Enter a math problem: ")

if " " in x:
  print("Invalid input")
  # You print "Invalid input" but then you continue to do the next steps. 
  # There should be an else here like below:
# else:
  try: 
    num1,o,num2 = x.split()
    # split() splits on whitespace, which your input doesn't have
    # You also overwrite o
  except ValueError: # split doesn't throw a valueerror
    print("Invalid Input")

    # This try..except block needs to be un-indented out of the previous except
    try: 
      num1 = int(num1)
      num2 = int(num2)
    except ValueError:
      print("Invalid Input")

    # o HAS to be in x because you got it by splitting x (if the split() was correct)
    if o not in x:
      print("Invalid Input")

if o == "+":
  r = int(num1) + int(num2)
elif o == "-":
  r = int(num1) - int(num2)
elif o == "*":
  r = int(num1) * int(num2)
elif o == "/":
  r = int(num1) / int(num2)
elif o == "%":
  r = int(num1) % int(num2)
  # this print is in the elif o == '%' block, so something will only be printed when you try to do a mod operation
  print("Result is", r)

考虑这种方法:

  • 如果输入中有任何空格,我们打印
    "Invalid input"
    .
  • 我们遍历字符串寻找运算符。
  • 当我们找到一个运算符时,我们将其之前的部分指定为
    num1
    ,将其之后的部分指定为
    num2
  • 我们尝试将
    num1
    num2
    转换为整数。如果有小数或任何非数字,则会抛出错误。我们捕获此错误以打印
    "Invalid input"
  • 最后,如果我们还没有遇到错误,我们计算并打印结果

注意我使用描述性变量名,这使代码更具可读性。

operators = ("+", "-", "*", "/", "%")

user_input = input("Enter a math problem: ")

if " " in user_input:
    print("Invalid input")
else:
    op_index = -1
    for i, char in enumerate(user_input):
        if char in operators:
            op_index = i
            break # We found an operator, so we don't need to look further

    if op_index == -1:
        # op_index is still -1, so no operator was found
        print("Invalid input")
    else:
        try:
            num1 = int(user_input[:op_index]) # Slice the user input from the start until the character before the operator for num1
            num2 = int(user_input[op_index+1:]) # Slice the user input from the character after the operator until the end for num2
            op = user_input[op_index] # The operator is what we found at op_index
            if op == "+": 
                result = num1 + num2
            elif op == "-": 
                result = num1 - num2
            elif op == "*": 
                result = num1 * num2
            elif op == "/": 
                result = num1 / num2
            elif op == "%": 
                result = num1 % num2
            print(f"Result is {result}")
        except ValueError:
            print("Invalid input")

0
投票

我看到您在我测试您的程序并进行一些重构时收到了一些答案。除了之前的好答案,我还将提出以下重构代码以供考虑。

o = "+","-","*","/","%"

while True:                                                 # Provide a robust loop to allow entry of multiple calculations

    x = input("Enter a math problem or 'q' to quit: ")      # Will exit when the user enters "q"

    if x == 'q':
        break;

    if " " not in x:                                        # Utilize a space that will be used in the splitting of the operands and operation
        print("Invalid input - need a space")
        continue

    try: 
        num1,o,num2 = x.split(" ")                          # Split using the space as the separator
    except ValueError: 
       print("Invalid input on split")
       continue

    try:
        num1 = int(num1)
        num2 = int(num2)
    except ValueError:
        print("Invalid Input - operands need to be integers")
        continue

    if o not in x:
        print("Invalid Input - operator was not found")
        continue

    if o == "+":
        r = int(num1) + int(num2)
    elif o == "-":
        r = int(num1) - int(num2)
    elif o == "*":
        r = int(num1) * int(num2)
    elif o == "/":
        r = int(num1) / int(num2)
    else:
        r = int(num1) % int(num2)

    print("Result is", r)

这里是一些关键点。

  • 为了使程序更健壮,添加了一个“while”循环以允许用户评估多个方程式。
  • 如其他答案之一所述,此版本在操作数和运算符之间使用空格以使拆分功能按需要工作。
  • 并且,为了使程序更加用户友好,错误消息变得更加冗长,以便为用户提供更多关于他们的输入可能出现的问题的信息。

通过这些调整,以下是一些示例终端输出。

@Vera:~/Python_Programs/Calculator$ python3 Calc.py 
Enter a math problem or 'q' to quit: 4+5
Invalid input - need a space
Enter a math problem or 'q' to quit: 44.5 * 4
Invalid Input - operands need to be integers
Enter a math problem or 'q' to quit: 4 + 5
Result is 9
Enter a math problem or 'q' to quit: 211 / 4
Result is 52.75
Enter a math problem or 'q' to quit: 323 % 3
Result is 2
Enter a math problem or 'q' to quit: q

你可以试试这个版本和其他好的建议,看看它是否符合你项目的精神。


-2
投票

试试这个:

x = input("Enter a math problem: ")

try:
  num1,o,num2 = x.split(" ")
except: 
  print("Invalid Input")
  exit()
try:
  num1 = int(num1)
  num2 = int(num2)
except:
  print("Invalid Input")
  exit()
if o not in x:
  print("Invalid Input")
  exit()

if o == "+":
  r = int(num1) + int(num2)
elif o == "-":
  r = int(num1) - int(num2)
elif o == "*":
  r = int(num1) * int(num2)
elif o == "/":
  r = int(num1) / int(num2)
elif o == "%":
  r = int(num1) % int(num2)
print("Result is", r)

我做了一些小改动。

首先,你不需要从代码的开头定义

o
,所以我删除了第一行。

然后使用

num1
定义变量
o
num2
split()
,使用数字和它们之间的符号必须有分隔它们的东西(如空格或其他符号)。

所以如果你想这样,你必须在每个字符之间包含空格。喜欢

4 + 5
10 / 2
.

如果它必须在没有空格的情况下工作,你不能使用

split()
.

像这样:

x = input("Enter a math problem: ")

if " " in x:
  print("Invalid input")
  exit()
try:
  num1 = x[0]
  o = x[1]
  num2 = x[2]
except: 
  print("Invalid Input")
  exit()
try:
  num1 = int(num1)
  num2 = int(num2)
except:
  print("Invalid Input")
  exit()
if o not in x:
  print("Invalid Input")
  exit()

if o == "+":
  r = int(num1) + int(num2)
elif o == "-":
  r = int(num1) - int(num2)
elif o == "*":
  r = int(num1) * int(num2)
elif o == "/":
  r = int(num1) / int(num2)
elif o == "%":
  r = int(num1) % int(num2)
print("Result is", r)
© www.soinside.com 2019 - 2024. All rights reserved.