编写一个python程序,要求用户输入一个6位数的整数,并检查输入是否为回文。如果用户未能输入整数或整数小于6位数,则必须要求用户再次输入。(注意:应该在不使用TRY和EXCEPT的情况下编写代码,并且不允许用户进行超过3次的尝试。(
我对此的看法是:
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")
使用此代码,如果我输入一个六位数,那么我必须输入三次,而不是一次。以下是输出
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'>
有没有更好的方法可以在不使用TRY和EXCEPT的情况下做到这一点?
而不是"对于";循环,你可以只使用一个计数器和";而";循环类似于下面的代码片段。
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")
通过测试,以下输出显示在我的终端上。
@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
我将把它留给你来构建测试,看看输入的数字是否是回文。
试试看。
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))
# Palindrome testing would start here
print("Going to see if this is a palindrome")
n=int(i)
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")
break
else:
tries += 1
if tries >= 3:
break
if tries >= 3:
print("Sorry - too many tries to enter a six digit integer")