Samuel Oranyeli - 1 year ago 121
Python Question

# while loop to calculate the maximum of two numbers

i just started learning python; i am totally new to programming. kindly look at this post and tell me if my variable declaration at the outset is wrong, and what better way(s) i can write the code. maximum of two numbers using the if else statement. python. thanks.

``````#determine the maximum of two numbers
A = 2
B=1
print 'Exit program by entering 0 for the first integer.'
while A != B:
A = int(input('Enter an integer: '))
if A == 0:
break
B = int(input('Enter a second integer: '))
if A > B:
print 'The maximum number is {0}'.format(A)
if B > A:
print 'The maximum number is ' + str(B)

print('Done')
``````

Can u help me fix it into a loop? @maze88 and other gurus pls.

``````while True:
try:
A=int(input('Enter a number:'))
except ValueError:
print('Not an integer! Try again.')
else:
break

while True:
try:
B=int(input('Enter a second number:'))
except ValueError:
print('Not an integer! Try again.')
else:
break

if A>B:
print(A)
elif B>A:
print(B)
else:
print('Equal numbers')

print('Done')
``````

Is your code Python 2? If it is, I recommend using Python 3.5.2 instead as it is newer and not many people use Python 2 anymore.

But anyway, the first improvement you could make is using the elif statements, instead of just using 3 if statements. You could also make the formatting a little better to make it easier to read for other programmers.

Like this:

``````#determine the maximum of two numbers
A = 2
B = 1

print 'Exit program by entering 0 for the first integer.'

while A != B:
A = int(input('Enter an integer: '))
B = int(input('Enter a second integer: '))

if A == 0:
break

elif A > B:
print 'The maximum number is {0}'.format(A)

elif B > A:
print 'The maximum number is ' + str(B)

print 'Done'
``````

Elif statements would be better for this case because in the second if statement

``````if A > B:
``````

If A is bigger than B, the next 2 elif statements would be ignored, but in your code, Python checks the if statements even if A is bigger than B.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download