Update: Re did my code. Now **I am unable to find the answer to this issue no 1). ** Newbie here. I spent the whole night trying to figure this out but I feel stuck if anyone can kindly guide me. Below is the question and Code I did for python. Thanks in advance.
- Limit the input range from -70 to 80 for each input number
- Prevent dividing by zero (Do not use try-except)
- Instead of hard-coding values from -70 to 80, let the user enter the range
- check to make sure that the lower range in < the higher range
while True:
print("what do you want to do?")
print("1 Addition")
print("2 Subtraction")
print("3 Multiplication")
print("4 Division")
print("Enter Q to Quit.")
def addition(firstNumber,secondNumber):
result = firstNumber secondNumber
print("{0} {1} = {2}".format(firstNumber,secondNumber,result))
def subtraction(firstNumber,secondNumber):
result = firstNumber - secondNumber
print("{0} - {1} = {2}".format(firstNumber,secondNumber,result))
def multiplication(firstNumber,secondNumber):
result = firstNumber * secondNumber
print("{0} * {1} = {2}".format(firstNumber,secondNumber,result))
def divide(firstNumber,secondNumber):
if secondNumber == 0.0:
print("You no divide by Zero my friend")
else:
result = firstNumber / secondNumber
print("{0} / {1} = {2}".format(firstNumber,secondNumber,result))
choice = input("Enter your choice: ")
if choice == "q" or choice == "Q":
break
firstNumber = float(input("enter the firstNumber: "))
secondNumber = float(input("enter the secondNumber: "))
if firstNumber <= -70 or firstNumber >= 80:
print("invalid choice enter the input again")
firstNumber =float(input())
else :
print("\n")
if secondNumber <= -70 or secondNumber >= 80:
print("invalid choice enter the input again")
secondNumber =float(input())
else :
print("\n")
if choice == "1":
addition(firstNumber,secondNumber)
elif choice == "2":
subtraction(firstNumber,secondNumber)
elif choice == "3":
multiplication(firstNumber,secondNumber)
elif choice == "4":
divide(firstNumber,secondNumber)
else:
print("Invalid Choice")
CodePudding user response:
You have not specified or put any check on the input. You can do that as shown below
counter = 100
while counter:
counter -=1
if firstNumber <= -70 or firstNumber >= 80:
print("invalid choice enter the input again")
firsNumber =float(input())
else :
break
counter2 = 100
while counter2:
counter2 -=1
if secondNumber <= -70 or firstNumber >= 80:
print("invalid choice enter the input again")
secondNumber =float(input())
else :
break
You can reduce the counter value depending upon how many times a user is allowed to give correct input. If you would like to take input from user until they enter correct input put True in place of counter and counter2.
Both of these checks can be done in one loop also I did it this way assuming you would like to ask correct input from user as soon as they enter something invalid.
Hope this helps.