So here is my code for a very simple program:
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')
When ever the user inputs in the number 0
for int2
, I want the program to print that they can not do that.
Would really appreciate some help getting this program to not let them divide by zero and either ending the program, or taking them back to the start.
This should do as expected:
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')
You will notice a few subtle changes:
I moved the loop to outside the input. This way the program loops over and over asking for input.
I removed the check for valid. This program will loop forever, asking for new input if the user tries to enter a zero in the denominator (as asked).
I removed the quotes from '0'
. The code you had before was trying to see if the input was equal to the string
0, which is different than the int
0. This is a small difference (in terms of code) but a very important one in terms of function.
I removed the int2 != 0
condition, as it wasn't necessary. oper == '/'
and int2 == 0
was already caught, so if oper == '/'
, then int2
must not be zero.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments