python - 如何使用函数调用在 Python 中循环 INPUT 语句
问题描述
我是 Python 的新用户,如果输入的数据不正确,我会坚持循环输入语句。我正在尝试改进下面代码中的输入语句。我试图让输入循环回到开头并提示用户再次输入,如果该条目超出了所要求的范围。
最初的工作版本非常简单,只循环了 3 次(因为我知道我只想要 3 个输入),然后程序执行并完成。我现在尝试添加一些额外的条件,以防用户出现拼写错误或想要退出 - 但随后输入命令再次提示。
我一直在重复出现 sample_string 变量超出函数范围的问题。然后我试图将它声明为一个全局变量,然后间距是错误的 - 所以没有工作所以任何帮助/指导表示赞赏。
标记代码我一直在尝试使用################# 符号我已经标记了我一直试图包含在#### 符号之间的代码以及我一直试图替换的代码。任何关于代码结构的帮助或评论都值得赞赏,我整天都在绕圈子。谢谢!!
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()
组成下面的输入数据文件
Name1,Name2,Name3,Name4,Name5,Name6,Name7,Name8 1,10,19,4,蓝色,6,7,8 2,11,20,4,蓝色,6,7,8 3,12,21 ,4,蓝色,6,7,8 4,13,22,4,绿色,6,7,8 5,14,23,4,绿色,6,7,8 6,15,24,4,蓝色, 6,7,8 7,16,25,4,蓝色,6,7,8 8,17,26,4,黄色,6,7,8 9,18,27,4,黄色,6,7,8
解决方案
推荐阅读
- reactjs - 删除 firebase 数据库中的值后无法重新呈现页面。This.setState 不起作用
- angular - 我无法将值设置为 formArray
- excel - 将 weeknum 放入数组中?
- go - 从 fmt.Printf 更改为 exec.Command
- c# - 从 C# 应用程序运行批处理
- statistics - 应针对单个条件进行哪些统计分析
- javascript - 父组件的状态更新是否确保在 ReactJS 中重新安装子组件?
- c# - 如果使用 Solr.NET 将 .NET Core 与 Solr 连接,如何修复“远程服务器返回错误:(404) Not Found”
- sql-server - 创建同步组超时
- python - 以下函数不提供任何输出