Write a python program to ask a user to input a 6-digit integer and check if the input is a palindrome or not. If the user fails to enter an integer or if the integer is less than 6-digit, the user must be asked to input it again. (NOTE: The code should be written without using TRY and EXCEPT and the user should not be allowed to take more than 3 attempts.)
My take on this is:
for n in range(3):
while True:
i = input("Please enter a six digit integer:")
if i.isnumeric():
if len(i)==6:
i_integer = int(i)
print("Your number is:",i_integer,"and the data type is:",type(i_integer))
break
else:
print("Enter value is not numeric")
With this code, if I enter a six-digit number, then I have to enter it for 3 times, instead of one time. Below is the output.
Please enter a six digit integer:123456
Your number is: 123456 and the data type is: <class 'int'>
Please enter a six digit integer:123456
Your number is: 123456 and the data type is: <class 'int'>
Please enter a six digit integer:123456
Your number is: 123456 and the data type is: <class 'int'>
Is there any better way to do this without using TRY and EXCEPT?
CodePudding user response:
Instead of a "for" loop, you could just use a counter and "while" loop like the following code snippet.
tries = 0
while True:
i = input("Please enter a six digit integer:")
if i.isnumeric() and len(i) == 6:
i_integer = int(i)
print("Your number is:",i_integer,"and the data type is:",type(i_integer))
break
else:
tries = 1
if tries >= 3:
break
if tries >= 3:
print("Sorry - too many tries to enter a six digit integer")
quit()
# Palindrome testing would start here
print("Going to see if this is a palindrome")
Testing this out, the following output was displayed on my terminal.
@Una:~/Python_Programs/Palindrome$ python3 Numeric.py
Please enter a six digit integer:12345
Please enter a six digit integer:123456
Your number is: 123456 and the data type is: <class 'int'>
Going to see if this is a palindrome
I will leave it to you to build the test to see whether or not the entered number is a palindrome.
Give that a try.