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

mnowg1ta  于 2023-11-20  发布在  Python
关注(0)|答案(2)|浏览(94)
import random as r

print(
"""
        Welcome to the Custom Counter!
    
    Type in your starting value and your
    ending value. Then, enter the amount
    by which to count.
""")

x = True

start = int(input("Starting number: "))
while x != False or start != "":
    fin = int(input("Ending number: "))
    amount = int(input("Count by: "))
    if amount > 0 or amount < 0:
        x = False
        
result = r.randrange(start, fin, amount)    
print(result)

input("Hit enter to exit.")

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

ymdaylpp

ymdaylpp1#

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

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

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

while x and start:

yeotifhr

yeotifhr2#

我的代码:

import random as r

print(
"""
        Welcome to the Custom Counter!
    
    Type in your starting value and your
    ending value. Then, enter the amount
    by which to count.
""")

while True:
    
    try:
        start = int(input("Starting number: "))
        fin = int(input("Ending number: "))
        amount = int(input("Count by: "))
    
    except ValueError as verr:
        
        print('error : ', verr,'\n restarting ....')
        
    else:
        
        break
        
   
result = r.randrange(start, fin, amount)    
print('result : ' ,result)

input("Hit enter to exit.")

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

相关问题