在while循环中提示用户输入直到正确的问题
if num < 0:
input('Only nonnegative intergervalues allowed, try again: ')
elif num == 0:
print('The factorial of 0 = 1')
while num > 1:
factor = factor * num
num = num -1
else:
num = int(input('Only nonnegative intergervalues allowed, try again: '))
这是我现在的情况。我只想在程序中使用while循环。它会在用户输入负数时提示用户两次,然后循环结束。我希望这个循环能一直提示用户,直到输入正确为止。我不太确定错误出在哪里。我需要一个嵌套的while循环吗,还是问题出在else语句上?
我在原来的循环下面尝试了另一个while循环,但不确定我是否做对了。此外,我还尝试了调整一些东西。
2 个回答
在编程中,有时候我们会遇到一些问题,比如代码运行不正常或者出现错误。这些问题可能是因为我们写的代码有bug,或者是因为我们没有正确理解某些概念。
如果你在编写代码时遇到困难,不妨先仔细检查一下你的代码,看看有没有拼写错误或者逻辑上的问题。很多时候,问题可能就隐藏在这些小细节里。
另外,了解一些基本的编程概念也很重要,比如变量、循环和条件判断等。这些都是编程的基础,掌握了它们,你就能更轻松地解决问题。
如果你还是无法找到问题所在,可以考虑向其他人请教,或者在网上寻找相关的解决方案。编程是一个不断学习和实践的过程,遇到问题是很正常的,重要的是要保持耐心和好奇心。
# The external loop if input is invalid
i = 0
while i < 5:
# If it is 5th attempt, error message
if i == 4:
print('Sorry, The maximum number of attempts exceeded')
#Upto 5 times of invalid input, takes another input
num = int(input())
#If the input is valid
if num > 0:
r = 1
while num >= 1:
r = r * num
num = num - 1
print(r)
break
else :
print('The number can not be zero or negative')
i += 1
问题的一部分在于你对while
循环中else
的理解。这个else
只会执行一次,因为while
循环在没有break
的情况下会退出。我想你可能期待的是在else
块之后,while
的条件会再次被检查。但实际上并不是这样,你应该在while
循环中使用if
语句。
你可能想要的代码大概是这样的:
# since Python does not have a repeat .. until loop, while True with a break works
while True:
num = int(input('Enter a non-negative integer value: '))
if num < 0:
input('Only non-negative integer values allowed, try again: ')
else:
break
factorial = 1
x = num # save num to print later, work with x to compute factorial
while x > 0:
factorial = factorial * x
x = x - 1
print(f'The factorial of {num} is: {factorial}')
在while
循环中使用else
是有用的,特别是当你需要在循环完成且没有中断时执行某些操作。例如:
total = 0
while total <= 10:
s = input(f'Total is {total}, add how much? ("x" to stop): ')
if s == 'x':
break
total = total + int(s)
else:
print(f'You reached a total over 10 of {total}')
关于你的代码,有几点需要注意:
- 第一部分将文本输入读入
num
,但没有对它做任何处理。你可能漏掉了一些代码,因为在if
语句之前num
并没有被定义。 - 第二部分假设
num
是一个int
类型的值,因为它是和这个类型进行比较的,但在那个时候,num
的值实际上是str
类型的。 - 如果
num
是一个正整数,while
的else
部分会总是执行,但这并不是你想要的行为——不过如果num
是负数,它就永远不会被执行,因为while
的else
并不是为了这个目的。
个人来说,我不喜欢Python中在for
和while
中重复使用else
这个关键词。用after
这样的词会更合适。但编程语言通常喜欢保持关键词的数量尽量少,所以这里重复使用了else
,这导致了你所遇到的困惑——这在学习语言时是很正常的。