python-3.x 我如何正确地创建一个条件,一旦条件满足,就会退出while循环?

mnowg1ta  于 2023-11-20  发布在  Python
关注(0)|答案(2)|浏览(95)
  1. import random as r
  2. print(
  3. """
  4. Welcome to the Custom Counter!
  5. Type in your starting value and your
  6. ending value. Then, enter the amount
  7. by which to count.
  8. """)
  9. x = True
  10. start = int(input("Starting number: "))
  11. while x != False or start != "":
  12. fin = int(input("Ending number: "))
  13. amount = int(input("Count by: "))
  14. if amount > 0 or amount < 0:
  15. x = False
  16. result = r.randrange(start, fin, amount)
  17. print(result)
  18. input("Hit enter to exit.")

字符串
我创建了while循环,希望在你点击回车时退出程序。不幸的是,无论我做什么,这都不会让我退出while循环。我的条件有什么问题吗?

ymdaylpp

ymdaylpp1#

使用and代替or
在您的行业中:

  1. while x != False or start != "":

字符串
你对python说,你想运行直到第一个或第二个条件为真。因为第二个条件总是为真,while将永远运行。
更简单:

  1. while x and start:

yeotifhr

yeotifhr2#

我的代码:

  1. import random as r
  2. print(
  3. """
  4. Welcome to the Custom Counter!
  5. Type in your starting value and your
  6. ending value. Then, enter the amount
  7. by which to count.
  8. """)
  9. while True:
  10. try:
  11. start = int(input("Starting number: "))
  12. fin = int(input("Ending number: "))
  13. amount = int(input("Count by: "))
  14. except ValueError as verr:
  15. print('error : ', verr,'\n restarting ....')
  16. else:
  17. break
  18. result = r.randrange(start, fin, amount)
  19. print('result : ' ,result)
  20. input("Hit enter to exit.")

字符串
这一个我相信考虑到输入非int s和从头开始程序时,遇到这样的输入。
请参见try语句为一组语句指定异常处理程序和/或清理代码
PS你的代码不处理无效值(即fin < start

展开查看全部

相关问题