如何不让用户除以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 不再是有效数字。例如.
这是使用 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 循环包围它。
所以这是我的一个非常简单的程序的代码:
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 不再是有效数字。例如.
这是使用 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 循环包围它。