I'm new to python and I'm looking to code a small calculator for divisions, that includes while loops and if conditionals
My code looks like this:
a = input('first number')
while type(a)!=int:
try:
a=int(a)
print('imput number is correct ',a)
except:
print('Imput data is not correct ')
a=input('first number')
b = input('second number')
while type(b)!=int and b!=0:
try:
b=int(b)
print('Imput data is correct',b)
except:
print(' imput data is not a number, please only imput numbers ')
b=input('second number')
while b==0:
try:
c=1/b
print('imput number is correct ',b)
except ZeroDivisionError:
print('Cant divide by 0')
b=input('second number again')
if type(a)==int and type(b)==int and b!=0:
c=a/b
print('the result is: ',c)
The program suddenly ends after you imput 0 a second time in the second number space, but the proccess should keep asking for a value that is a number and different from 0
CodePudding user response:
After b=input('second number again')
is executed, b
is a string, so b == 0
is False
(a string is never equal to an integer).
CodePudding user response:
You'll find this easier if you write a common function to get the user input. Something like this:
def get_input(prompt, nonZero=False):
while True:
try:
if (n := int(input(prompt))) == 0 and nonZero:
raise ValueError('Value must be non-zero')
return n
except ValueError as e:
print(e)
a = get_input('Input first number: ')
b = get_input('Input second number: ', True)
print(a/b)