循环直到非字母数字输入

时间:2018-02-04 15:15:04

标签: python loops

我希望这段代码循环,直到用户输入一些输入(检查空字符串)并打印else语句,如果不匹配python中的任何条件

任何人都可以帮我搞清楚吗?

这是我的代码:

public interface Action {
    void execute();
}

public class ActionImpl implements Action {

    @Override
    public void execute() {
        System.out.println("execute with ActionImpl");
    }

}

public static void main(String[] args) {
    Action action = new Action() {
        @Override
        public void execute() {
            System.out.println("execute with anonymous class");
        }
    };
    action.execute();

    //or

    Action actionImpl = new ActionImpl();
    actionImpl.execute();
}

2 个答案:

答案 0 :(得分:0)

如果您想重复循环,则需要continuebreak当你希望它结束​​时。

另外,我建议您先进行输入验证

while True:    
    string_1 = input("enter a  word or number: ")

    if not (string_1.isalpha() or string_1.isdigit()):
        print(string_1 , "is not alpha nor digit")
        break

    if string_1.isalpha():
        print(string_1 ,"is all alphabetical character")
        continue

    if string_1.isdigit():
        if int(string_1) < min_value:
            print(string_1 , "is less than expected")
            continue
        elif int(string_1) > min_value:
            print(string_1 , "is a preety big number") 
            continue
        else:  # == min_value
            print("you got it")

如果您需要处理负数,请参阅

How do I check if a string is a negative number before passing it through int()?

答案 1 :(得分:-1)

您需要从breakif条件中删除elif语句。
else条件中添加break语句。
< BR />

while True:    
string_1 = input("enter a  word or number: ")

if string_1.isalpha():
        print(string_1 ,"is all alphabetical character")


elif  int(string_1.isdigit()):
    if int(string_1) < min_value:
        print(string_1 , "is less than expected")


    if int(string_1) > min_value:
        print(string_1 , "is a preety big number") 


else:
    print(string_1 , "is not alpha nor digit" , "\n")
    break

Click here了解break语句。