我一直在尝试使用以下功能解决此问题。如果程序完成循环,我该怎么做才能存储所有数字输入值并仅在程序结束时打印它们。
def compare(a):
a=0
while True:
b=input("Enter an integer : ")
if b.isdigit():
k=n+1
a=a+int(b)
elif b.isalpha():
if b.upper()=="Q":
print("Digits\n",a,"\nTotal\n",a)
break
else:
print("Invalid Value. Enter again")
elif b.isalnum():
print("Value not recognized. Enter a valid value.")
else:
print("Unrecognized value is submitted. Enter again")
答案 0 :(得分:0)
根据问题更新代码
def compare(a):
a=0
all_digits = [] # Empty list
while True:
b=input("Enter an integer : ")
if b.isdigit():
all_inputs.append(b) # Append digit to list
k=n+1
a=a+int(b)
elif b.isalpha():
if b.upper()=="Q":
print("Digits\n",a,"\nTotal\n",a)
print("all digits: {}".format(all_digits))
break
else:
print("Invalid Value. Enter again")
elif b.isalnum():
print("Value not recognized. Enter a valid value.")
else:
print("Unrecognized value is submitted. Enter again")
但这可能是更好的代码:
def compare(): # no need to pass any argument
a = 0
all_digits = [] # Empty list
while True:
b = raw_input("Enter an integer: ")
if b.isdigit():
all_digits.append(b) # Append digit to list
a = a + int(b) # do not see 'k' being used anywhere
elif b.isalpha():
if b.upper() == "Q":
print("Digits: {}\nTotal: {}\nSum: {}".format(", ".join(all_digits), len(all_digits), a))
break
else:
print("Invalid Value. Enter again")
else: # no need of b.isalnum(). this will take care of both
print("Unrecognized value is submitted. Enter again")
<强>输出强>
Enter an integer: 1
Enter an integer: 2
Enter an integer: 3
Enter an integer: 4
Enter an integer: 5
Enter an integer: Q
Digits: 1, 2, 3, 4, 5
Total: 5
Sum: 15
答案 1 :(得分:0)
我假设您希望Total打印位数,而不是数字的总和。一个工作版本,其中包含与您的代码相比更改的注释:
def compare(): # input value is not used
a=[] # changed a to a list instead of integer
n=0 # hold the number of digits that were entered
while True:
b=input("Enter an integer : ")
if b.isdigit():
n+=1 # add 1 to the number of digits that were entered, variable k is not used
a.append(int(b)) #append the entered digit to list a
elif b.isalpha():
if b.upper()=="Q":
print("Digits\n",*a,"\nTotal\n",n) # use print(*a) to print the list of numbers
break
else:
print("Invalid Value. Enter again")
elif b.isalnum():
print("Value not recognized. Enter a valid value.")
else:
print("Unrecognized value is submitted. Enter again")