简体   繁体   中英

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.

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

  • I removed the int2 != 0 condition, as it wasn't necessary. oper == '/' and int2 == 0 was already caught, so if oper == '/' , then int2 must not be zero.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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