How to write a condition in a function to make this comment "Please provide two integers or floats" Now I have a ValueError like " could not convert string or float "
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()
here I have a problem:
while True:
if num2 == []: # wrong condition
print("Please provide two integers or floats")
Thx for all answers
The error you get arises as soon as you try to convert your string input to float in one of the following lines:
num1 = float(input("Enter first number:"))
num2 = float(input("Enter second number:"))
I would suggest you change your divede function to the following:
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")
The while loop makes sure that the user is asked for repeating input until he actually provides two numbers. The except(ValueError) is there to catch only the specific errors you want. Then you also need to change the rest of the script like so:
while True:
if num2 != 0:
print(f"{num1} / {num2} is {num1 / num2}")
break
else:
print("Please do not divede by zero")
num1, num2 = divede()