Python - Preventing simple user Input errors with while loops.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • krec
    New Member
    • Oct 2016
    • 3

    Python - Preventing simple user Input errors with while loops.

    Hello everyone! Anticipating my thanks for reading. Well, on line 2 i was trying to prevent an user of inputing something different than 1,2,3,4,5,6. It works, yes, but...
    I was wondering if i could make it more simple. I first tried to do range(1,7) but it didn't work because it creates a list with [1,2,3,4,5,6] and not integers.
    I was wondering if someone could help me with this! Thank you once again


    Code:
    s_test_n = int(raw_input("How many tests did your student do?[1-6]:"))
            while s_test_n != 1 and s_test_n != 2 and s_test_n != 3 and s_test_n != 4 and s_test_n != 5 and s_test_n != 6:
                s_test_n = int(raw_input("Sorry but, how many tests did your student do?[1-6]:"))
  • dwblas
    Recognized Expert Contributor
    • May 2008
    • 626

    #2
    Using a list/range is the common way as it can include/accept anything you want, not just a range of numbers.
    Code:
    s_test_n=0
    include_list=range(1, 7)
    while s_test_n not in include_list:
        s_test_n=int(raw_input("How many tests did your student do?[1-6]:"))
    ##
    ##  or
    ##    while s_test_n < 1 or s_test_n > 6

    Comment

    • krec
      New Member
      • Oct 2016
      • 3

      #3
      Thanks for your generosity!!! You're a genius :D that was exactly what i was looking for :)

      Comment

      Working...