如何在函数中编写条件以进行注释“请提供两个整数或浮点数”
现在我有一个ValueError,例如“无法转换字符串或浮点数”
def divede():
num1 = float(input("Enter first number:"))
num2 = float(input("Enter second number:"))
return num1, num2
num1, num2 = divede()
while True:
if num2 == []:
print("Please provide two integers or floats")
elif num2 != 0:
print(f"{num1} / {num2} is {num1/num2}")
break
else:
print("Please do not divede by zero")
num1, num2 = divede()
def divede():
num1 = float(input("Enter first number:"))
num2 = float(input("Enter second number:"))
return num1, num2
num1, num2 = divede()
while True:
if num2 == []:
print("Please provide two integers or floats")
elif num2 != 0:
print(f"{num1} / {num2} is {num1/num2}")
break
else:
print("Please do not divede by zero")
num1, num2 = divede()
这里我有一个问题:
while True:
if num2 == []: # wrong condition
print("Please provide two integers or floats")
谢谢所有答案
最佳答案
当您尝试将字符串输入转换为float时,出现以下错误之一:
num1 = float(input("Enter first number:"))
num2 = float(input("Enter second number:"))
我建议您将潜水功能更改为以下内容:
def divede():
while True:
try:
num1 = float(input("Enter first number:"))
num2 = float(input("Enter second number:"))
return num1, num2
except(ValueError):
print("Please provide two integers or floats")
while循环可确保要求用户重复输入,直到他实际提供两个数字为止。
其中的except(ValueError)仅捕获所需的特定错误。
然后,您还需要像下面这样更改脚本的其余部分:
while True:
if num2 != 0:
print(f"{num1} / {num2} is {num1 / num2}")
break
else:
print("Please do not divede by zero")
num1, num2 = divede()
关于python - 如何在函数中编写条件以发表此注释Python,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58743341/