简体   繁体   English

如何根据用户输入创建变量? (Python)

[英]How do you create variables based on user input? (Python)

I want to create a program to automate my science assessments.我想创建一个程序来自动化我的科学评估。 Here is the code:这是代码:

from statistics import mean
import matplotlib.pyplot as plt
import numpy as np

independent = input("What is your independent variable?\nindependent(unit):  ")
dependent = input("What is your dependent variable?\ndependent(unit): ")
intervals = [int(x) for x in input(f"\nWhich {independent} values are you measuring? \nPlease seperate your answers with commas.: ").split(', ')]

try:
    intervals[0]
except IndexError:
    raise IndexError(f"PLease enter at least 5 {independent} values") from None

results1 = [int(x) for x in input(f"What are the results of {intervals[0]}: ").split(', ')]

try:
    intervals[1]
except IndexError:
    raise IndexError(f"PLease enter at least 5 {independent} values") from None

results2 = [int(x) for x in input(f"What are the results of {intervals[1]}: ").split(', ')]

try:
    intervals[2]
except IndexError:
    raise IndexError(f"PLease enter at least 5 {independent} values") from None

results3 = [int(x) for x in input(f"What are the results of {intervals[2]}: ").split(', ')]

try:
    intervals[3]
except IndexError:
    raise IndexError(f"PLease enter at least 5 {independent} values") from None

results4 = [int(x) for x in input(f"What are the results of {intervals[3]}: ").split(', ')]

try:
    intervals[4]
except IndexError:
    raise IndexError(f"PLease enter at least 5 {independent} values") from None

results5 = [int(x) for x in input(f"What are the results of {intervals[4]}: ").split(', ')]

# processing data
def average(a):
    return mean(a)

def range(list):
    list.sort()
    min = list[0]
    max = list[-1]
    return max - min


print(f"\nThe average of {intervals[0]} is {average(results1)}. The Range is {range(results1)}")
print(f"\nThe average of {intervals[1]} is {average(results2)}. The Range is {range(results2)}")
print(f"\nThe average of {intervals[2]} is {average(results3)}. The Range is {range(results3)}")
print(f"\nThe average of {intervals[3]} is {average(results4)}. The Range is {range(results4)}")
print(f"\nThe average of {intervals[4]} is {average(results5)}. The Range is {range(results5)}")

# graphing

y = np.array(intervals)
x = np.array([average(results1), average(results2), average(results3), average(results4), average(results5)])
xerrorbars = [range(results1) / 2, range(results2) / 2, range(results3) / 2, range(results4) / 2, range(results5) / 2]

def give_me_a_straight_line(x,y):
    w, b  = np.polyfit(x,y,deg=1)
    line  = w * x + b
    return line

line = give_me_a_straight_line(x,y)

plt.plot(x,y,'o')
plt.plot(x,line,'r--')

plt.errorbar(x, y, xerr=xerrorbars, fmt="o", color="blue")
plt.ylabel(independent)
plt.xlabel(dependent)
plt.grid()
plt.show()

As you can see, I have added error messages in case the user inputs less or more than 5 items in the variable intervals.如您所见,我添加了错误消息,以防用户在可变间隔中输入少于或多于 5 个项目。 This makes the program only useable if there are 5 items entered.这使得程序只有在输入 5 个项目时才可用。 This is bad because sometimes you might want to use only 4 or 3 intervals.这很糟糕,因为有时您可能只想使用 4 或 3 个间隔。 Is there a way to create a number of variables based on the items in the list intervals?.有没有办法根据列表间隔中的项目创建许多变量?

Use lists instead of plain variables.使用列表而不是普通变量。

minVals = 5

if len(intervals) < minVals:
    raise IndexError(f"Please enter at least 5 {independent} values")

results = []
for interval in intervals:
    results.append([int(x) for x in input(f"What are the results of {intervals[0]}: ").split(', ')])

print(f"\nThe average of {intervals[0]} is {average(results[0])}.")

While you can create variable variable names, it is a terrible idea most of the time as it will clutter your namespace, make it a nightmare to debug/modify and other nasty stuff.虽然您可以创建变量变量名称,但大多数情况下这是一个糟糕的主意,因为它会弄乱您的命名空间,使其成为调试/修改和其他讨厌的东西的噩梦。

Most of the time lists and dictionaries will do just the same thing with waaaay cleaner code.大多数情况下,列表和字典将使用 waaaay 更简洁的代码做同样的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在python中从原始输入创建多个变量? - How do you create multiple variables from raw input in python? 如何根据 Python 中的用户输入设置变量的值? - How do you set the value of a variable based on user input in Python? 您可以根据用户输入动态创建 python function 吗? - Can you dynamically create a python function, based on user input? 如何基于用户输入创建正则表达式(Python) - How to create a Regex based on user input (Python) 如何根据用户输入创建不同的变量 - How to create different variables based off user input 您如何在python中创建一个自定义异常来处理用户输入,并考虑帐户中的值范围? - How do you create a custom exception that handles user input taking range of values in account, in python? 我如何创建一个函数,该函数根据在Python中输入相同输入的次数,使用户输入具有不同的结果? - How do I create a function that allows for user input to have a different outcomes based on how many times the same input was entered in Python? Python 3.4如何限制用户输入 - Python 3.4 How do you limit user input 您如何要求用户在Python上输入矩阵? - How do you ask a user to input a matrix on Python? 如何在 vscode 中的 python 中获得用户输入? - How do you get a user input in python in vscode?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM