How to validate array for negative # and alpha input in Python












0















I'm trying to validate an array of user inputs (pints of blood collected per hour over 7 hours) for negative numbers, spaces, and/or letters. Currently, with an if statement checking user input is below 0, the program receives type error: "'<' not supported between instances of 'list' and 'int'."



inputPints = 
totalPints = 0
hours = ["#1", "#2", "#3", "#4", "#5", "#6", "#7"]

def userInput():
for hour in hours:
inputPints.append(int(input("Enter pints collected for hour {}: ".format(hour))))
if inputPints<0:
inputPints.append(int(input("Please enter a whole number {}: ".format(hour))))
userInput()

def userOutput():
print("")
print("Average number of pints donated is: ", "{:.2f}".format(import_functions.averagePints(totalPints, 7)))
print("Most pints donated is: ", import_functions.maxPints())
print("Least pints donated is: ", import_functions.minPints())
print("")
userOutput()









share|improve this question























  • Are you looking for if len(inputPints) < 0? Because you're comparing a list with the integer 0.. Just as the error says. Or are you looking for if len(inputPints[-1]) < 0 if the last input is length below zero?

    – Torxed
    Nov 22 '18 at 21:58













  • Why do you perform the check after having appended the input already? How do you want to recover from the erroneous value? How do you want to deal with repeated incorrect input?

    – MisterMiyagi
    Nov 22 '18 at 22:03











  • Great questions. I honestly couldn't tell you as I'm new to Python as of about 6 weeks ago. I've tried the length function and it returns no errors, but it doesn't show the user they are inputting an invalid integer.

    – Kyle Barnes
    Nov 22 '18 at 22:16
















0















I'm trying to validate an array of user inputs (pints of blood collected per hour over 7 hours) for negative numbers, spaces, and/or letters. Currently, with an if statement checking user input is below 0, the program receives type error: "'<' not supported between instances of 'list' and 'int'."



inputPints = 
totalPints = 0
hours = ["#1", "#2", "#3", "#4", "#5", "#6", "#7"]

def userInput():
for hour in hours:
inputPints.append(int(input("Enter pints collected for hour {}: ".format(hour))))
if inputPints<0:
inputPints.append(int(input("Please enter a whole number {}: ".format(hour))))
userInput()

def userOutput():
print("")
print("Average number of pints donated is: ", "{:.2f}".format(import_functions.averagePints(totalPints, 7)))
print("Most pints donated is: ", import_functions.maxPints())
print("Least pints donated is: ", import_functions.minPints())
print("")
userOutput()









share|improve this question























  • Are you looking for if len(inputPints) < 0? Because you're comparing a list with the integer 0.. Just as the error says. Or are you looking for if len(inputPints[-1]) < 0 if the last input is length below zero?

    – Torxed
    Nov 22 '18 at 21:58













  • Why do you perform the check after having appended the input already? How do you want to recover from the erroneous value? How do you want to deal with repeated incorrect input?

    – MisterMiyagi
    Nov 22 '18 at 22:03











  • Great questions. I honestly couldn't tell you as I'm new to Python as of about 6 weeks ago. I've tried the length function and it returns no errors, but it doesn't show the user they are inputting an invalid integer.

    – Kyle Barnes
    Nov 22 '18 at 22:16














0












0








0








I'm trying to validate an array of user inputs (pints of blood collected per hour over 7 hours) for negative numbers, spaces, and/or letters. Currently, with an if statement checking user input is below 0, the program receives type error: "'<' not supported between instances of 'list' and 'int'."



inputPints = 
totalPints = 0
hours = ["#1", "#2", "#3", "#4", "#5", "#6", "#7"]

def userInput():
for hour in hours:
inputPints.append(int(input("Enter pints collected for hour {}: ".format(hour))))
if inputPints<0:
inputPints.append(int(input("Please enter a whole number {}: ".format(hour))))
userInput()

def userOutput():
print("")
print("Average number of pints donated is: ", "{:.2f}".format(import_functions.averagePints(totalPints, 7)))
print("Most pints donated is: ", import_functions.maxPints())
print("Least pints donated is: ", import_functions.minPints())
print("")
userOutput()









share|improve this question














I'm trying to validate an array of user inputs (pints of blood collected per hour over 7 hours) for negative numbers, spaces, and/or letters. Currently, with an if statement checking user input is below 0, the program receives type error: "'<' not supported between instances of 'list' and 'int'."



inputPints = 
totalPints = 0
hours = ["#1", "#2", "#3", "#4", "#5", "#6", "#7"]

def userInput():
for hour in hours:
inputPints.append(int(input("Enter pints collected for hour {}: ".format(hour))))
if inputPints<0:
inputPints.append(int(input("Please enter a whole number {}: ".format(hour))))
userInput()

def userOutput():
print("")
print("Average number of pints donated is: ", "{:.2f}".format(import_functions.averagePints(totalPints, 7)))
print("Most pints donated is: ", import_functions.maxPints())
print("Least pints donated is: ", import_functions.minPints())
print("")
userOutput()






python validation






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 22 '18 at 21:57









Kyle BarnesKyle Barnes

94




94













  • Are you looking for if len(inputPints) < 0? Because you're comparing a list with the integer 0.. Just as the error says. Or are you looking for if len(inputPints[-1]) < 0 if the last input is length below zero?

    – Torxed
    Nov 22 '18 at 21:58













  • Why do you perform the check after having appended the input already? How do you want to recover from the erroneous value? How do you want to deal with repeated incorrect input?

    – MisterMiyagi
    Nov 22 '18 at 22:03











  • Great questions. I honestly couldn't tell you as I'm new to Python as of about 6 weeks ago. I've tried the length function and it returns no errors, but it doesn't show the user they are inputting an invalid integer.

    – Kyle Barnes
    Nov 22 '18 at 22:16



















  • Are you looking for if len(inputPints) < 0? Because you're comparing a list with the integer 0.. Just as the error says. Or are you looking for if len(inputPints[-1]) < 0 if the last input is length below zero?

    – Torxed
    Nov 22 '18 at 21:58













  • Why do you perform the check after having appended the input already? How do you want to recover from the erroneous value? How do you want to deal with repeated incorrect input?

    – MisterMiyagi
    Nov 22 '18 at 22:03











  • Great questions. I honestly couldn't tell you as I'm new to Python as of about 6 weeks ago. I've tried the length function and it returns no errors, but it doesn't show the user they are inputting an invalid integer.

    – Kyle Barnes
    Nov 22 '18 at 22:16

















Are you looking for if len(inputPints) < 0? Because you're comparing a list with the integer 0.. Just as the error says. Or are you looking for if len(inputPints[-1]) < 0 if the last input is length below zero?

– Torxed
Nov 22 '18 at 21:58







Are you looking for if len(inputPints) < 0? Because you're comparing a list with the integer 0.. Just as the error says. Or are you looking for if len(inputPints[-1]) < 0 if the last input is length below zero?

– Torxed
Nov 22 '18 at 21:58















Why do you perform the check after having appended the input already? How do you want to recover from the erroneous value? How do you want to deal with repeated incorrect input?

– MisterMiyagi
Nov 22 '18 at 22:03





Why do you perform the check after having appended the input already? How do you want to recover from the erroneous value? How do you want to deal with repeated incorrect input?

– MisterMiyagi
Nov 22 '18 at 22:03













Great questions. I honestly couldn't tell you as I'm new to Python as of about 6 weeks ago. I've tried the length function and it returns no errors, but it doesn't show the user they are inputting an invalid integer.

– Kyle Barnes
Nov 22 '18 at 22:16





Great questions. I honestly couldn't tell you as I'm new to Python as of about 6 weeks ago. I've tried the length function and it returns no errors, but it doesn't show the user they are inputting an invalid integer.

– Kyle Barnes
Nov 22 '18 at 22:16












3 Answers
3






active

oldest

votes


















0














I think you should define your userInput() method like this …



def userInput():
for hour in hours:
user_input = -1
while user_input < 0:
try:
user_input = int(input("Enter pints collected for hour {}: ".format(hour)))
except:
user_input = -1
if user_input > -1:
inputPints.append(user_input)





share|improve this answer































    0














    You can use regex to validade your input.
    To allow only the form #number.numbers, you can use the following for instance:



    # test for matches on the regex expression. 
    if len(re.findall('^#d+.d+$', "#-1.30")) > 0:
    # It is valid
    return true





    share|improve this answer































      0














      Just as Torxed commented, you are comparing an object of the "list" type vs an object of the "int" type. This rises the error:
      "'<' not supported between instances of 'list' and 'int'."



      Yo should either validate user input before appending it to the list, or you could loop over the complete list to find wrong/right inputs.



      -Checking input before appending:



      if int(input("Enter pints collected for hour {}: ".format(hours))) > 1:
      #This is ok


      -Checking input with complete list



      for a in inputPints:
      if int(a) > 1:
      #a is OK.


      I reccomend you put those validations inside a try catch block, since the int() casting may break your code if it detects a non-castable character.



      Hope this helps!



      Regards






      share|improve this answer























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53438397%2fhow-to-validate-array-for-negative-and-alpha-input-in-python%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        0














        I think you should define your userInput() method like this …



        def userInput():
        for hour in hours:
        user_input = -1
        while user_input < 0:
        try:
        user_input = int(input("Enter pints collected for hour {}: ".format(hour)))
        except:
        user_input = -1
        if user_input > -1:
        inputPints.append(user_input)





        share|improve this answer




























          0














          I think you should define your userInput() method like this …



          def userInput():
          for hour in hours:
          user_input = -1
          while user_input < 0:
          try:
          user_input = int(input("Enter pints collected for hour {}: ".format(hour)))
          except:
          user_input = -1
          if user_input > -1:
          inputPints.append(user_input)





          share|improve this answer


























            0












            0








            0







            I think you should define your userInput() method like this …



            def userInput():
            for hour in hours:
            user_input = -1
            while user_input < 0:
            try:
            user_input = int(input("Enter pints collected for hour {}: ".format(hour)))
            except:
            user_input = -1
            if user_input > -1:
            inputPints.append(user_input)





            share|improve this answer













            I think you should define your userInput() method like this …



            def userInput():
            for hour in hours:
            user_input = -1
            while user_input < 0:
            try:
            user_input = int(input("Enter pints collected for hour {}: ".format(hour)))
            except:
            user_input = -1
            if user_input > -1:
            inputPints.append(user_input)






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 22 '18 at 22:17









            Red CricketRed Cricket

            4,389103384




            4,389103384

























                0














                You can use regex to validade your input.
                To allow only the form #number.numbers, you can use the following for instance:



                # test for matches on the regex expression. 
                if len(re.findall('^#d+.d+$', "#-1.30")) > 0:
                # It is valid
                return true





                share|improve this answer




























                  0














                  You can use regex to validade your input.
                  To allow only the form #number.numbers, you can use the following for instance:



                  # test for matches on the regex expression. 
                  if len(re.findall('^#d+.d+$', "#-1.30")) > 0:
                  # It is valid
                  return true





                  share|improve this answer


























                    0












                    0








                    0







                    You can use regex to validade your input.
                    To allow only the form #number.numbers, you can use the following for instance:



                    # test for matches on the regex expression. 
                    if len(re.findall('^#d+.d+$', "#-1.30")) > 0:
                    # It is valid
                    return true





                    share|improve this answer













                    You can use regex to validade your input.
                    To allow only the form #number.numbers, you can use the following for instance:



                    # test for matches on the regex expression. 
                    if len(re.findall('^#d+.d+$', "#-1.30")) > 0:
                    # It is valid
                    return true






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 22 '18 at 22:08









                    Pedro TorresPedro Torres

                    683413




                    683413























                        0














                        Just as Torxed commented, you are comparing an object of the "list" type vs an object of the "int" type. This rises the error:
                        "'<' not supported between instances of 'list' and 'int'."



                        Yo should either validate user input before appending it to the list, or you could loop over the complete list to find wrong/right inputs.



                        -Checking input before appending:



                        if int(input("Enter pints collected for hour {}: ".format(hours))) > 1:
                        #This is ok


                        -Checking input with complete list



                        for a in inputPints:
                        if int(a) > 1:
                        #a is OK.


                        I reccomend you put those validations inside a try catch block, since the int() casting may break your code if it detects a non-castable character.



                        Hope this helps!



                        Regards






                        share|improve this answer




























                          0














                          Just as Torxed commented, you are comparing an object of the "list" type vs an object of the "int" type. This rises the error:
                          "'<' not supported between instances of 'list' and 'int'."



                          Yo should either validate user input before appending it to the list, or you could loop over the complete list to find wrong/right inputs.



                          -Checking input before appending:



                          if int(input("Enter pints collected for hour {}: ".format(hours))) > 1:
                          #This is ok


                          -Checking input with complete list



                          for a in inputPints:
                          if int(a) > 1:
                          #a is OK.


                          I reccomend you put those validations inside a try catch block, since the int() casting may break your code if it detects a non-castable character.



                          Hope this helps!



                          Regards






                          share|improve this answer


























                            0












                            0








                            0







                            Just as Torxed commented, you are comparing an object of the "list" type vs an object of the "int" type. This rises the error:
                            "'<' not supported between instances of 'list' and 'int'."



                            Yo should either validate user input before appending it to the list, or you could loop over the complete list to find wrong/right inputs.



                            -Checking input before appending:



                            if int(input("Enter pints collected for hour {}: ".format(hours))) > 1:
                            #This is ok


                            -Checking input with complete list



                            for a in inputPints:
                            if int(a) > 1:
                            #a is OK.


                            I reccomend you put those validations inside a try catch block, since the int() casting may break your code if it detects a non-castable character.



                            Hope this helps!



                            Regards






                            share|improve this answer













                            Just as Torxed commented, you are comparing an object of the "list" type vs an object of the "int" type. This rises the error:
                            "'<' not supported between instances of 'list' and 'int'."



                            Yo should either validate user input before appending it to the list, or you could loop over the complete list to find wrong/right inputs.



                            -Checking input before appending:



                            if int(input("Enter pints collected for hour {}: ".format(hours))) > 1:
                            #This is ok


                            -Checking input with complete list



                            for a in inputPints:
                            if int(a) > 1:
                            #a is OK.


                            I reccomend you put those validations inside a try catch block, since the int() casting may break your code if it detects a non-castable character.



                            Hope this helps!



                            Regards







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 22 '18 at 22:29









                            Santiago PeronSantiago Peron

                            1




                            1






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53438397%2fhow-to-validate-array-for-negative-and-alpha-input-in-python%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                404 Error Contact Form 7 ajax form submitting

                                How to know if a Active Directory user can login interactively

                                TypeError: fit_transform() missing 1 required positional argument: 'X'