0

I am a new user to Python and stuck on looping over input statements if the data entered is not correct. I am trying to improve my input statement in the code below. I am trying to get the input to loop back to the beginning and prompt the user to enter again if the entry is outside whats asked for.

The original working version was very simple and just looped 3 times (because i knew i only wanted 3 inputs) and then the program executed and finished. I am now trying to add some extra conditions in case the user makes spelling mistakes or wants to quit - but then be prompted by the input command again.

I have been getting repeated problems with the sample_string variable being out of scope outside the function. I then tried to declare it as a global variable, then the spacings were wrong - so that didnt work so any help/guidance appreciated.

Marked up code I have been trying to get to work with ################# symbol I have marked up the code that I have been trying to include between the #### symbol and aslo the code that I have been trying to replace. Any help or comments about code structure appreciated I have been going round in circles with this all day. Thankyou!!

from matplotlib import style
from matplotlib import pyplot as plt
import numpy as np
import csv
# import random used for changing line colors in chart
import random
from itertools import cycle

# opens a the input file and reads in the data
with open('Test_colours_in.csv', 'r') as csv_file:
    csv_reader = csv.DictReader(csv_file)
# prints list of unique values in column 5 of csv of input file
    my_list = set()
    for line in csv_reader:
        my_list.add(line['Name5'])
    print(my_list)

# takes these unique values and creates files associated with each unique value
    for item in my_list:
        with open(item + '_'+'Test.csv', 'w', newline='') as new_file:
            fieldnames = ['Name1', 'Name2', 'Name3', 'Name4', 'Name5', 'Name6', 'Name7', 'Name8']
            csv_writer = csv.DictWriter(new_file, fieldnames=fieldnames)
            csv_writer.writeheader()

# filters the original file for each item in the list of unique values and writes them to respective file
            csv_file.seek(0)  # Reposition to front of file
            filtered = filter(lambda r: r['Name5'] == item, csv_reader)
            for row in filtered:
                csv_writer.writerow(row)

# Section of code below plots data from each of the filtered files

#
    my_color_list = ['b', 'g', 'r', 'c', 'm', 'y', 'tab:blue', 'tab:orange', 'tab:purple', 'tab:gray', 'b', 'g', 'r',
                     'c', 'm', 'y', 'tab:blue', 'tab:orange', 'tab:purple', 'tab:gray']
# ###################################################################
# ### trying to get this to do the same as the current input commands
#     def get_input(prompt):
#         while True:
#             user_input = input(prompt).lower[0:1]
#             if user_input in ('apples', 'pears', 'oranges', 'q'):
#                 return user_input
#      print(get_input('Enter apples, oranges or q to quit'))
# #####################################################################
#
# ########To be replaced#####################################
# loops through 3 times because theres only 3 input values
    for i in range(3):
        # the user = int(0),int(1), int(2) values just assign a different column numnber
        # from the data file depending on whats inputs been entered , eg apples might
        # want the first column etc
        user_input = input('enter apples, pears or oranges, q to quit ?')
        sample_string = user_input
        if sample_string[:1] == 'q':
            break
        if sample_string[:1] == 'a':
            user = int(0)
        if sample_string[:1] == 'p':
            user = int(1)
        if sample_string[:1] == 'o':
            user = int(2)
# ######end of input#########################################################################

        for item in my_list:
            print(user)

            x, y = np.loadtxt(item + '_'+'Test.csv', skiprows=1, usecols=[0, user], unpack=True, delimiter=',')
            color = random.choice(my_color_list)
            plt.plot(x, y, color, label=item, linewidth=5)

            style.use('ggplot')

        plt.title('Data v Time')
        plt.ylabel('Data')
        plt.xlabel('Time seconds')

        plt.legend()
        plt.grid(True, color='k')
        plt.show()

made up input data file below

Name1,Name2,Name3,Name4,Name5,Name6,Name7,Name8 1,10,19,4,Blue,6,7,8 2,11,20,4,Blue,6,7,8 3,12,21,4,Blue,6,7,8 4,13,22,4,Green,6,7,8 5,14,23,4,Green,6,7,8 6,15,24,4,Blue,6,7,8 7,16,25,4,Blue,6,7,8 8,17,26,4,Yellow,6,7,8 9,18,27,4,Yellow,6,7,8

Sid
  • 153
  • 3
  • 15
  • You turn your `user_input` into a single letter string with `[0:1]` but then you check with a set of full words, not single letters. I think you actually want to check the full lowered words, not letters. – progmatico Apr 06 '20 at 16:24
  • I have changed the code to below – Sid Apr 06 '20 at 17:05
  • I have changed the function code to below – Sid Apr 06 '20 at 17:09
  • This looks like a duplicate question (about input data validation loops). Try to search Stack Overflow for similar questions. For example, take a look [here](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) for ideas. – progmatico Apr 07 '20 at 12:31

0 Answers0