我的代码如何只接受Python中的整数?

时间:2015-08-23 21:49:49

标签: python error-handling

我的代码区分输入是否有效。它不应该接受零或单词。如果用户插入零,它工作并说“除了零之外的任何东西”,“再试一次”但是当它再次询问时,它接受任何东西。在有有效输入之前,我该怎么做才能继续询问? 到目前为止,我得到了:

A = raw_input('Enter A: ')
try:
    A = float(A)
    if A == 0:
        print "anything but zero"
        A = raw_input("Try again")
except ValueError:
    print "HEY! that is not a float!"
    A = raw_input("Try again")

请帮忙!谢谢大家!

4 个答案:

答案 0 :(得分:1)

您需要使用循环:

protected void grdviewContractorTypes_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        try
        {
            if (e.CommandName == "edit")
            {
                byte ContractorTypeID = Convert.ToByte(grdviewContractorTypes.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);

                //HFActID.Value = ID.ToString();

                btnAddContractorType.Visible = false;
                btnUpdate.Visible = true;

                DataTable dt = MngContractorTypes.SelectContractorTypesByContractorTypeID(ContractorTypeID);
                DataRow r = dt.Rows[0];

                txtBoxContractorTypeName.Text = r["ContractorTypeName"].ToString();

                Response.Write("DONE");

            }
        }
        catch (Exception)
        {

        }
    }

答案 1 :(得分:1)

最简单的方法是使用while循环,如果强制转换成功且不等于0,则在try break中移动所有逻辑:

while True:
    try:
        A = float(raw_input('Enter A: '))
        if A != 0:
            break
        print "anything but zero"
    except ValueError:
        print "HEY! that is not a float!"

如果你实际上只想要整数,那么你应该转向int而不是float

答案 2 :(得分:0)

使用while循环:

valid = false
while not valid:
    A = raw_input('Enter A: ')
    try:
        A = float(A)
        if A == 0:
            print "anything but zero"
            A = raw_input("Try again")
        else: 
            valid = true
    except ValueError:
        print "HEY! that is not a float!"
        A = raw_input("Try again")

答案 3 :(得分:0)

希望这会有所帮助:)

while 1==1:
A = raw_input('Enter A: ')
try:
    A = float(A)
    if A == 0:
        print "anything but zero"
        A = raw_input("Try again")
    else:
        #valid input
        break
except ValueError:
    print "HEY! that is not a float!"