简体   繁体   English

我想对int()进行输入验证,但验证str()

[英]I want to do an input validation on an int(), but validate for str()

I want the code to "break" when the user's input is <=0 AND when the input = "stop". 当用户的输入<= 0且输入=“停止”时,我希望代码“中断”。 This is what I have so far. 这就是我到目前为止所拥有的。

while True:

    try:
        x = input("how many times do you want to flip the coin?: ")
        if int(x) <= 0 or x.lower() == "stop": 
            break
        x = int(x)
        coinFlip(x)


     except ValueError:
        print ()
        print ("Please read the instructions carefully and try one more time! :)")
        print ()

I get the error: 我收到错误:

    if int(x) <= 0 or str(x).lower() == "stop":
ValueError: invalid literal for int() with base 10: 'stop'

you get the exception because the first condition that's evaluated is int(x) <= 0 and x is not really an integer at this point. 你得到异常是因为第一个被评估的条件是int(x) <= 0而x此时并不是真正的整数。

you can change the order of the the conditions: 你可以改变条件的顺序:

if x.lower() == 'stop' or int(x) <=0

this way you check for 'stop' first, and don't evaluated int(x) (because the the or condition already evaluates to True ). 这样你首先检查'stop' ,并且不评估int(x) (因为or条件已经计算为True )。 any string that is not an integer and not 'stop' would cause the ValueError exception which you're already handling. 任何非整数而不是'stop'字符串都会导致您正在处理的ValueError异常。

You get a ValueError because you can't convert the string 'stop' to an integer. 您得到一个ValueError因为您无法将字符串'stop'转换为整数。

One way to solve this would be to use a helper method that correctly catches the ValueError and then checks if the string is stop : 解决此问题的一种方法是使用正确捕获ValueError的辅助方法,然后检查字符串是否stop

def should_stop(value):
    try:
        return int(value) <= 0
    except ValueError:
        return value.lower() == "stop"

while True:
    x = input("how many times do you want to flip the coin?: ")
    if should_stop(x): 
        break

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

相关问题 列表索引必须是int,而不是str。 但我希望他们成为 - list indices must be int, not str. But I want them to be str 如何连接“str”和“int”对象? - How do I concatenate 'str' and 'int' objects? 我想将DataFrame的值从str更改为int - I want to change DataFrame's value from str into int 测试用户输入是int还是str,然后如果输入是str则失败。 我不断输入未定义的str - Testing if user input is an int or a str, then failing if input is a str. I keep getting strs I enter as undefined 我在使用 input、int 和 str 提问时遇到问题 - I have a problem with asking questions using input, int and str 我如何摆脱这个错误:max() 收到了一个无效的参数组合 - 得到了 (str, int),但需要以下之一:*(张量输入) - How do I get rid of this error: max() received an invalid combination of arguments - got (str, int), but expected one of: * (Tensor input) 获取用户输入为int或str - Get user input as int or str 问:如何将str + int连接到=现有变量 - Q: How do I concatenate str + int to = an existing variable 如何解决 TypeError: &#39;int&#39; 和 &#39;str&#39; 实例之间不支持的 &#39;&lt;&#39;? - How do I resolve TypeError: '<' not supported between instances of 'int' and 'str'? 如何将具有词组的str列表转换为int列表? - How do I convert a str list that has phrases to a int list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM