简体   繁体   English

如何正确地创建一个条件,一旦条件满足就会退出 while 循环?

[英]How do I properly make a condition that will exit a while loop once a condition has been met?

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.")

I made the while loop in hopes to exit the program when you clicked enter.我制作了 while 循环,希望在您单击 enter 时退出程序。 Unfortunately, this will not let me exit the while loop no matter what I do.不幸的是,无论我做什么,这都不会让我退出 while 循环。 I am a noob at python. What is wrong with my condition?我是python的菜鸟。我的情况有什么问题吗?

Thank you!谢谢!

Welcome to stackoverflow and welcome to Python!欢迎使用 stackoverflow,欢迎使用 Python!

Try to use and instead of or .尝试使用and而不是or

In your line:在你的行中:

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

You say to python, you want to run until 1st or 2nd condition is true.你对 python 说,你想运行直到第一个或第二个条件为真。 Since the 2nd condition stays always true, while will run forever.由于第二个条件始终为真,while 将永远运行。

Even more simple:更简单:

while x and start:

Hope you will enjoy Python as I do!希望您和我一样喜欢 Python!

my code:我的代码:

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.")

this one I believe takes into account inputting of non int s and restart program from scratch when encountering such kind of inputs.我相信这个考虑到了非int的输入,并在遇到此类输入时从头开始重新启动程序。

See The try statement specifies exception handlers and/or cleanup code for a group of statements请参阅try 语句为一组语句指定异常处理程序和/或清理代码

PS your code doesnt handle invalid values (ie fin < start ) PS 你的代码不处理无效值(即fin < start

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM