0

I am currently writing a program that needs to interpret user input and turn it into useable data. The number of words in data must be 4, 8, 12, or any multiple of 4. This is because of the format the user must follow while entering data- his input is actually just multiple sets of 4 words. As such, before I attempt to use the data, i want to check to make sure the user followed the format given properly, so I must check to see that the 0th, 4th and 8th place are 3 digit month, and that the 1st, 5th and 9th... you get the idea.

The problem is this: i don't want to check the 0th and 4th and 8th entry in the data, i want to check all the way up to 80 without writing the code to check 20 times.

An example input for this program:

JUL ENT 20 K AUG SAL 2 M MAR OTR 200 K

I am new to Python, so any suggestions would help immensely. Here is what i have written so far.

import re
data_input = input("Please input data.\n")
data_set = re.sub("[^\w]", " ", data_input).split()

data_ready_1 = False
def data_ready_function_1():
    if not len(data_set) % 4 == 0:
        print("That\'s not a valid input. For formatting help, type \'help\'.'")
        data_ready_1 = False
    else:
        data_ready_1 = True

number = len(data_set) // 4

def data_ready_function_2():
    if not (data_set[0]) == ("JAN" or "FEB" or "MAR" "APR" or "MAY" or "JUN" or "JUL" or "AUG" or "SEP" or "OCT" or "NOV" or "DEC"))
        print("That\'s not a valid input.'")

1 Answers1

0

For avoiding exhausting checks, you need to restructure your code to smaller parts and introduce control structures, such as while.

In my example I created two functions get_data_set() and check_months().

Function get_data_set() loops infinitely, until the input is correct. That means the number of words is divisible by 4 and every 4th word is a months name.

Function check_months() has one argument - data_set and checks it if every 4th word is month. If it is, returns True, in not False.

Example is bellow:

import re

def get_data_set():
    while True:
        data_input = input("Please input data.\n")
        data_set = re.sub(r"[^\w]", " ", data_input).split()
        if len(data_set) % 4 != 0:
            print("That\'s not a valid input. For formatting help, type \'help\'.'")
            continue
        if check_months(data_set) == False:
            print("That\'s not a valid input.'")
            continue
        return data_set

def check_months(data_set):
    for word in data_set[::4]:
        if word not in ("JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"):
            return False
    return True

data_set = get_data_set()
print('Valid data set!')
print(data_set)

Output:

Please input data.
JUL ENT 20 K AUG SAL 2 M MAR OTR 200 K
Valid data set!
['JUL', 'ENT', '20', 'K', 'AUG', 'SAL', '2', 'M', 'MAR', 'OTR', '200', 'K']
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91