简体   繁体   English

如何不让用户除以 0?

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

So here is my code for a very simple program:所以这是我的一个非常简单的程序的代码:

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')

When ever the user inputs in the number 0 for int2 , I want the program to print that they can not do that.当用户为int2输入数字0 ,我希望程序打印他们不能这样做。

Would really appreciate some help getting this program to not let them divide by zero and either ending the program, or taking them back to the start.真的很感谢一些帮助让这个程序不让它们除以零并结束程序或将它们带回开始。

This should do as expected:这应该按预期进行:

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')

You will notice a few subtle changes:您会注意到一些细微的变化:

  • I moved the loop to outside the input.我将循环移到输入之外。 This way the program loops over and over asking for input.这样程序就会一遍又一遍地循环询问输入。

  • I removed the check for valid.我删除了检查有效。 This program will loop forever, asking for new input if the user tries to enter a zero in the denominator (as asked).该程序将永远循环,如果用户试图在分母中输入零(如询问),则要求新的输入。

  • I removed the quotes from '0' .我从'0'删除了引号。 The code you had before was trying to see if the input was equal to the string 0, which is different than the int 0. This is a small difference (in terms of code) but a very important one in terms of function.您之前的代码试图查看输入是否等于string 0,这与int 0 不同。这是一个很小的差异(在代码方面),但在功能方面非常重要。

  • I removed the int2 != 0 condition, as it wasn't necessary.我删除了int2 != 0条件,因为它不是必需的。 oper == '/' and int2 == 0 was already caught, so if oper == '/' , then int2 must not be zero. oper == '/'int2 == 0已经被捕获,所以如果oper == '/' ,那么int2不能为零。

I would probably add functions to make sure you get integers.我可能会添加函数来确保你得到整数。

You can also use a dictionary to get the right math functions.您还可以使用字典来获取正确的数学函数。 I rewrote this code and we could pass valid operators based on input to the question.我重写了这段代码,我们可以根据问题的输入传递有效的运算符。 I think you'd like something like this:我想你会喜欢这样的:

Full script:完整脚本:

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))

Basically if the user inputs a 0 as int2 you don't have the option to do the division anymore.基本上,如果用户输入 0 作为 int2,您将无法再进行除法操作。 We could rewrite the code to make it the other way around.我们可以重写代码以使其相反。 First you input the first number, then the operator and if operator is /, 0 is not a valid number anymore.首先输入第一个数字,然后是运算符,如果运算符是 /,则 0 不再是有效数字。 For instance.例如。

Here's a more concise version using the operator library :这是使用运算符库的更简洁版本:

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")

You can surround it in a while loop if you want it to repeat.如果您希望它重复,您可以将其环绕在一个 while 循环中。

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

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