gpt4 book ai didi

python - 如何不让用户除以0?

转载 作者:太空宇宙 更新时间:2023-11-03 14:36:29 25 4
gpt4 key购买 nike

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

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

关于python - 如何不让用户除以0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46900466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com