如何不让用户除以0?

时间:2017-10-24 00:35:23

标签: python divide

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

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

当用户输入0的数字int2时,我希望打印的程序无法执行此操作。

非常感谢一些帮助让这个程序不要让它们除以零并且要么结束程序,要么让它们回到起点。

3 个答案:

答案 0 :(得分:1)

这应该按预期进行:

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不得为零。

答案 1 :(得分:0)

我可能会添加函数以确保获得整数。

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

完整脚本:

pry(main) foo = Customer.first
pry(main)> bar = foo.statements.where(some_param: 42)
pry(main)> bar.destroy_all
   (0.2ms)  BEGIN
  SQL (0.6ms)  DELETE FROM `notices` WHERE `notices`.`id` = 4639
   (0.5ms)  COMMIT
   (0.2ms)  BEGIN
  SQL (0.5ms)  DELETE FROM `notices` WHERE `notices`.`id` = 4640
   (0.4ms)  COMMIT
   (0.1ms)  BEGIN
  SQL (0.5ms)  DELETE FROM `notices` WHERE `notices`.`id` = 4641
   (0.5ms)  COMMIT
  . . . etc etc etc . . .

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

答案 2 :(得分:0)

这是使用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")

如果您想重复播放,可以在while循环中将其包围。