【问题标题】:How do I count the number of occurrences of the invalid input when the user enter the wrong input?当用户输入错误的输入时,如何计算无效输入的出现次数?
【发布时间】:2021-12-08 17:52:37
【问题描述】:
我想数一下“无效输入”这个词出现了多少次。
这是我的代码。请帮助我。
while True:
number = input("Enter a number: ")
if number.isdigit():
print("The input is valid.")
else:
print("Invalid input.")
continue
【问题讨论】:
标签:
python
for-loop
input
while-loop
printing
【解决方案1】:
只需添加一个计数器变量。
i = 0
while True:
number = input("Enter a number: ")
if number.isdigit():
print("The input is valid.")
else:
print("Invalid input.")
i = i + 1 # Increment the counter variable
【解决方案2】:
为其分配一个计数器
count = 0
while True:
number = input("Enter a. number: ")
if number.isdigit():
print("The input is valid.")
else:
print("Invalid input.")
count += 1
continue
print('Invalid responses count: {}'.format(count))