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
Change your division function to this:
def divede():
num1 = input("Enter first number:")
num2 = input("Enter second number:")
try:
num1, num2 = float(num1), float(num2)
except ValueError:
print("Invalid entry, please enter numbers")
return divede()
return num1, num2
In that case you do not need the first if
in your while
loop.
My code is too complicate:) correct answer is:
def divide(a,b):
try:
total = a / b
except TypeError:
return "Please provide two integers or floats"
except ZeroDivisionError:
return "Please do not divide by zero"
return total
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()
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.