繁体   English   中英

如何不让用户除以 0?

[英]How to not let the user divide by 0?

所以这是我的一个非常简单的程序的代码:

import math

valid = True
oper = input('Please input your operation(+, -, *, /): ')
int1 = int(input('Please enter your first number: '))
int2 = int(input('Please enter your second number: '))


while(valid == True):
    if(oper == '/' and int2 == '0'):
        print('Error! Cannot divide by zero!')
        valid = False
    elif(oper == '/' and int2 != '0'):
        print(int1 / int2)
    elif(oper == '+'):
        print(int1 + int2)
    elif(oper == '-'):
        print(int1-int2)
    elif(oper == '*'):
        print(int1 * int2)


    else:
        print('Invalid Operation')

当用户为int2输入数字0 ,我希望程序打印他们不能这样做。

真的很感谢一些帮助让这个程序不让它们除以零并结束程序或将它们带回开始。

这应该按预期进行:

import math

while(True):
  oper = input('Please input your operation(+, -, *, /): ')
  int1 = int(input('Please enter your first number: '))
  int2 = int(input('Please enter your second number: '))

  if(oper == '/' and int2 == 0):
      print('Error! Cannot divide by zero!')
  elif(oper == '/'):
      print(int1 / int2)
  elif(oper == '+'):
      print(int1 + int2)
  elif(oper == '-'):
      print(int1-int2)
  elif(oper == '*'):
      print(int1 * int2)
  else:
      print('Invalid Operation')

您会注意到一些细微的变化:

  • 我将循环移到输入之外。 这样程序就会一遍又一遍地循环询问输入。

  • 我删除了检查有效。 该程序将永远循环,如果用户试图在分母中输入零(如询问),则要求新的输入。

  • 我从'0'删除了引号。 您之前的代码试图查看输入是否等于string 0,这与int 0 不同。这是一个很小的差异(在代码方面),但在功能方面非常重要。

  • 我删除了int2 != 0条件,因为它不是必需的。 oper == '/'int2 == 0已经被捕获,所以如果oper == '/' ,那么int2不能为零。

我可能会添加函数来确保你得到整数。

您还可以使用字典来获取正确的数学函数。 我重写了这段代码,我们可以根据问题的输入传递有效的运算符。 我想你会喜欢这样的:

完整脚本:

import math
import operator

op_map = {
          "+":operator.add,
          "-":operator.sub,
          "*":operator.mul,
          "/":operator.truediv #div in python2
         }

# Define a function that returns an int
def return_int(s):
    i = input('Please enter your {} number: '.format(s))
    try:
        return int(i)
    except ValueError:
        print("Not valid. Try again:")

# Define a function that returns a valid operator
def return_operator(valid_ops):
    q = 'Please input your operation({}): '.format(', '.join(valid_ops))
    i = input(q)
    while i not in valid_ops:
        i = input("Error. "+q)
    return op_map[i]

# Create a while loop (infinite) and run program
while True:
    valid_ops = list("+-*/")
    int1 = return_int("first")
    int2 = return_int("second")
    if int2 == 0: 
        valid_ops.remove("/") # remove devision for 0
    op = return_operator(valid_ops) # return the operator function
    r = op(int1,int2) # calculates the result
    print("Result: {}".format(r))

基本上,如果用户输入 0 作为 int2,您将无法再进行除法操作。 我们可以重写代码以使其相反。 首先输入第一个数字,然后是运算符,如果运算符是 /,则 0 不再是有效数字。 例如。

这是使用运算符库的更简洁版本:

import operator

operations = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.div}

oper = input('Please input your operation(+, -, *, /): ')
int1 = int(input('Please enter your first number: '))
int2 = int(input('Please enter your second number: '))

if oper not in operations:
    print("Inavlid operator")
    exit(1)
try:
    print(operations[oper](int1, int2))
except ZeroDivisionError:
    print("Divide by zero")

如果您希望它重复,您可以将其环绕在一个 while 循环中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM