简体   繁体   中英

How can I make raw_input tolerance more robust in Python 2.7?

I'm new here and to programming so please take it easy. I understand that almost anybody reading this knows more than I do and that I'm probably doing it wrong.

That being said, this is what I'm trying to do:

while True:
    arrival = raw_input('Arrival time? Example 8:30 \n')

    if  arrival != "%s%s:%s%s" % (range(0, 1), range(0, 10), range(0, 7), range(0, 10):

        arrival = raw_input('Follow the example: 8:30 \n)
        break

    elif arrival == "q":
        print "escape velocity reached!!!"
        return 0

The "if" statement doesn't have proper syntax and I don't even know if this is how one should/would go about writing this code in the first place. Basically, I would like the user input to be in the format 1:11 or 11:11, or my code breaks. Please ignore elif, its just there to break the loop while I'm testing.

Main question:

  1. How can I fix this code or the implement the idea behind this code?

Related questions:

  1. How can I get python to accept many different possible combinations of "properly" formatted strings (XX:XX or X:XX)?

  2. What is a better way to coerce somebody into inputting data within a range of tolerance in a specific format or increase raw_input tolerance?

  3. What is a better way to do all of the above or is there a better way to approach this problem?

Thank you in advance!

ps

  1. I know that the only way to get a good answer is to ask a good question... Any tips on better question formatting appreciated as well.

Here's how I would do this:

  • Use time.strptime to parse the time. A format string of '%H:%M' works OK for your example, you could get more specific or try to support multiple formats if you need to.
  • Use try/except to deal with input that can't be parsed properly. strptime will raise a ValueError if the format doesn't match, so you use except to deal with that
  • Set the time_ok flag to True (and therefore exit the while loop) once we've got a time that can be parsed.

Code:

import time

time_ok = False
while not time_ok:
    arrival = raw_input('Arrival time? Example 8:30 \n')
    if arrival == 'q':
        print("Exiting.")
        break
    # Try to parse the entered time
    try:
        time_data = time.strptime(arrival, '%H:%M')
        time_ok = True
    # If the format doesn't match, print a warning
    # and go back through the while loop
    except ValueError:
        print('Follow the example: 8:30 \n')

hours, minutes = time_data.tm_hour, time_data.tm_min
print(hours, minutes)

If I'm understanding you right you want people to enter a time from 0:00 to 11:59. All you have to do is something like the following

while True:
    arrival = raw_input("Please enter a time in the format hr:min (such as 8:30)")
    if ":" not in arrival:
        print("Please enter a time in the format hour:minute")
        continue
    else:
        arrival_list = arrival.split(":")
        if (int(arrival_list[0]) not in range(12)) or
           (int(arrival_list[1]) not in range(60)):
            print("Please enter a valid hour from 0-12 and a valid minute from 0-59")
        else: 
            break

This will keep your loop going until you have a properly formatted time given as an input.

From an overall, general programming point of view I think using the time module is probably better, but I tried to keep this to what I estimated was your skill level.

You will want to use regular expressions to match the input:

import re

format_ok = False
while format_ok:
    arrival = raw_input('Arrival time? Example 8:30 \n')
    if re.match("\d{1,2}:\d{2}", arrival):
        #string format is OK - break the loop
        format_ok = True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM