简体   繁体   English

如何使try函数仅打印我的消息一次

[英]How to make the try function only print my message once

I've tried using the try() function, but when i try: and then type print() it just prints the message non-stop. 我已经尝试过使用try()函数,但是当我尝试:然后键入print()时,它只是不停地打印消息。 how do i make it only print once? 我如何使其仅打印一次?

def inputInt(minv, maxv, message):
    res = int(input(message))
    while (res > minv) and (res < maxv):
        try:
            print("Good job.")
        except:
            print("Invalid input")

Have you tried with break ? 您尝试过break吗?

Take a look at this and this to get more clarification, but if you want that at the one time the try jumps to the except, it should print it once only, break is the thing. 看看这个这个 ,以获得更多的澄清,但如果你想,在一个时间尝试跳转到不同的,它应该打印出来只有一次, break是事情。

I must say this loop will go on forever as you are not changing res . 我必须说这个循环将永远持续下去,因为您没有更改res Even if it goes in the try or in the except . 即使在try还是在except

The code that could raise an exception should be in the try . 可能引发异常的代码应该在try The input should be inside the while . 输入应在while Catch expected exceptions in case an unexpected exception occurs. 如果发生意外异常,请捕获预期的异常。 A naked except is bad practice and can hide errors. except是不好的做法,可以掩盖错误。

Here's a suggested implementation: 这是一个建议的实现:

def inputInt(minv, maxv, message):
    while True: # Loop until break
        try:
            res = int(input(message)) # Could raise ValueError if input is not an integer.
            if minv <= res <= maxv:   # if res is valid,
                break                 #    exit while loop
        except ValueError:            # Ignore ValueError exceptions
            pass
        print("Invalid input")        # if didn't break, input or res was invalid.
    return res                        # Once while exits, res is good

x = inputInt(5,10,"enter number between 5 and 10: ")

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

相关问题 如何确保我只打印一次? - How to make sure I only print once? 如何使我的for循环仅打印一次,而不是为每个i值打印一次 - how to make my for loop print only once instead of for each value of i 如何使嵌套的循环打印仅在python中一次 - how to make nested for loop print only once in python 如何使打印语句在Python 3中仅闪烁一次? - How to make a print statement to blink only once in Python 3? 一旦我的 scrapy 爬取了所有预期页面,如何打印消息? - How can I print a message once my scrapy has crawled all the intended pages? 我的代码为每一行打印“未找到”,如果搜索不成功,我如何让它只打印一次“未找到”? - My code prints “Not Found” for every line, how do i get it to only print “Not Found” once if the search is unsuccessful? 即使多个用户在 python 中访问我的网络应用程序,有没有办法确保函数只运行一次? - Is there a way to make sure a function runs only once even if multiple user access my web app in python? 仅当使用 print 调用时,我才能将函数打印到 shell 中吗? - Can I make a function print into shell only if called with print? 如何使 if 语句只工作一次 - How to make an if statement works only once 如何仅打印列表中的唯一项目,这些项目只发生一次? - How to print only the unique items in a list, those occurring once?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM