bpr
bpr

Reputation: 477

How do I put user inputted values into an array?

I am trying to put user named values into an array to be used later on. However, I get an infinite loop with my code so far... here's what I got:

def dates():
    dates = []
    user_input = raw_input("Please put folder with format yy.mm.dd: ")
    while user_input != 'end':
        if user_input == '%y.%m.%d':
            dates.append(user_input)
        else:
            print "Please out folder in form yy.mm.dd or write 'end'"
    print dates    

new function:

def date():
    dates = []
    user_input =raw_input("Please put folder with format yy.mm.dd: ")
    pattern = re.compile('\d{2}.\d{2}.\d{2}')
    if pattern.match(user_input):
        dates.append(user_input)
    elif user_input == 'end':
        print 'Dates:'
    else:
        print "Use yy.mm.dd format or write 'end'"

    return dates

Upvotes: 0

Views: 258

Answers (2)

miradulo
miradulo

Reputation: 29690

This is because you never request user input inside your while loop. As a result, it keeps evaluating your first user_input, and your user never has the opportunity to type 'end' and break out of the loop. Place another raw_input call within your while loop instead of your else string, in order to actually re-evaluate user input. This will ensure that if the format is correct, your user will be cued for another input as well.

Also, since you have a function dates(), you should return your result if that is the end of your function, not print it.

Finally, as your conditional statement currently stands the only valid match you will ever have is the literal string. You need to use regex or an actual pattern match in order to match valid inputs.

Upvotes: 1

Łukasz Rogalski
Łukasz Rogalski

Reputation: 23203

There are two issues in your code, first:

user_input = raw_input("Please put folder with format yy.mm.dd: ")

This input is evaluated only once, so either you go to infinite loop, or you add only one string to list.

Moreover,

user_input == '%y.%m.%d'

This comparision checks for string equality, not for pattern matching. You have two options, first to use regular expression to check validity of input string:

pattern = re.compile('\d{2}.\d{2}.\d{2}')
if pattern.match(user_input):
    pass # handle valid input
else:
    pass # handle invalid input

This option has a drawback as you'll be able to pass 00 or >12 for month, analogically for day bigger than 31 etc.

For me preferred way would be to use EAFP approach and try to create datetime.date object.

year, month, day = user_input.split('.')
try:
    date = datetime.date(int(year), int(month), int(day))
except ValueError:
    pass # handle invalid input
else:
    pass # handle valid input

Upvotes: 2

Related Questions